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
Ast.fst
Ast.with_dummy_range
val with_dummy_range : x: _ -> Ast.with_meta_t _
let with_dummy_range x = with_range x dummy_range
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 49, "end_line": 782, "start_col": 0, "start_line": 782 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
x: _ -> Ast.with_meta_t _
Prims.Tot
[ "total" ]
[]
[ "Ast.with_range", "Ast.dummy_range", "Ast.with_meta_t" ]
[]
false
false
false
true
false
let with_dummy_range x =
with_range x dummy_range
false
Ast.fst
Ast.to_ident'
val to_ident' : x: Prims.string -> Ast.ident'
let to_ident' x = {modul_name=None;name=x}
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 42, "end_line": 783, "start_col": 0, "start_line": 783 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
x: Prims.string -> Ast.ident'
Prims.Tot
[ "total" ]
[]
[ "Prims.string", "Ast.Mkident'", "FStar.Pervasives.Native.None", "Ast.ident'" ]
[]
false
false
false
true
false
let to_ident' x =
{ modul_name = None; name = x }
false
Ast.fst
Ast.tuint8
val tuint8 : Ast.with_meta_t Ast.typ'
let tuint8 = mk_prim_t "UINT8"
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 30, "end_line": 787, "start_col": 0, "start_line": 787 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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.with_meta_t Ast.typ'
Prims.Tot
[ "total" ]
[]
[ "Ast.mk_prim_t" ]
[]
false
false
false
true
false
let tuint8 =
mk_prim_t "UINT8"
false
Ast.fst
Ast.tcopybuffer
val tcopybuffer : Ast.with_meta_t Ast.typ'
let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T"
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 53, "end_line": 793, "start_col": 0, "start_line": 793 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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.with_meta_t Ast.typ'
Prims.Tot
[ "total" ]
[]
[ "Ast.mk_prim_t" ]
[]
false
false
false
true
false
let tcopybuffer =
mk_prim_t "EVERPARSE_COPY_BUFFER_T"
false
Ast.fst
Ast.unit_atomic_field
val unit_atomic_field : rng: Ast.range -> Ast.with_meta_t Ast.atomic_field'
let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 20, "end_line": 807, "start_col": 0, "start_line": 795 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
rng: Ast.range -> Ast.with_meta_t Ast.atomic_field'
Prims.Tot
[ "total" ]
[]
[ "Ast.range", "Ast.with_range", "Ast.atomic_field'", "Ast.Mkatomic_field'", "Ast.tunit", "Ast.FieldScalar", "FStar.Pervasives.Native.None", "Ast.expr", "Ast.field_bitwidth_t", "FStar.Pervasives.Native.tuple2", "Ast.action", "Prims.bool", "Ast.probe_call", "Ast.with_meta_t", "Ast.ident'", "Ast.to_ident'" ]
[]
false
false
false
true
false
let unit_atomic_field rng =
let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence = false; field_ident = dummy_identifier; field_type = tunit; field_array_opt = FieldScalar; field_constraint = None; field_bitwidth = None; field_action = None; field_probe = None } in with_range f rng
false
Ast.fst
Ast.tunknown
val tunknown : Ast.with_meta_t Ast.typ'
let tunknown = mk_prim_t "?"
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 28, "end_line": 794, "start_col": 0, "start_line": 794 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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.with_meta_t Ast.typ'
Prims.Tot
[ "total" ]
[]
[ "Ast.mk_prim_t" ]
[]
false
false
false
true
false
let tunknown =
mk_prim_t "?"
false
Ast.fst
Ast.action_has_out_expr
val action_has_out_expr (a: action) : Tot bool
val action_has_out_expr (a: action) : Tot bool
let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 25, "end_line": 663, "start_col": 0, "start_line": 645 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
a: Ast.action -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "Ast.action", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.action'", "Ast.atomic_action", "Ast.atomic_action_has_out_expr", "Ast.with_meta_t", "Prims.bool", "Ast.action_has_out_expr", "Ast.expr", "Ast.ident" ]
[ "recursion" ]
false
false
false
true
false
let rec action_has_out_expr (a: action) : Tot bool =
match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a
false
Ast.fst
Ast.field_action_has_out_expr
val field_action_has_out_expr (f: option (action & bool)) : Tot bool
val field_action_has_out_expr (f: option (action & bool)) : Tot bool
let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 40, "end_line": 670, "start_col": 0, "start_line": 665 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: FStar.Pervasives.Native.option (Ast.action * Prims.bool) -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "FStar.Pervasives.Native.option", "FStar.Pervasives.Native.tuple2", "Ast.action", "Prims.bool", "Ast.action_has_out_expr" ]
[]
false
false
false
true
false
let field_action_has_out_expr (f: option (action & bool)) : Tot bool =
match f with | None -> false | Some (a, _) -> action_has_out_expr a
false
Ast.fst
Ast.subst_atomic_action
val subst_atomic_action (s: subst) (aa: atomic_action) : ML atomic_action
val subst_atomic_action (s: subst) (aa: atomic_action) : ML atomic_action
let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 11, "end_line": 839, "start_col": 0, "start_line": 834 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> aa: Ast.atomic_action -> FStar.All.ML Ast.atomic_action
FStar.All.ML
[ "ml" ]
[]
[ "Ast.subst", "Ast.atomic_action", "Ast.expr", "Ast.Action_return", "Ast.subst_expr", "Ast.out_expr", "Ast.Action_assignment", "Ast.ident", "Prims.list", "Ast.Action_call", "FStar.List.map" ]
[]
false
true
false
false
false
let subst_atomic_action (s: subst) (aa: atomic_action) : ML atomic_action =
match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa
false
Ast.fst
Ast.eq_typ_params
val eq_typ_params (ps1 ps2: list typ_param) : bool
val eq_typ_params (ps1 ps2: list typ_param) : bool
let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 14, "end_line": 768, "start_col": 0, "start_line": 764 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
ps1: Prims.list Ast.typ_param -> ps2: Prims.list Ast.typ_param -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Ast.typ_param", "FStar.Pervasives.Native.Mktuple2", "Prims.op_AmpAmp", "Ast.eq_typ_param", "Ast.eq_typ_params", "FStar.Pervasives.Native.tuple2", "Prims.bool" ]
[ "recursion" ]
false
false
false
true
false
let rec eq_typ_params (ps1 ps2: list typ_param) : bool =
match ps1, ps2 with | [], [] -> true | p1 :: ps1, p2 :: ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false
false
Ast.fst
Ast.field_has_out_expr
val field_has_out_expr (f: field) : Tot bool
val field_has_out_expr (f: field) : Tot bool
let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 24, "end_line": 712, "start_col": 0, "start_line": 678 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.field -> Prims.bool
Prims.Tot
[ "total" ]
[ "field_has_out_expr", "record_has_out_expr", "switch_case_has_out_expr", "cases_have_out_expr", "case_has_out_expr" ]
[ "Ast.field", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.field'", "Ast.with_meta_t", "Ast.atomic_field'", "Ast.atomic_field_has_out_expr", "Prims.list", "Ast.ident", "Ast.record_has_out_expr", "FStar.Pervasives.Native.tuple2", "Ast.expr", "Ast.case", "Ast.switch_case_has_out_expr", "Prims.bool" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec field_has_out_expr (f: field) : Tot bool =
match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw
false
Ast.fst
Ast.eq_expr
val eq_expr (e1 e2: expr) : Tot bool (decreases e1)
val eq_expr (e1 e2: expr) : Tot bool (decreases e1)
let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 14, "end_line": 742, "start_col": 0, "start_line": 728 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.expr -> e2: Ast.expr -> Prims.Tot Prims.bool
Prims.Tot
[ "total", "" ]
[ "eq_expr", "eq_exprs" ]
[ "Ast.expr", "FStar.Pervasives.Native.Mktuple2", "Ast.expr'", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.constant", "Prims.op_Equality", "Ast.ident", "Ast.ident'", "Ast.op", "Prims.list", "Ast.with_meta_t", "Prims.op_AmpAmp", "Ast.eq_exprs", "FStar.Pervasives.Native.tuple2", "Prims.bool" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec eq_expr (e1 e2: expr) : Tot bool (decreases e1) =
match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false
false
Ast.fst
Ast.subst_out_expr
val subst_out_expr (s: subst) (o: out_expr) : out_expr
val subst_out_expr (s: subst) (o: out_expr) : out_expr
let subst_out_expr (s:subst) (o:out_expr) : out_expr = o
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 56, "end_line": 853, "start_col": 0, "start_line": 853 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> o: Ast.out_expr -> Ast.out_expr
Prims.Tot
[ "total" ]
[]
[ "Ast.subst", "Ast.out_expr" ]
[]
false
false
false
true
false
let subst_out_expr (s: subst) (o: out_expr) : out_expr =
o
false
Ast.fst
Ast.eq_idents
val eq_idents (i1 i2: ident) : Tot bool
val eq_idents (i1 i2: ident) : Tot bool
let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 60, "end_line": 745, "start_col": 0, "start_line": 744 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
i1: Ast.ident -> i2: Ast.ident -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "Ast.ident", "Prims.op_AmpAmp", "Prims.op_Equality", "FStar.Pervasives.Native.option", "Prims.string", "Ast.__proj__Mkident'__item__modul_name", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.ident'", "Ast.__proj__Mkident'__item__name", "Prims.bool" ]
[]
false
false
false
true
false
let eq_idents (i1 i2: ident) : Tot bool =
i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name
false
Ast.fst
Ast.eq_out_expr
val eq_out_expr (o1 o2: out_expr) : bool
val eq_out_expr (o1 o2: out_expr) : bool
let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 14, "end_line": 756, "start_col": 0, "start_line": 749 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
o1: Ast.out_expr -> o2: Ast.out_expr -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "Ast.out_expr", "FStar.Pervasives.Native.Mktuple2", "Ast.out_expr'", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.__proj__Mkout_expr__item__out_expr_node", "Ast.ident", "Ast.eq_idents", "Ast.eq_out_expr", "Prims.op_AmpAmp", "FStar.Pervasives.Native.tuple2", "Prims.bool" ]
[ "recursion" ]
false
false
false
true
false
let rec eq_out_expr (o1 o2: out_expr) : bool =
match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false
false
Ast.fst
Ast.eq_typ
val eq_typ (t1 t2: typ) : Tot bool
val eq_typ (t1 t2: typ) : Tot bool
let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 14, "end_line": 778, "start_col": 0, "start_line": 770 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
t1: Ast.typ -> t2: Ast.typ -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "Ast.typ", "FStar.Pervasives.Native.Mktuple2", "Ast.typ'", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.ident", "Ast.t_kind", "Prims.list", "Ast.either", "Ast.expr", "Ast.out_expr", "Prims.op_AmpAmp", "Ast.eq_idents", "Prims.op_Equality", "Ast.eq_typ_params", "Ast.with_meta_t", "Ast.eq_typ", "FStar.Pervasives.Native.tuple2", "Prims.bool" ]
[ "recursion" ]
false
false
false
true
false
let rec eq_typ (t1 t2: typ) : Tot bool =
match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false
false
Ast.fst
Ast.record_has_out_expr
val record_has_out_expr (fs: record) : Tot bool
val record_has_out_expr (fs: record) : Tot bool
let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 24, "end_line": 712, "start_col": 0, "start_line": 678 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
fs: Ast.record -> Prims.bool
Prims.Tot
[ "total" ]
[ "field_has_out_expr", "record_has_out_expr", "switch_case_has_out_expr", "cases_have_out_expr", "case_has_out_expr" ]
[ "Ast.record", "Ast.with_meta_t", "Ast.field'", "Prims.list", "Ast.field_has_out_expr", "Prims.bool", "Ast.record_has_out_expr" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec record_has_out_expr (fs: record) : Tot bool =
match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs'
false
Ast.fst
Ast.eq_exprs
val eq_exprs (es1 es2: list expr) : Tot bool
val eq_exprs (es1 es2: list expr) : Tot bool
let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 14, "end_line": 742, "start_col": 0, "start_line": 728 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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 Ast.expr -> es2: Prims.list Ast.expr -> Prims.bool
Prims.Tot
[ "total" ]
[ "eq_expr", "eq_exprs" ]
[ "Prims.list", "Ast.expr", "FStar.Pervasives.Native.Mktuple2", "Prims.op_AmpAmp", "Ast.eq_expr", "Ast.eq_exprs", "FStar.Pervasives.Native.tuple2", "Prims.bool" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec eq_exprs (es1 es2: list expr) : Tot bool =
match es1, es2 with | [], [] -> true | hd1 :: es1, hd2 :: es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false
false
Ast.fst
Ast.cases_have_out_expr
val cases_have_out_expr (cs: list case) : Tot bool
val cases_have_out_expr (cs: list case) : Tot bool
let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 24, "end_line": 712, "start_col": 0, "start_line": 678 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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 Ast.case -> Prims.bool
Prims.Tot
[ "total" ]
[ "field_has_out_expr", "record_has_out_expr", "switch_case_has_out_expr", "cases_have_out_expr", "case_has_out_expr" ]
[ "Prims.list", "Ast.case", "Ast.case_has_out_expr", "Prims.bool", "Ast.cases_have_out_expr" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec cases_have_out_expr (cs: list case) : Tot bool =
match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs
false
Ast.fst
Ast.subst_params
val subst_params (s: subst) (p: list param) : ML (list param)
val subst_params (s: subst) (p: list param) : ML (list param)
let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 51, "end_line": 897, "start_col": 0, "start_line": 896 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case =
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> p: Prims.list Ast.param -> FStar.All.ML (Prims.list Ast.param)
FStar.All.ML
[ "ml" ]
[]
[ "Ast.subst", "Prims.list", "Ast.param", "FStar.List.map", "FStar.Pervasives.Native.tuple3", "Ast.typ", "Ast.ident", "Ast.qualifier", "FStar.Pervasives.Native.Mktuple3", "Ast.subst_typ" ]
[]
false
true
false
false
false
let subst_params (s: subst) (p: list param) : ML (list param) =
List.map (fun (t, i, q) -> subst_typ s t, i, q) p
false
Ast.fst
Ast.map_opt
val map_opt (f: ('a -> ML 'b)) (o: option 'a) : ML (option 'b)
val map_opt (f: ('a -> ML 'b)) (o: option 'a) : ML (option 'b)
let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 24, "end_line": 812, "start_col": 0, "start_line": 809 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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 'b) -> o: FStar.Pervasives.Native.option 'a -> FStar.All.ML (FStar.Pervasives.Native.option 'b)
FStar.All.ML
[ "ml" ]
[]
[ "FStar.Pervasives.Native.option", "FStar.Pervasives.Native.None", "FStar.Pervasives.Native.Some" ]
[]
false
true
false
false
false
let map_opt (f: ('a -> ML 'b)) (o: option 'a) : ML (option 'b) =
match o with | None -> None | Some x -> Some (f x)
false
Ast.fst
Ast.case_has_out_expr
val case_has_out_expr (c: case) : Tot bool
val case_has_out_expr (c: case) : Tot bool
let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 24, "end_line": 712, "start_col": 0, "start_line": 678 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
c: Ast.case -> Prims.bool
Prims.Tot
[ "total" ]
[ "field_has_out_expr", "record_has_out_expr", "switch_case_has_out_expr", "cases_have_out_expr", "case_has_out_expr" ]
[ "Ast.case", "Ast.expr", "Ast.with_meta_t", "Ast.field'", "Ast.field_has_out_expr", "Prims.bool" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec case_has_out_expr (c: case) : Tot bool =
match c with | Case _ f | DefaultCase f -> field_has_out_expr f
false
Ast.fst
Ast.subst
val subst : Type0
let subst = H.t ident' expr
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 27, "end_line": 818, "start_col": 0, "start_line": 818 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions ////////////////////////////////////////////////////////////////////////////////
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
Type0
Prims.Tot
[ "total" ]
[]
[ "Hashtable.t", "Ast.ident'", "Ast.expr" ]
[]
false
false
false
true
true
let subst =
H.t ident' expr
false
Ast.fst
Ast.print_ident
val print_ident : i: Ast.ident -> Prims.string
let print_ident (i:ident) = ident_to_string i
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 45, "end_line": 935, "start_col": 0, "start_line": 935 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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", "Ast.ident_to_string", "Prims.string" ]
[]
false
false
false
true
false
let print_ident (i: ident) =
ident_to_string i
false
Hacl.Test.HMAC_DRBG.fst
Hacl.Test.HMAC_DRBG.compare_and_print
val compare_and_print: b1:B.buffer UInt8.t -> b2:B.buffer UInt8.t -> len:UInt32.t -> Stack bool (requires fun h0 -> B.live h0 b1 /\ B.live h0 b2 /\ B.length b1 == v len /\ B.length b2 == v len) (ensures fun h0 _ h1 -> B.modifies B.loc_none h0 h1)
val compare_and_print: b1:B.buffer UInt8.t -> b2:B.buffer UInt8.t -> len:UInt32.t -> Stack bool (requires fun h0 -> B.live h0 b1 /\ B.live h0 b2 /\ B.length b1 == v len /\ B.length b2 == v len) (ensures fun h0 _ h1 -> B.modifies B.loc_none h0 h1)
let compare_and_print b1 b2 len = push_frame(); LowStar.Printf.(printf "Expected: %xuy\n" len b1 done); LowStar.Printf.(printf "Computed: %xuy\n" len b2 done); let b = Lib.ByteBuffer.lbytes_eq #len b1 b2 in if b then LowStar.Printf.(printf "PASS\n" done) else LowStar.Printf.(printf "FAIL\n" done); pop_frame(); b
{ "file_name": "code/tests/Hacl.Test.HMAC_DRBG.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 3, "end_line": 50, "start_col": 0, "start_line": 40 }
module Hacl.Test.HMAC_DRBG open FStar.HyperStack.ST open Test.Lowstarize open Lib.IntTypes open Hacl.HMAC_DRBG open Spec.HMAC_DRBG.Test.Vectors module D = Spec.Hash.Definitions module L = Test.Lowstarize module B = LowStar.Buffer #set-options "--fuel 0 --ifuel 0 --z3rlimit 100" (* FStar.Reflection only supports up to 8-tuples *) noextract let vectors_tmp = List.Tot.map (fun x -> x.a, h x.entropy_input, h x.nonce, h x.personalization_string, h x.entropy_input_reseed, h x.additional_input_reseed, (h x.additional_input_1, h x.additional_input_2), h x.returned_bits) test_vectors %splice[vectors_low] (lowstarize_toplevel "vectors_tmp" "vectors_low") // Cheap alternative to friend Lib.IntTypes needed because Test.Lowstarize uses UInt8.t assume val declassify_uint8: squash (uint8 == UInt8.t) let vec8 = L.lbuffer UInt8.t let vector = D.hash_alg & vec8 & vec8 & vec8 & vec8 & vec8 & (vec8 & vec8) & vec8 // This could replace TestLib.compare_and_print val compare_and_print: b1:B.buffer UInt8.t -> b2:B.buffer UInt8.t -> len:UInt32.t -> Stack bool (requires fun h0 -> B.live h0 b1 /\ B.live h0 b2 /\ B.length b1 == v len /\ B.length b2 == v len)
{ "checked_file": "/", "dependencies": [ "Test.Lowstarize.fst.checked", "Spec.HMAC_DRBG.Test.Vectors.fst.checked", "Spec.HMAC_DRBG.fsti.checked", "Spec.Hash.Definitions.fst.checked", "prims.fst.checked", "LowStar.Printf.fst.checked", "LowStar.BufferOps.fst.checked", "LowStar.Buffer.fst.checked", "Lib.IntTypes.fsti.checked", "Lib.ByteBuffer.fsti.checked", "Hacl.HMAC_DRBG.fsti.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.Int32.fsti.checked", "FStar.HyperStack.ST.fsti.checked", "C.String.fsti.checked", "C.Loops.fst.checked", "C.fst.checked" ], "interface_file": false, "source_file": "Hacl.Test.HMAC_DRBG.fst" }
[ { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": true, "full_module": "Test.Lowstarize", "short_module": "L" }, { "abbrev": true, "full_module": "Spec.Hash.Definitions", "short_module": "D" }, { "abbrev": false, "full_module": "Spec.HMAC_DRBG.Test.Vectors", "short_module": null }, { "abbrev": false, "full_module": "Hacl.HMAC_DRBG", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "Test.Lowstarize", "short_module": null }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "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
b1: LowStar.Buffer.buffer FStar.UInt8.t -> b2: LowStar.Buffer.buffer FStar.UInt8.t -> len: FStar.UInt32.t -> FStar.HyperStack.ST.Stack Prims.bool
FStar.HyperStack.ST.Stack
[]
[]
[ "LowStar.Buffer.buffer", "FStar.UInt8.t", "FStar.UInt32.t", "Prims.bool", "Prims.unit", "FStar.HyperStack.ST.pop_frame", "LowStar.Printf.printf", "LowStar.Printf.done", "Lib.ByteBuffer.lbytes_eq", "LowStar.Buffer.trivial_preorder", "FStar.HyperStack.ST.push_frame" ]
[]
false
true
false
false
false
let compare_and_print b1 b2 len =
push_frame (); (let open LowStar.Printf in printf "Expected: %xuy\n" len b1 done); (let open LowStar.Printf in printf "Computed: %xuy\n" len b2 done); let b = Lib.ByteBuffer.lbytes_eq #len b1 b2 in if b then let open LowStar.Printf in printf "PASS\n" done else (let open LowStar.Printf in printf "FAIL\n" done); pop_frame (); b
false
Ast.fst
Ast.mk_subst
val mk_subst (s: list (ident * expr)) : ML subst
val mk_subst (s: list (ident * expr)) : ML subst
let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 3, "end_line": 822, "start_col": 0, "start_line": 819 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Prims.list (Ast.ident * Ast.expr) -> FStar.All.ML Ast.subst
FStar.All.ML
[ "ml" ]
[]
[ "Prims.list", "FStar.Pervasives.Native.tuple2", "Ast.ident", "Ast.expr", "Ast.subst", "Prims.unit", "FStar.List.iter", "Ast.with_meta_t", "Ast.ident'", "Hashtable.insert", "Ast.__proj__Mkwith_meta_t__item__v", "Hashtable.t", "Hashtable.create" ]
[]
false
true
false
false
false
let mk_subst (s: list (ident * expr)) : ML subst =
let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h
false
Ast.fst
Ast.typ_as_integer_type
val typ_as_integer_type (t: typ) : ML integer_type
val typ_as_integer_type (t: typ) : ML integer_type
let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 74, "end_line": 1055, "start_col": 0, "start_line": 1052 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.typ -> FStar.All.ML Ast.integer_type
FStar.All.ML
[ "ml" ]
[]
[ "Ast.typ", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.typ'", "Ast.ident", "Ast.t_kind", "Ast.as_integer_typ", "Ast.integer_type", "Ast.error", "Ast.__proj__Mkwith_meta_t__item__range", "Prims.string", "Prims.op_Hat", "Ast.print_typ" ]
[]
false
true
false
false
false
let typ_as_integer_type (t: typ) : ML integer_type =
match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range
false
Ast.fst
Ast.switch_case_has_out_expr
val switch_case_has_out_expr (sw: switch_case) : Tot bool
val switch_case_has_out_expr (sw: switch_case) : Tot bool
let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 24, "end_line": 712, "start_col": 0, "start_line": 678 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
sw: Ast.switch_case -> Prims.bool
Prims.Tot
[ "total" ]
[ "field_has_out_expr", "record_has_out_expr", "switch_case_has_out_expr", "cases_have_out_expr", "case_has_out_expr" ]
[ "Ast.switch_case", "Ast.expr", "Prims.list", "Ast.case", "Ast.cases_have_out_expr", "Prims.bool" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec switch_case_has_out_expr (sw: switch_case) : Tot bool =
let _, c = sw in cases_have_out_expr c
false
Ast.fst
Ast.subst_decl
val subst_decl (s: subst) (d: decl) : ML decl
val subst_decl (s: subst) (d: decl) : ML decl
let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 86, "end_line": 913, "start_col": 0, "start_line": 913 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> d: Ast.decl -> FStar.All.ML Ast.decl
FStar.All.ML
[ "ml" ]
[]
[ "Ast.subst", "Ast.decl", "Ast.decl_with_v", "Ast.decl'", "Ast.subst_decl'", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.__proj__Mkdecl__item__d_decl" ]
[]
false
true
false
false
false
let subst_decl (s: subst) (d: decl) : ML decl =
decl_with_v d (subst_decl' s d.d_decl.v)
false
Ast.fst
Ast.bit_order_of_typ
val bit_order_of_typ (t: typ) : ML bitfield_bit_order
val bit_order_of_typ (t: typ) : ML bitfield_bit_order
let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 74, "end_line": 1060, "start_col": 0, "start_line": 1057 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.typ -> FStar.All.ML Ast.bitfield_bit_order
FStar.All.ML
[ "ml" ]
[]
[ "Ast.typ", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.typ'", "Ast.ident", "Ast.t_kind", "Ast.bit_order_of", "Ast.bitfield_bit_order", "Ast.error", "Ast.__proj__Mkwith_meta_t__item__range", "Prims.string", "Prims.op_Hat", "Ast.print_typ" ]
[]
false
true
false
false
false
let bit_order_of_typ (t: typ) : ML bitfield_bit_order =
match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range
false
Ast.fst
Ast.print_params
val print_params : ps: Prims.list Ast.param -> FStar.All.ALL Prims.string
let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p))))
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 33, "end_line": 1077, "start_col": 0, "start_line": 1066 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> ""
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
ps: Prims.list Ast.param -> FStar.All.ALL Prims.string
FStar.All.ALL
[]
[]
[ "Prims.list", "Ast.param", "Prims.string", "FStar.Printf.sprintf", "FStar.String.concat", "FStar.List.map", "FStar.Pervasives.Native.tuple3", "Ast.with_meta_t", "Ast.typ'", "Ast.ident", "Ast.qualifier", "Ast.print_ident", "Ast.print_qual", "Ast.print_typ" ]
[]
false
true
false
false
false
let print_params (ps: list param) =
match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p))))
false
Ast.fst
Ast.subst_expr
val subst_expr (s: subst) (e: expr) : ML expr
val subst_expr (s: subst) (e: expr) : ML expr
let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)}
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 65, "end_line": 833, "start_col": 0, "start_line": 827 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> e: Ast.expr -> FStar.All.ML Ast.expr
FStar.All.ML
[ "ml" ]
[]
[ "Ast.subst", "Ast.expr", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.expr'", "Ast.constant", "Ast.ident", "Ast.apply", "Ast.with_meta_t", "Ast.Mkwith_meta_t", "Ast.__proj__Mkwith_meta_t__item__range", "Ast.__proj__Mkwith_meta_t__item__comments", "Ast.Static", "Ast.subst_expr", "Ast.op", "Prims.list", "Ast.App", "FStar.List.map" ]
[ "recursion" ]
false
true
false
false
false
let rec subst_expr (s: subst) (e: expr) : ML expr =
match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> { e with v = App op (List.map (subst_expr s) es) }
false
Ast.fst
Ast.apply
val apply (s: subst) (id: ident) : ML expr
val apply (s: subst) (id: ident) : ML expr
let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 15, "end_line": 826, "start_col": 0, "start_line": 823 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s;
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> id: Ast.ident -> FStar.All.ML Ast.expr
FStar.All.ML
[ "ml" ]
[]
[ "Ast.subst", "Ast.ident", "Ast.with_range", "Ast.expr'", "Ast.Identifier", "Ast.__proj__Mkwith_meta_t__item__range", "Ast.ident'", "Ast.expr", "FStar.Pervasives.Native.option", "Hashtable.try_find", "Ast.__proj__Mkwith_meta_t__item__v" ]
[]
false
true
false
false
false
let apply (s: subst) (id: ident) : ML expr =
match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e
false
Ast.fst
Ast.subst_field_array
val subst_field_array (s: subst) (f: field_array_t) : ML field_array_t
val subst_field_array (s: subst) (f: field_array_t) : ML field_array_t
let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 24, "end_line": 867, "start_col": 0, "start_line": 862 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> f: Ast.field_array_t -> FStar.All.ML Ast.field_array_t
FStar.All.ML
[ "ml" ]
[]
[ "Ast.subst", "Ast.field_array_t", "Ast.expr", "Ast.array_qualifier", "Ast.FieldArrayQualified", "FStar.Pervasives.Native.tuple2", "FStar.Pervasives.Native.Mktuple2", "Ast.subst_expr", "FStar.Pervasives.Native.option", "Ast.FieldString", "Ast.map_opt" ]
[]
false
true
false
false
false
let subst_field_array (s: subst) (f: field_array_t) : ML field_array_t =
match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f
false
Ast.fst
Ast.subst_typ
val subst_typ (s: subst) (t: typ) : ML typ
val subst_typ (s: subst) (t: typ) : ML typ
let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) }
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 54, "end_line": 861, "start_col": 0, "start_line": 858 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> t: Ast.typ -> FStar.All.ML Ast.typ
FStar.All.ML
[ "ml" ]
[]
[ "Ast.subst", "Ast.typ", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.typ'", "Ast.ident", "Ast.t_kind", "Prims.list", "Ast.either", "Ast.expr", "Ast.out_expr", "Ast.Mkwith_meta_t", "Ast.__proj__Mkwith_meta_t__item__range", "Ast.__proj__Mkwith_meta_t__item__comments", "Ast.Type_app", "FStar.List.map", "Ast.subst_typ_param", "Ast.with_meta_t", "Ast.Pointer", "Ast.subst_typ" ]
[ "recursion" ]
false
true
false
false
false
let rec subst_typ (s: subst) (t: typ) : ML typ =
match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> { t with v = Pointer (subst_typ s t) }
false
Ast.fst
Ast.subst_action_opt
val subst_action_opt (s: subst) (a: option action) : ML (option action)
val subst_action_opt (s: subst) (a: option action) : ML (option action)
let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 37, "end_line": 850, "start_col": 0, "start_line": 840 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> a: FStar.Pervasives.Native.option Ast.action -> FStar.All.ML (FStar.Pervasives.Native.option Ast.action)
FStar.All.ML
[ "ml" ]
[ "subst_action", "subst_action_opt" ]
[ "Ast.subst", "FStar.Pervasives.Native.option", "Ast.action", "FStar.Pervasives.Native.None", "FStar.Pervasives.Native.Some", "Ast.subst_action" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec subst_action_opt (s: subst) (a: option action) : ML (option action) =
match a with | None -> None | Some a -> Some (subst_action s a)
false
Ast.fst
Ast.subst_action
val subst_action (s: subst) (a: action) : ML action
val subst_action (s: subst) (a: action) : ML action
let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 37, "end_line": 850, "start_col": 0, "start_line": 840 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> a: Ast.action -> FStar.All.ML Ast.action
FStar.All.ML
[ "ml" ]
[ "subst_action", "subst_action_opt" ]
[ "Ast.subst", "Ast.action", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.action'", "Ast.atomic_action", "Ast.Mkwith_meta_t", "Ast.__proj__Mkwith_meta_t__item__range", "Ast.__proj__Mkwith_meta_t__item__comments", "Ast.Atomic_action", "Ast.subst_atomic_action", "Ast.with_meta_t", "Ast.Action_seq", "Ast.subst_action", "Ast.expr", "FStar.Pervasives.Native.option", "Ast.Action_ite", "Ast.subst_action_opt", "Ast.subst_expr", "Ast.ident", "Ast.Action_let", "Ast.Action_act" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec subst_action (s: subst) (a: action) : ML action =
match a.v with | Atomic_action aa -> { a with v = Atomic_action (subst_atomic_action s aa) } | Action_seq hd tl -> { a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> { a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> { a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> { a with v = Action_act (subst_action s a) }
false
Ast.fst
Ast.print_decl
val print_decl (d: decl) : ML string
val print_decl (d: decl) : ML string
let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 34, "end_line": 1207, "start_col": 0, "start_line": 1202 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
d: Ast.decl -> FStar.All.ML Prims.string
FStar.All.ML
[ "ml" ]
[]
[ "Ast.decl", "Ast.__proj__Mkwith_meta_t__item__comments", "Ast.decl'", "Ast.__proj__Mkdecl__item__d_decl", "Ast.print_decl'", "Ast.__proj__Mkwith_meta_t__item__v", "Prims.string", "Prims.list", "FStar.Printf.sprintf", "FStar.String.concat" ]
[]
false
true
false
false
false
let print_decl (d: decl) : ML string =
match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v)
false
Ast.fst
Ast.print_integer_type
val print_integer_type : _: Ast.integer_type -> Prims.string
let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64"
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 22, "end_line": 941, "start_col": 0, "start_line": 937 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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 =
function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64"
false
Ast.fst
Ast.print_decls
val print_decls (ds: list decl) : ML string
val print_decls (ds: list decl) : ML string
let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n"
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 23, "end_line": 1211, "start_col": 0, "start_line": 1209 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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 Ast.decl -> FStar.All.ML Prims.string
FStar.All.ML
[ "ml" ]
[]
[ "Prims.list", "Ast.decl", "FStar.String.concat", "Prims.string", "FStar.List.map", "Ast.print_decl" ]
[]
false
true
false
false
false
let print_decls (ds: list decl) : ML string =
List.map print_decl ds |> String.concat "\n"
false
Hacl.Impl.Ed25519.RecoverX.fst
Hacl.Impl.Ed25519.RecoverX.x_mod_2
val x_mod_2: x:felem -> Stack uint64 (requires fun h -> live h x) (ensures fun h0 z h1 -> h0 == h1 /\ v z < 2 /\ v z == F51.as_nat h0 x % 2)
val x_mod_2: x:felem -> Stack uint64 (requires fun h -> live h x) (ensures fun h0 z h1 -> h0 == h1 /\ v z < 2 /\ v z == F51.as_nat h0 x % 2)
let x_mod_2 x = let x0 = x.(0ul) in let z = x0 &. u64 1 in mod_mask_lemma x0 1ul; Lib.IntTypes.Compatibility.uintv_extensionality (u64 1) (mod_mask #U64 1ul); z
{ "file_name": "code/ed25519/Hacl.Impl.Ed25519.RecoverX.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 3, "end_line": 100, "start_col": 0, "start_line": 95 }
module Hacl.Impl.Ed25519.RecoverX module ST = FStar.HyperStack.ST open FStar.HyperStack.All open FStar.Mul open Lib.IntTypes open Lib.Buffer open Hacl.Bignum25519 module F51 = Hacl.Impl.Ed25519.Field51 module S51 = Hacl.Spec.Curve25519.Field51.Definition module SC = Spec.Curve25519 module SE = Spec.Ed25519 #reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0" inline_for_extraction noextract let elemB = lbuffer uint64 5ul val is_0: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.as_nat h x == F51.fevalh h x) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.fevalh h0 x == SC.zero))) [@CInline] let is_0 x = let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 =^ 0uL && u64_to_UInt64 x1 =^ 0uL && u64_to_UInt64 x2 =^ 0uL && u64_to_UInt64 x3 =^ 0uL && u64_to_UInt64 x4 =^ 0uL) inline_for_extraction noextract val gte_q: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.felem_fits h x (1, 1, 1, 1, 1)) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.as_nat h0 x >= SC.prime))) let gte_q x = let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 >=^ 0x7ffffffffffeduL && u64_to_UInt64 x1 =^ 0x7ffffffffffffuL && u64_to_UInt64 x2 =^ 0x7ffffffffffffuL && u64_to_UInt64 x3 =^ 0x7ffffffffffffuL && u64_to_UInt64 x4 =^ 0x7ffffffffffffuL) val mul_modp_sqrt_m1: x:elemB -> Stack unit (requires fun h -> live h x /\ F51.mul_inv_t h x) (ensures fun h0 _ h1 -> modifies (loc x) h0 h1 /\ F51.mul_inv_t h1 x /\ F51.fevalh h1 x == F51.fevalh h0 x `SC.fmul` SE.modp_sqrt_m1) [@CInline] let mul_modp_sqrt_m1 x = [@inline_let] let (x0, x1, x2, x3, x4) = (u64 0x00061b274a0ea0b0, u64 0x0000d5a5fc8f189d, u64 0x0007ef5e9cbd0c60, u64 0x00078595a6804c9e, u64 0x0002b8324804fc1d) in push_frame(); let sqrt_m1 = create 5ul (u64 0) in make_u64_5 sqrt_m1 x0 x1 x2 x3 x4; assert_norm (S51.as_nat5 (x0, x1, x2, x3, x4) == SE.modp_sqrt_m1); fmul x x sqrt_m1; pop_frame() inline_for_extraction noextract val x_mod_2: x:felem -> Stack uint64 (requires fun h -> live h x) (ensures fun h0 z h1 -> h0 == h1 /\ v z < 2 /\ v z == F51.as_nat h0 x % 2)
{ "checked_file": "/", "dependencies": [ "Spec.Ed25519.fst.checked", "Spec.Curve25519.fst.checked", "prims.fst.checked", "Lib.RawIntTypes.fsti.checked", "Lib.IntTypes.Compatibility.fst.checked", "Lib.IntTypes.fsti.checked", "Lib.Buffer.fsti.checked", "Hacl.Spec.Curve25519.Field51.Definition.fst.checked", "Hacl.Impl.Ed25519.Pow2_252m2.fst.checked", "Hacl.Impl.Ed25519.Field51.fst.checked", "Hacl.Bignum25519.fsti.checked", "FStar.UInt8.fsti.checked", "FStar.UInt64.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.All.fst.checked" ], "interface_file": false, "source_file": "Hacl.Impl.Ed25519.RecoverX.fst" }
[ { "abbrev": true, "full_module": "Spec.Ed25519", "short_module": "SE" }, { "abbrev": true, "full_module": "Spec.Curve25519", "short_module": "SC" }, { "abbrev": true, "full_module": "Hacl.Spec.Curve25519.Field51.Definition", "short_module": "S51" }, { "abbrev": true, "full_module": "Hacl.Impl.Ed25519.Field51", "short_module": "F51" }, { "abbrev": false, "full_module": "Hacl.Bignum25519", "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": true, "full_module": "FStar.HyperStack.ST", "short_module": "ST" }, { "abbrev": false, "full_module": "Hacl.Impl.Ed25519", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Impl.Ed25519", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: Hacl.Bignum25519.felem -> FStar.HyperStack.ST.Stack Lib.IntTypes.uint64
FStar.HyperStack.ST.Stack
[]
[]
[ "Hacl.Bignum25519.felem", "Prims.unit", "Lib.IntTypes.Compatibility.uintv_extensionality", "Lib.IntTypes.U64", "Lib.IntTypes.SEC", "Lib.IntTypes.u64", "Lib.IntTypes.mod_mask", "FStar.UInt32.__uint_to_t", "Lib.IntTypes.mod_mask_lemma", "Lib.IntTypes.int_t", "Lib.IntTypes.op_Amp_Dot", "Lib.IntTypes.uint64", "Lib.Buffer.op_Array_Access", "Lib.Buffer.MUT" ]
[]
false
true
false
false
false
let x_mod_2 x =
let x0 = x.(0ul) in let z = x0 &. u64 1 in mod_mask_lemma x0 1ul; Lib.IntTypes.Compatibility.uintv_extensionality (u64 1) (mod_mask #U64 1ul); z
false
Ast.fst
Ast.print_op
val print_op : _: Ast.op -> Prims.string
let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 14, "end_line": 972, "start_col": 0, "start_line": 947 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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.op -> Prims.string
Prims.Tot
[ "total" ]
[]
[ "Ast.op", "FStar.Pervasives.Native.option", "Ast.integer_type", "Prims.int", "Ast.bitfield_bit_order", "FStar.Printf.sprintf", "Ast.print_bitfield_bit_order", "Prims.op_Hat", "Ast.print_integer_type", "Prims.string" ]
[]
false
false
false
true
false
let print_op =
function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s
false
Ast.fst
Ast.subst_decl'
val subst_decl' (s: subst) (d: decl') : ML decl'
val subst_decl' (s: subst) (d: decl') : ML decl'
let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 22, "end_line": 912, "start_col": 0, "start_line": 898 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) =
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> d: Ast.decl' -> FStar.All.ML Ast.decl'
FStar.All.ML
[ "ml" ]
[]
[ "Ast.subst", "Ast.decl'", "Ast.ident", "Ast.constant", "Ast.typ", "Ast.Define", "FStar.Pervasives.Native.option", "FStar.Pervasives.Native.Some", "Ast.subst_typ", "Ast.TypeAbbrev", "Prims.list", "Ast.enum_case", "Ast.Enum", "Ast.typedef_names", "Ast.param", "Ast.expr", "Ast.record", "Ast.Record", "FStar.List.map", "Ast.with_meta_t", "Ast.field'", "Ast.subst_field", "Ast.map_opt", "Ast.subst_expr", "Ast.subst_params", "Ast.switch_case", "Ast.CaseType", "Ast.subst_switch_case", "Ast.out_typ" ]
[]
false
true
false
false
false
let subst_decl' (s: subst) (d: decl') : ML decl' =
match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d
false
Ast.fst
Ast.subst_field
val subst_field (s: subst) (ff: field) : ML field
val subst_field (s: subst) (ff: field) : ML field
let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 57, "end_line": 895, "start_col": 0, "start_line": 868 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> ff: Ast.field -> FStar.All.ML Ast.field
FStar.All.ML
[ "ml" ]
[ "subst_field", "subst_atomic_field", "subst_record", "subst_case", "subst_switch_case" ]
[ "Ast.subst", "Ast.field", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.field'", "Ast.with_meta_t", "Ast.atomic_field'", "Ast.Mkwith_meta_t", "Ast.__proj__Mkwith_meta_t__item__range", "Ast.__proj__Mkwith_meta_t__item__comments", "Ast.AtomicField", "Ast.subst_atomic_field", "Ast.atomic_field", "Prims.list", "Ast.ident", "Ast.RecordField", "Ast.subst_record", "Ast.record", "FStar.Pervasives.Native.tuple2", "Ast.expr", "Ast.case", "Ast.SwitchCaseField", "Ast.subst_switch_case", "Ast.switch_case" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec subst_field (s: subst) (ff: field) : ML field =
match ff.v with | AtomicField f -> { ff with v = AtomicField (subst_atomic_field s f) } | RecordField f i -> { ff with v = RecordField (subst_record s f) i } | SwitchCaseField f i -> { ff with v = SwitchCaseField (subst_switch_case s f) i }
false
Ast.fst
Ast.atomic_field_prune_actions
val atomic_field_prune_actions (a: atomic_field) : Tot atomic_field
val atomic_field_prune_actions (a: atomic_field) : Tot atomic_field
let atomic_field_prune_actions (a: atomic_field) : Tot atomic_field = { a with v = atomic_field'_prune_actions a.v }
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 48, "end_line": 1247, "start_col": 0, "start_line": 1244 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak" let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak let field_tag_equal (f0 f1:field) = match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false (* Pruning actions out of the surface ast (to generate validators checking Z3 test cases) *) let atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field' = { a with field_action = None }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
a: Ast.atomic_field -> Ast.atomic_field
Prims.Tot
[ "total" ]
[]
[ "Ast.atomic_field", "Ast.Mkwith_meta_t", "Ast.atomic_field'", "Ast.atomic_field'_prune_actions", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.__proj__Mkwith_meta_t__item__range", "Ast.__proj__Mkwith_meta_t__item__comments" ]
[]
false
false
false
true
false
let atomic_field_prune_actions (a: atomic_field) : Tot atomic_field =
{ a with v = atomic_field'_prune_actions a.v }
false
Hacl.Impl.Curve25519.Generic.fst
Hacl.Impl.Curve25519.Generic.ladder_step
val ladder_step: #s:field_spec -> k:scalar -> q:point s -> i:size_t{v i < 251} -> p01_tmp1_swap:lbuffer (limb s) (8ul *! nlimb s +! 1ul) -> tmp2:felem_wide2 s -> Stack unit (requires fun h0 -> live h0 k /\ live h0 q /\ live h0 p01_tmp1_swap /\ live h0 tmp2 /\ LowStar.Monotonic.Buffer.all_disjoint [loc k; loc q; loc p01_tmp1_swap; loc tmp2] /\ (let nq = gsub p01_tmp1_swap 0ul (2ul *! nlimb s) in let nq_p1 = gsub p01_tmp1_swap (2ul *! nlimb s) (2ul *! nlimb s) in let bit : lbuffer uint64 1ul = gsub p01_tmp1_swap (8ul *! nlimb s) 1ul in v (LSeq.index (as_seq h0 bit) 0) <= 1 /\ state_inv_t h0 (get_x q) /\ state_inv_t h0 (get_z q) /\ state_inv_t h0 (get_x nq) /\ state_inv_t h0 (get_z nq) /\ state_inv_t h0 (get_x nq_p1) /\ state_inv_t h0 (get_z nq_p1))) (ensures fun h0 _ h1 -> modifies (loc p01_tmp1_swap |+| loc tmp2) h0 h1 /\ (let nq = gsub p01_tmp1_swap 0ul (2ul *! nlimb s) in let nq_p1 = gsub p01_tmp1_swap (2ul *! nlimb s) (2ul *! nlimb s) in let bit : lbuffer uint64 1ul = gsub p01_tmp1_swap (8ul *! nlimb s) 1ul in let (p0, p1, b) = S.ladder_step (as_seq h0 k) (fget_xz h0 q) (v i) (fget_xz h0 nq, fget_xz h0 nq_p1, LSeq.index (as_seq h0 bit) 0) in p0 == fget_xz h1 nq /\ p1 == fget_xz h1 nq_p1 /\ b == LSeq.index (as_seq h1 bit) 0 /\ v (LSeq.index (as_seq h1 bit) 0) <= 1 /\ state_inv_t h1 (get_x q) /\ state_inv_t h1 (get_z q) /\ state_inv_t h1 (get_x nq) /\ state_inv_t h1 (get_z nq) /\ state_inv_t h1 (get_x nq_p1) /\ state_inv_t h1 (get_z nq_p1)))
val ladder_step: #s:field_spec -> k:scalar -> q:point s -> i:size_t{v i < 251} -> p01_tmp1_swap:lbuffer (limb s) (8ul *! nlimb s +! 1ul) -> tmp2:felem_wide2 s -> Stack unit (requires fun h0 -> live h0 k /\ live h0 q /\ live h0 p01_tmp1_swap /\ live h0 tmp2 /\ LowStar.Monotonic.Buffer.all_disjoint [loc k; loc q; loc p01_tmp1_swap; loc tmp2] /\ (let nq = gsub p01_tmp1_swap 0ul (2ul *! nlimb s) in let nq_p1 = gsub p01_tmp1_swap (2ul *! nlimb s) (2ul *! nlimb s) in let bit : lbuffer uint64 1ul = gsub p01_tmp1_swap (8ul *! nlimb s) 1ul in v (LSeq.index (as_seq h0 bit) 0) <= 1 /\ state_inv_t h0 (get_x q) /\ state_inv_t h0 (get_z q) /\ state_inv_t h0 (get_x nq) /\ state_inv_t h0 (get_z nq) /\ state_inv_t h0 (get_x nq_p1) /\ state_inv_t h0 (get_z nq_p1))) (ensures fun h0 _ h1 -> modifies (loc p01_tmp1_swap |+| loc tmp2) h0 h1 /\ (let nq = gsub p01_tmp1_swap 0ul (2ul *! nlimb s) in let nq_p1 = gsub p01_tmp1_swap (2ul *! nlimb s) (2ul *! nlimb s) in let bit : lbuffer uint64 1ul = gsub p01_tmp1_swap (8ul *! nlimb s) 1ul in let (p0, p1, b) = S.ladder_step (as_seq h0 k) (fget_xz h0 q) (v i) (fget_xz h0 nq, fget_xz h0 nq_p1, LSeq.index (as_seq h0 bit) 0) in p0 == fget_xz h1 nq /\ p1 == fget_xz h1 nq_p1 /\ b == LSeq.index (as_seq h1 bit) 0 /\ v (LSeq.index (as_seq h1 bit) 0) <= 1 /\ state_inv_t h1 (get_x q) /\ state_inv_t h1 (get_z q) /\ state_inv_t h1 (get_x nq) /\ state_inv_t h1 (get_z nq) /\ state_inv_t h1 (get_x nq_p1) /\ state_inv_t h1 (get_z nq_p1)))
let ladder_step #s k q i p01_tmp1_swap tmp2 = let p01_tmp1 = sub p01_tmp1_swap 0ul (8ul *! nlimb s) in let swap : lbuffer uint64 1ul = sub p01_tmp1_swap (8ul *! nlimb s) 1ul in let nq = sub p01_tmp1 0ul (2ul *! nlimb s) in let nq_p1 = sub p01_tmp1 (2ul *! nlimb s) (2ul *! nlimb s) in assert (gsub p01_tmp1_swap 0ul (2ul *! nlimb s) == nq); assert (gsub p01_tmp1_swap (2ul *! nlimb s) (2ul *! nlimb s) == nq_p1); assert (gsub p01_tmp1 0ul (2ul *! nlimb s) == nq); assert (gsub p01_tmp1 (2ul *! nlimb s) (2ul *! nlimb s) == nq_p1); assert (gsub p01_tmp1_swap 0ul (8ul *! nlimb s) == p01_tmp1); assert (gsub p01_tmp1_swap (8ul *! nlimb s) 1ul == swap); let h0 = ST.get () in let bit = scalar_bit k (253ul -. i) in assert (v bit == v (S.ith_bit (as_seq h0 k) (253 - v i))); let sw = swap.(0ul) ^. bit in logxor_lemma1 (LSeq.index (as_seq h0 swap) 0) bit; cswap2 #s sw nq nq_p1; point_add_and_double #s q p01_tmp1 tmp2; swap.(0ul) <- bit
{ "file_name": "code/curve25519/Hacl.Impl.Curve25519.Generic.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 19, "end_line": 188, "start_col": 0, "start_line": 168 }
module Hacl.Impl.Curve25519.Generic open FStar.HyperStack open FStar.HyperStack.All open FStar.Mul open Lib.IntTypes open Lib.Buffer open Lib.ByteBuffer open Hacl.Impl.Curve25519.Fields include Hacl.Impl.Curve25519.Finv include Hacl.Impl.Curve25519.AddAndDouble module ST = FStar.HyperStack.ST module BSeq = Lib.ByteSequence module LSeq = Lib.Sequence module C = Hacl.Impl.Curve25519.Fields.Core module S = Spec.Curve25519 module M = Hacl.Spec.Curve25519.AddAndDouble module Lemmas = Hacl.Spec.Curve25519.Field64.Lemmas friend Lib.LoopCombinators #set-options "--z3rlimit 30 --fuel 0 --ifuel 1 --using_facts_from '* -FStar.Seq -Hacl.Spec.*' --record_options" //#set-options "--debug Hacl.Impl.Curve25519.Generic --debug_level ExtractNorm" inline_for_extraction noextract let scalar = lbuffer uint8 32ul inline_for_extraction noextract val scalar_bit: s:scalar -> n:size_t{v n < 256} -> Stack uint64 (requires fun h0 -> live h0 s) (ensures fun h0 r h1 -> h0 == h1 /\ r == S.ith_bit (as_seq h0 s) (v n) /\ v r <= 1) let scalar_bit s n = let h0 = ST.get () in mod_mask_lemma ((LSeq.index (as_seq h0 s) (v n / 8)) >>. (n %. 8ul)) 1ul; assert_norm (1 = pow2 1 - 1); assert (v (mod_mask #U8 #SEC 1ul) == v (u8 1)); to_u64 ((s.(n /. 8ul) >>. (n %. 8ul)) &. u8 1) inline_for_extraction noextract val decode_point: #s:field_spec -> o:point s -> i:lbuffer uint8 32ul -> Stack unit (requires fun h0 -> live h0 o /\ live h0 i /\ disjoint o i) (ensures fun h0 _ h1 -> modifies (loc o) h0 h1 /\ state_inv_t h1 (get_x o) /\ state_inv_t h1 (get_z o) /\ fget_x h1 o == S.decodePoint (as_seq h0 i) /\ fget_z h1 o == 1) [@ Meta.Attribute.specialize ] let decode_point #s o i = push_frame(); let tmp = create 4ul (u64 0) in let h0 = ST.get () in uints_from_bytes_le #U64 tmp i; let h1 = ST.get () in BSeq.uints_from_bytes_le_nat_lemma #U64 #SEC #4 (as_seq h0 i); assert (BSeq.nat_from_intseq_le (as_seq h1 tmp) == BSeq.nat_from_bytes_le (as_seq h0 i)); let tmp3 = tmp.(3ul) in tmp.(3ul) <- tmp3 &. u64 0x7fffffffffffffff; mod_mask_lemma tmp3 63ul; assert_norm (0x7fffffffffffffff = pow2 63 - 1); assert (v (mod_mask #U64 #SEC 63ul) == v (u64 0x7fffffffffffffff)); let h2 = ST.get () in assert (v (LSeq.index (as_seq h2 tmp) 3) < pow2 63); Lemmas.lemma_felem64_mod255 (as_seq h1 tmp); assert (BSeq.nat_from_intseq_le (as_seq h2 tmp) == BSeq.nat_from_bytes_le (as_seq h0 i) % pow2 255); let x : felem s = sub o 0ul (nlimb s) in let z : felem s = sub o (nlimb s) (nlimb s) in set_one z; load_felem x tmp; pop_frame() val encode_point: #s:field_spec -> o:lbuffer uint8 32ul -> i:point s -> Stack unit (requires fun h0 -> live h0 o /\ live h0 i /\ disjoint o i /\ state_inv_t h0 (get_x i) /\ state_inv_t h0 (get_z i)) (ensures fun h0 _ h1 -> modifies (loc o) h0 h1 /\ as_seq h1 o == S.encodePoint (fget_x h0 i, fget_z h0 i)) [@ Meta.Attribute.specialize ] let encode_point #s o i = push_frame(); let x : felem s = sub i 0ul (nlimb s) in let z : felem s = sub i (nlimb s) (nlimb s) in let tmp = create_felem s in let u64s = create 4ul (u64 0) in let tmp_w = create (2ul `FStar.UInt32.mul` ((nwide s) <: FStar.UInt32.t)) (wide_zero s) in let h0 = ST.get () in finv tmp z tmp_w; fmul tmp tmp x tmp_w; let h1 = ST.get () in assert (feval h1 tmp == S.fmul (S.fpow (feval h0 z) (pow2 255 - 21)) (feval h0 x)); assert (feval h1 tmp == S.fmul (feval h0 x) (S.fpow (feval h0 z) (pow2 255 - 21))); store_felem u64s tmp; let h2 = ST.get () in assert (as_seq h2 u64s == BSeq.nat_to_intseq_le 4 (feval h1 tmp)); uints_to_bytes_le #U64 4ul o u64s; let h3 = ST.get () in BSeq.uints_to_bytes_le_nat_lemma #U64 #SEC 4 (feval h1 tmp); assert (as_seq h3 o == BSeq.nat_to_bytes_le 32 (feval h1 tmp)); pop_frame() // TODO: why re-define the signature here? val cswap2: #s:field_spec -> bit:uint64{v bit <= 1} -> p1:felem2 s -> p2:felem2 s -> Stack unit (requires fun h0 -> live h0 p1 /\ live h0 p2 /\ disjoint p1 p2) (ensures fun h0 _ h1 -> modifies (loc p1 |+| loc p2) h0 h1 /\ (v bit == 1 ==> as_seq h1 p1 == as_seq h0 p2 /\ as_seq h1 p2 == as_seq h0 p1) /\ (v bit == 0 ==> as_seq h1 p1 == as_seq h0 p1 /\ as_seq h1 p2 == as_seq h0 p2) /\ (fget_xz h1 p1, fget_xz h1 p2) == S.cswap2 bit (fget_xz h0 p1) (fget_xz h0 p2)) [@ Meta.Attribute.inline_ ] let cswap2 #s bit p0 p1 = C.cswap2 #s bit p0 p1 val ladder_step: #s:field_spec -> k:scalar -> q:point s -> i:size_t{v i < 251} -> p01_tmp1_swap:lbuffer (limb s) (8ul *! nlimb s +! 1ul) -> tmp2:felem_wide2 s -> Stack unit (requires fun h0 -> live h0 k /\ live h0 q /\ live h0 p01_tmp1_swap /\ live h0 tmp2 /\ LowStar.Monotonic.Buffer.all_disjoint [loc k; loc q; loc p01_tmp1_swap; loc tmp2] /\ (let nq = gsub p01_tmp1_swap 0ul (2ul *! nlimb s) in let nq_p1 = gsub p01_tmp1_swap (2ul *! nlimb s) (2ul *! nlimb s) in let bit : lbuffer uint64 1ul = gsub p01_tmp1_swap (8ul *! nlimb s) 1ul in v (LSeq.index (as_seq h0 bit) 0) <= 1 /\ state_inv_t h0 (get_x q) /\ state_inv_t h0 (get_z q) /\ state_inv_t h0 (get_x nq) /\ state_inv_t h0 (get_z nq) /\ state_inv_t h0 (get_x nq_p1) /\ state_inv_t h0 (get_z nq_p1))) (ensures fun h0 _ h1 -> modifies (loc p01_tmp1_swap |+| loc tmp2) h0 h1 /\ (let nq = gsub p01_tmp1_swap 0ul (2ul *! nlimb s) in let nq_p1 = gsub p01_tmp1_swap (2ul *! nlimb s) (2ul *! nlimb s) in let bit : lbuffer uint64 1ul = gsub p01_tmp1_swap (8ul *! nlimb s) 1ul in let (p0, p1, b) = S.ladder_step (as_seq h0 k) (fget_xz h0 q) (v i) (fget_xz h0 nq, fget_xz h0 nq_p1, LSeq.index (as_seq h0 bit) 0) in p0 == fget_xz h1 nq /\ p1 == fget_xz h1 nq_p1 /\ b == LSeq.index (as_seq h1 bit) 0 /\ v (LSeq.index (as_seq h1 bit) 0) <= 1 /\ state_inv_t h1 (get_x q) /\ state_inv_t h1 (get_z q) /\ state_inv_t h1 (get_x nq) /\ state_inv_t h1 (get_z nq) /\ state_inv_t h1 (get_x nq_p1) /\ state_inv_t h1 (get_z nq_p1))) #push-options "--z3rlimit 200 --fuel 0 --ifuel 1"
{ "checked_file": "/", "dependencies": [ "Spec.Curve25519.fst.checked", "prims.fst.checked", "Meta.Attribute.fst.checked", "LowStar.Monotonic.Buffer.fsti.checked", "Lib.Sequence.fsti.checked", "Lib.Loops.fsti.checked", "Lib.LoopCombinators.fst.checked", "Lib.IntTypes.fsti.checked", "Lib.ByteSequence.fsti.checked", "Lib.ByteBuffer.fsti.checked", "Lib.Buffer.fsti.checked", "Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked", "Hacl.Spec.Curve25519.AddAndDouble.fst.checked", "Hacl.Impl.Curve25519.Finv.fst.checked", "Hacl.Impl.Curve25519.Fields.Core.fsti.checked", "Hacl.Impl.Curve25519.Fields.fst.checked", "Hacl.Impl.Curve25519.AddAndDouble.fst.checked", "FStar.UInt32.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.All.fst.checked", "FStar.HyperStack.fst.checked" ], "interface_file": true, "source_file": "Hacl.Impl.Curve25519.Generic.fst" }
[ { "abbrev": true, "full_module": "Hacl.Spec.Curve25519.Field64.Lemmas", "short_module": "Lemmas" }, { "abbrev": true, "full_module": "Hacl.Spec.Curve25519.AddAndDouble", "short_module": "M" }, { "abbrev": true, "full_module": "Spec.Curve25519", "short_module": "S" }, { "abbrev": true, "full_module": "Hacl.Impl.Curve25519.Fields.Core", "short_module": "C" }, { "abbrev": true, "full_module": "Lib.Sequence", "short_module": "LSeq" }, { "abbrev": true, "full_module": "Lib.ByteSequence", "short_module": "BSeq" }, { "abbrev": true, "full_module": "FStar.HyperStack.ST", "short_module": "ST" }, { "abbrev": false, "full_module": "Hacl.Impl.Curve25519.AddAndDouble", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Impl.Curve25519.Finv", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Impl.Curve25519.Fields", "short_module": null }, { "abbrev": false, "full_module": "Lib.ByteBuffer", "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": "FStar.HyperStack", "short_module": null }, { "abbrev": true, "full_module": "Spec.Curve25519", "short_module": "S" }, { "abbrev": false, "full_module": "Hacl.Impl.Curve25519.Fields", "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.HyperStack.All", "short_module": null }, { "abbrev": false, "full_module": "FStar.HyperStack", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Impl.Curve25519", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Impl.Curve25519", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": 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": 1, "max_fuel": 0, "max_ifuel": 1, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_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": 200, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
k: Hacl.Impl.Curve25519.Generic.scalar -> q: Hacl.Impl.Curve25519.AddAndDouble.point s -> i: Lib.IntTypes.size_t{Lib.IntTypes.v i < 251} -> p01_tmp1_swap: Lib.Buffer.lbuffer (Hacl.Impl.Curve25519.Fields.Core.limb s) (8ul *! Hacl.Impl.Curve25519.Fields.Core.nlimb s +! 1ul) -> tmp2: Hacl.Impl.Curve25519.Fields.Core.felem_wide2 s -> FStar.HyperStack.ST.Stack Prims.unit
FStar.HyperStack.ST.Stack
[]
[]
[ "Hacl.Impl.Curve25519.Fields.Core.field_spec", "Hacl.Impl.Curve25519.Generic.scalar", "Hacl.Impl.Curve25519.AddAndDouble.point", "Lib.IntTypes.size_t", "Prims.b2t", "Prims.op_LessThan", "Lib.IntTypes.v", "Lib.IntTypes.U32", "Lib.IntTypes.PUB", "Lib.Buffer.lbuffer", "Hacl.Impl.Curve25519.Fields.Core.limb", "Lib.IntTypes.op_Plus_Bang", "Lib.IntTypes.op_Star_Bang", "FStar.UInt32.__uint_to_t", "Hacl.Impl.Curve25519.Fields.Core.nlimb", "Hacl.Impl.Curve25519.Fields.Core.felem_wide2", "Lib.Buffer.op_Array_Assignment", "Lib.IntTypes.int_t", "Lib.IntTypes.U64", "Lib.IntTypes.SEC", "FStar.UInt32.uint_to_t", "Prims.unit", "Hacl.Impl.Curve25519.AddAndDouble.point_add_and_double", "Hacl.Impl.Curve25519.Generic.cswap2", "Lib.IntTypes.logxor_lemma1", "Lib.Sequence.index", "Lib.Buffer.as_seq", "Lib.Buffer.MUT", "Lib.IntTypes.op_Hat_Dot", "Lib.Buffer.op_Array_Access", "Prims._assert", "Prims.eq2", "Lib.IntTypes.range_t", "Spec.Curve25519.ith_bit", "Lib.IntTypes.uint8", "Prims.op_Subtraction", "Hacl.Impl.Curve25519.Generic.scalar_bit", "Lib.IntTypes.op_Subtraction_Dot", "Lib.IntTypes.uint64", "FStar.Monotonic.HyperStack.mem", "FStar.HyperStack.ST.get", "Lib.Buffer.buffer_t", "Prims.l_or", "Prims.int", "Prims.op_GreaterThanOrEqual", "Lib.IntTypes.range", "Lib.Buffer.length", "FStar.UInt32.t", "Lib.Buffer.gsub", "Lib.Buffer.lbuffer_t", "Lib.IntTypes.mul", "Lib.Buffer.sub" ]
[]
false
true
false
false
false
let ladder_step #s k q i p01_tmp1_swap tmp2 =
let p01_tmp1 = sub p01_tmp1_swap 0ul (8ul *! nlimb s) in let swap:lbuffer uint64 1ul = sub p01_tmp1_swap (8ul *! nlimb s) 1ul in let nq = sub p01_tmp1 0ul (2ul *! nlimb s) in let nq_p1 = sub p01_tmp1 (2ul *! nlimb s) (2ul *! nlimb s) in assert (gsub p01_tmp1_swap 0ul (2ul *! nlimb s) == nq); assert (gsub p01_tmp1_swap (2ul *! nlimb s) (2ul *! nlimb s) == nq_p1); assert (gsub p01_tmp1 0ul (2ul *! nlimb s) == nq); assert (gsub p01_tmp1 (2ul *! nlimb s) (2ul *! nlimb s) == nq_p1); assert (gsub p01_tmp1_swap 0ul (8ul *! nlimb s) == p01_tmp1); assert (gsub p01_tmp1_swap (8ul *! nlimb s) 1ul == swap); let h0 = ST.get () in let bit = scalar_bit k (253ul -. i) in assert (v bit == v (S.ith_bit (as_seq h0 k) (253 - v i))); let sw = swap.(0ul) ^. bit in logxor_lemma1 (LSeq.index (as_seq h0 swap) 0) bit; cswap2 #s sw nq nq_p1; point_add_and_double #s q p01_tmp1 tmp2; swap.(0ul) <- bit
false
Ast.fst
Ast.subst_switch_case
val subst_switch_case (s: subst) (sc: switch_case) : ML switch_case
val subst_switch_case (s: subst) (sc: switch_case) : ML switch_case
let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 57, "end_line": 895, "start_col": 0, "start_line": 868 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> sc: Ast.switch_case -> FStar.All.ML Ast.switch_case
FStar.All.ML
[ "ml" ]
[ "subst_field", "subst_atomic_field", "subst_record", "subst_case", "subst_switch_case" ]
[ "Ast.subst", "Ast.switch_case", "FStar.Pervasives.Native.Mktuple2", "Ast.expr", "Prims.list", "Ast.case", "FStar.List.map", "Ast.subst_case", "FStar.Pervasives.Native.snd", "Ast.subst_expr", "FStar.Pervasives.Native.fst" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec subst_switch_case (s: subst) (sc: switch_case) : ML switch_case =
subst_expr s (fst sc), List.map (subst_case s) (snd sc)
false
Ast.fst
Ast.subst_typ_param
val subst_typ_param (s: subst) (p: typ_param) : ML typ_param
val subst_typ_param (s: subst) (p: typ_param) : ML typ_param
let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 39, "end_line": 857, "start_col": 0, "start_line": 854 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> p: Ast.typ_param -> FStar.All.ML Ast.typ_param
FStar.All.ML
[ "ml" ]
[]
[ "Ast.subst", "Ast.typ_param", "Ast.expr", "Ast.Inl", "Ast.out_expr", "Ast.subst_expr", "Ast.Inr", "Ast.subst_out_expr" ]
[]
false
true
false
false
false
let subst_typ_param (s: subst) (p: typ_param) : ML typ_param =
match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe)
false
Ast.fst
Ast.field_tag_equal
val field_tag_equal : f0: Ast.field -> f1: Ast.field -> Prims.bool
let field_tag_equal (f0 f1:field) = match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 14, "end_line": 1235, "start_col": 0, "start_line": 1230 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak" let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
f0: Ast.field -> f1: Ast.field -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "Ast.field", "FStar.Pervasives.Native.Mktuple2", "Ast.field'", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.with_meta_t", "Ast.atomic_field'", "Prims.list", "Ast.ident", "FStar.Pervasives.Native.tuple2", "Ast.expr", "Ast.case", "Prims.bool" ]
[]
false
false
false
true
false
let field_tag_equal (f0 f1: field) =
match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false
false
Ast.fst
Ast.print_constant
val print_constant : c: Ast.constant -> Prims.string
let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 35, "end_line": 933, "start_col": 0, "start_line": 916 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
c: Ast.constant -> Prims.string
Prims.Tot
[ "total" ]
[]
[ "Ast.constant", "Ast.integer_type", "Prims.int", "FStar.Printf.sprintf", "Prims.string", "Prims.op_AmpAmp", "Prims.op_GreaterThanOrEqual", "FStar.String.length", "Prims.op_Equality", "FStar.String.sub", "Prims.op_Subtraction", "Prims.bool" ]
[]
false
false
false
true
false
let print_constant (c: constant) =
let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b
false
Ast.fst
Ast.subst_atomic_field
val subst_atomic_field (s: subst) (f: atomic_field) : ML atomic_field
val subst_atomic_field (s: subst) (f: atomic_field) : ML atomic_field
let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 57, "end_line": 895, "start_col": 0, "start_line": 868 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> f: Ast.atomic_field -> FStar.All.ML Ast.atomic_field
FStar.All.ML
[ "ml" ]
[ "subst_field", "subst_atomic_field", "subst_record", "subst_case", "subst_switch_case" ]
[ "Ast.subst", "Ast.atomic_field", "Ast.Mkwith_meta_t", "Ast.atomic_field'", "Ast.__proj__Mkwith_meta_t__item__range", "Ast.__proj__Mkwith_meta_t__item__comments", "Ast.Mkatomic_field'", "Ast.__proj__Mkatomic_field'__item__field_dependence", "Ast.__proj__Mkatomic_field'__item__field_ident", "Ast.__proj__Mkatomic_field'__item__field_bitwidth", "Ast.__proj__Mkatomic_field'__item__field_probe", "FStar.Pervasives.Native.option", "Ast.expr", "Ast.map_opt", "Ast.subst_expr", "Ast.__proj__Mkatomic_field'__item__field_constraint", "Ast.field_array_t", "Ast.subst_field_array", "Ast.__proj__Mkatomic_field'__item__field_array_opt", "Ast.typ", "Ast.subst_typ", "Ast.__proj__Mkatomic_field'__item__field_type", "FStar.Pervasives.Native.tuple2", "Ast.action", "Prims.bool", "Ast.__proj__Mkatomic_field'__item__field_action", "FStar.Pervasives.Native.None", "FStar.Pervasives.Native.Some", "FStar.Pervasives.Native.Mktuple2", "Ast.subst_action", "Ast.__proj__Mkwith_meta_t__item__v" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec subst_atomic_field (s: subst) (f: atomic_field) : ML atomic_field =
let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf }
false
Ast.fst
Ast.print_qual
val print_qual : _: Ast.qualifier -> Prims.string
let print_qual = function | Mutable -> "mutable" | Immutable -> ""
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 19, "end_line": 1064, "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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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.qualifier -> Prims.string
Prims.Tot
[ "total" ]
[]
[ "Ast.qualifier", "Prims.string" ]
[]
false
false
false
true
false
let print_qual =
function | Mutable -> "mutable" | Immutable -> ""
false
Ast.fst
Ast.prog_prune_actions
val prog_prune_actions (p: prog) : Tot prog
val prog_prune_actions (p: prog) : Tot prog
let prog_prune_actions (p: prog) : Tot prog = let (decls, refines) = p in (List.Tot.map decl_prune_actions decls, refines)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 50, "end_line": 1307, "start_col": 0, "start_line": 1303 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak" let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak let field_tag_equal (f0 f1:field) = match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false (* Pruning actions out of the surface ast (to generate validators checking Z3 test cases) *) let atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field' = { a with field_action = None } let atomic_field_prune_actions (a: atomic_field) : Tot atomic_field = { a with v = atomic_field'_prune_actions a.v } let rec field'_prune_actions (f: field') : Tot field' = match f with | AtomicField a -> AtomicField (atomic_field_prune_actions a) | RecordField r i -> RecordField (record_prune_actions r) i | SwitchCaseField s i -> SwitchCaseField (switch_case_prune_actions s) i and field_prune_actions (f: field) : Tot field = { f with v = field'_prune_actions f.v } and record_prune_actions (r: record) : Tot record = match r with | [] -> [] | f :: r' -> field_prune_actions f :: record_prune_actions r' and case_prune_actions (c: case) : Tot case = match c with | Case e f -> Case e (field_prune_actions f) | DefaultCase f -> DefaultCase (field_prune_actions f) and cases_prune_actions (l: list case) : Tot (list case) = match l with | [] -> [] | c :: l' -> case_prune_actions c :: cases_prune_actions l' and switch_case_prune_actions (s: switch_case) : Tot switch_case = let (e, l) = s in (e, cases_prune_actions l) let decl'_prune_actions (d: decl') : Tot decl' = match d with | ModuleAbbrev _ _ | Define _ _ _ | TypeAbbrev _ _ | Enum _ _ _ | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d | Record names params where fields -> Record names params where (record_prune_actions fields) | CaseType names params cases -> CaseType names params (switch_case_prune_actions cases) let decl_prune_actions (d: decl) : Tot decl = { d with d_decl = { d.d_decl with v = decl'_prune_actions d.d_decl.v } }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
p: Ast.prog -> Ast.prog
Prims.Tot
[ "total" ]
[]
[ "Ast.prog", "Prims.list", "Ast.decl", "FStar.Pervasives.Native.option", "Ast.type_refinement", "FStar.Pervasives.Native.Mktuple2", "FStar.List.Tot.Base.map", "Ast.decl_prune_actions" ]
[]
false
false
false
true
false
let prog_prune_actions (p: prog) : Tot prog =
let decls, refines = p in (List.Tot.map decl_prune_actions decls, refines)
false
Ast.fst
Ast.print_bitfield_bit_order
val print_bitfield_bit_order : _: Ast.bitfield_bit_order -> Prims.string
let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst"
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 26, "end_line": 945, "start_col": 0, "start_line": 943 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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 | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst"
false
Ast.fst
Ast.decl_prune_actions
val decl_prune_actions (d: decl) : Tot decl
val decl_prune_actions (d: decl) : Tot decl
let decl_prune_actions (d: decl) : Tot decl = { d with d_decl = { d.d_decl with v = decl'_prune_actions d.d_decl.v } }
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 74, "end_line": 1301, "start_col": 0, "start_line": 1298 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak" let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak let field_tag_equal (f0 f1:field) = match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false (* Pruning actions out of the surface ast (to generate validators checking Z3 test cases) *) let atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field' = { a with field_action = None } let atomic_field_prune_actions (a: atomic_field) : Tot atomic_field = { a with v = atomic_field'_prune_actions a.v } let rec field'_prune_actions (f: field') : Tot field' = match f with | AtomicField a -> AtomicField (atomic_field_prune_actions a) | RecordField r i -> RecordField (record_prune_actions r) i | SwitchCaseField s i -> SwitchCaseField (switch_case_prune_actions s) i and field_prune_actions (f: field) : Tot field = { f with v = field'_prune_actions f.v } and record_prune_actions (r: record) : Tot record = match r with | [] -> [] | f :: r' -> field_prune_actions f :: record_prune_actions r' and case_prune_actions (c: case) : Tot case = match c with | Case e f -> Case e (field_prune_actions f) | DefaultCase f -> DefaultCase (field_prune_actions f) and cases_prune_actions (l: list case) : Tot (list case) = match l with | [] -> [] | c :: l' -> case_prune_actions c :: cases_prune_actions l' and switch_case_prune_actions (s: switch_case) : Tot switch_case = let (e, l) = s in (e, cases_prune_actions l) let decl'_prune_actions (d: decl') : Tot decl' = match d with | ModuleAbbrev _ _ | Define _ _ _ | TypeAbbrev _ _ | Enum _ _ _ | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d | Record names params where fields -> Record names params where (record_prune_actions fields) | CaseType names params cases -> CaseType names params (switch_case_prune_actions cases)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
d: Ast.decl -> Ast.decl
Prims.Tot
[ "total" ]
[]
[ "Ast.decl", "Ast.Mkdecl", "Ast.Mkwith_meta_t", "Ast.decl'", "Ast.decl'_prune_actions", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.__proj__Mkdecl__item__d_decl", "Ast.__proj__Mkwith_meta_t__item__range", "Ast.__proj__Mkwith_meta_t__item__comments", "Ast.with_meta_t", "Ast.__proj__Mkdecl__item__d_exported" ]
[]
false
false
false
true
false
let decl_prune_actions (d: decl) : Tot decl =
{ d with d_decl = { d.d_decl with v = decl'_prune_actions d.d_decl.v } }
false
Ast.fst
Ast.subst_record
val subst_record (s: subst) (f: record) : ML record
val subst_record (s: subst) (f: record) : ML record
let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 57, "end_line": 895, "start_col": 0, "start_line": 868 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> f: Ast.record -> FStar.All.ML Ast.record
FStar.All.ML
[ "ml" ]
[ "subst_field", "subst_atomic_field", "subst_record", "subst_case", "subst_switch_case" ]
[ "Ast.subst", "Ast.record", "FStar.List.map", "Ast.with_meta_t", "Ast.field'", "Ast.subst_field", "Prims.list" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec subst_record (s: subst) (f: record) : ML record =
List.map (subst_field s) f
false
Hacl.Impl.Ed25519.RecoverX.fst
Hacl.Impl.Ed25519.RecoverX.is_0
val is_0: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.as_nat h x == F51.fevalh h x) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.fevalh h0 x == SC.zero)))
val is_0: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.as_nat h x == F51.fevalh h x) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.fevalh h0 x == SC.zero)))
let is_0 x = let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 =^ 0uL && u64_to_UInt64 x1 =^ 0uL && u64_to_UInt64 x2 =^ 0uL && u64_to_UInt64 x3 =^ 0uL && u64_to_UInt64 x4 =^ 0uL)
{ "file_name": "code/ed25519/Hacl.Impl.Ed25519.RecoverX.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 27, "end_line": 41, "start_col": 0, "start_line": 29 }
module Hacl.Impl.Ed25519.RecoverX module ST = FStar.HyperStack.ST open FStar.HyperStack.All open FStar.Mul open Lib.IntTypes open Lib.Buffer open Hacl.Bignum25519 module F51 = Hacl.Impl.Ed25519.Field51 module S51 = Hacl.Spec.Curve25519.Field51.Definition module SC = Spec.Curve25519 module SE = Spec.Ed25519 #reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0" inline_for_extraction noextract let elemB = lbuffer uint64 5ul val is_0: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.as_nat h x == F51.fevalh h x) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.fevalh h0 x == SC.zero)))
{ "checked_file": "/", "dependencies": [ "Spec.Ed25519.fst.checked", "Spec.Curve25519.fst.checked", "prims.fst.checked", "Lib.RawIntTypes.fsti.checked", "Lib.IntTypes.Compatibility.fst.checked", "Lib.IntTypes.fsti.checked", "Lib.Buffer.fsti.checked", "Hacl.Spec.Curve25519.Field51.Definition.fst.checked", "Hacl.Impl.Ed25519.Pow2_252m2.fst.checked", "Hacl.Impl.Ed25519.Field51.fst.checked", "Hacl.Bignum25519.fsti.checked", "FStar.UInt8.fsti.checked", "FStar.UInt64.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.All.fst.checked" ], "interface_file": false, "source_file": "Hacl.Impl.Ed25519.RecoverX.fst" }
[ { "abbrev": true, "full_module": "Spec.Ed25519", "short_module": "SE" }, { "abbrev": true, "full_module": "Spec.Curve25519", "short_module": "SC" }, { "abbrev": true, "full_module": "Hacl.Spec.Curve25519.Field51.Definition", "short_module": "S51" }, { "abbrev": true, "full_module": "Hacl.Impl.Ed25519.Field51", "short_module": "F51" }, { "abbrev": false, "full_module": "Hacl.Bignum25519", "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": true, "full_module": "FStar.HyperStack.ST", "short_module": "ST" }, { "abbrev": false, "full_module": "Hacl.Impl.Ed25519", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Impl.Ed25519", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: Hacl.Impl.Ed25519.RecoverX.elemB -> FStar.HyperStack.ST.Stack Prims.bool
FStar.HyperStack.ST.Stack
[]
[]
[ "Hacl.Impl.Ed25519.RecoverX.elemB", "Prims.op_AmpAmp", "FStar.UInt64.op_Equals_Hat", "Lib.RawIntTypes.u64_to_UInt64", "FStar.UInt64.__uint_to_t", "Prims.bool", "Lib.IntTypes.int_t", "Lib.IntTypes.U64", "Lib.IntTypes.SEC", "Lib.Buffer.op_Array_Access", "Lib.Buffer.MUT", "Lib.IntTypes.uint64", "FStar.UInt32.__uint_to_t" ]
[]
false
true
false
false
false
let is_0 x =
let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 =^ 0uL && u64_to_UInt64 x1 =^ 0uL && u64_to_UInt64 x2 =^ 0uL && u64_to_UInt64 x3 =^ 0uL && u64_to_UInt64 x4 =^ 0uL)
false
Ast.fst
Ast.atomic_field'_prune_actions
val atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field'
val atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field'
let atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field' = { a with field_action = None }
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 32, "end_line": 1242, "start_col": 0, "start_line": 1239 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak" let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak let field_tag_equal (f0 f1:field) = match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false (* Pruning actions out of the surface ast (to generate validators checking Z3 test cases) *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
a: Ast.atomic_field' -> Ast.atomic_field'
Prims.Tot
[ "total" ]
[]
[ "Ast.atomic_field'", "Ast.Mkatomic_field'", "Ast.__proj__Mkatomic_field'__item__field_dependence", "Ast.__proj__Mkatomic_field'__item__field_ident", "Ast.__proj__Mkatomic_field'__item__field_type", "Ast.__proj__Mkatomic_field'__item__field_array_opt", "Ast.__proj__Mkatomic_field'__item__field_constraint", "Ast.__proj__Mkatomic_field'__item__field_bitwidth", "FStar.Pervasives.Native.None", "FStar.Pervasives.Native.tuple2", "Ast.action", "Prims.bool", "Ast.__proj__Mkatomic_field'__item__field_probe" ]
[]
false
false
false
true
false
let atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field' =
{ a with field_action = None }
false
Hacl.HMAC.fst
Hacl.HMAC.mk_compute
val mk_compute: i: D.fixed_len_impl -> hash: D.hash_st (D.get_alg i) -> alloca: D.alloca_st i -> init: D.init_st i -> update_multi: D.update_multi_st i -> update_last: D.update_last_st i -> finish: D.finish_st i -> compute_st (D.get_alg i)
val mk_compute: i: D.fixed_len_impl -> hash: D.hash_st (D.get_alg i) -> alloca: D.alloca_st i -> init: D.init_st i -> update_multi: D.update_multi_st i -> update_last: D.update_last_st i -> finish: D.finish_st i -> compute_st (D.get_alg i)
let mk_compute i hash alloca init update_multi update_last finish dst key key_len data data_len = [@inline_let] let a = D.get_alg i in [@inline_let] let m = D.get_spec i in block_len_positive a; hash_lt_block a; (**) let h0 = ST.get() in push_frame (); (**) let h1 = ST.get () in let l = D.block_len a in let key_block = B.alloca (u8 0x00) l in mk_wrap_key a hash key_block key key_len; (**) let h2 = ST.get () in (**) assert (B.as_seq h2 key_block `Seq.equal` wrap a (B.as_seq h0 key)); let ipad = B.alloca (u8 0x36) l in xor_bytes_inplace ipad key_block l; (**) let h3 = ST.get () in (**) assert (B.as_seq h3 ipad `Seq.equal` S.(xor (u8 0x36) (wrap a (B.as_seq h0 key)))); let opad = B.alloca (u8 0x5c) l in xor_bytes_inplace opad key_block l; (**) let h4 = ST.get () in (**) assert B.(modifies (loc_buffer key_block `loc_union` loc_buffer ipad (**) `loc_union` loc_buffer opad) h1 h4); (**) S.lemma_eq_intro (B.as_seq h4 ipad) (S.(xor (u8 0x36) (wrap a (B.as_seq h0 key)))); (**) S.lemma_eq_intro (B.as_seq h4 opad) (S.(xor (u8 0x5c) (wrap a (B.as_seq h0 key)))); (**) S.lemma_eq_intro (B.as_seq h4 data) (B.as_seq h0 data); let s = alloca () in part1 a m init update_multi update_last finish s ipad data data_len; (**) key_and_data_fits a; (**) let h5 = ST.get () in (**) S.lemma_eq_intro (S.slice (B.as_seq h5 ipad) 0 (hash_length a)) (**) (Spec.Agile.Hash.hash a S.(append (xor (u8 0x36) (wrap a (B.as_seq h0 key))) (**) (B.as_seq h0 data))); let hash1 = B.sub ipad 0ul (D.hash_len a) in init s; part2 a m init update_multi update_last finish s dst opad hash1 (D.hash_len a); (**) let h6 = ST.get () in (**) assert (B.as_seq h6 dst `S.equal` hmac a (B.as_seq h0 key) (B.as_seq h0 data)); pop_frame (); (**) let h7 = ST.get () in (**) assert B.(modifies (loc_buffer key_block `loc_union` loc_buffer ipad `loc_union` (**) loc_buffer opad `loc_union` loc_buffer s) h1 h2); (**) LowStar.Monotonic.Buffer.modifies_fresh_frame_popped h0 h1 (B.loc_buffer dst) h6 h7
{ "file_name": "code/hmac/Hacl.HMAC.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 90, "end_line": 430, "start_col": 0, "start_line": 389 }
module Hacl.HMAC module S = FStar.Seq module D = Hacl.Hash.Definitions module ST = FStar.HyperStack.ST module B = LowStar.Buffer module MB = LowStar.Monotonic.Buffer module C = Hacl.Impl.Blake2.Core open FStar.HyperStack.ST open LowStar.BufferOps open Spec.Hash.Definitions open Spec.Agile.HMAC open Spec.Agile.Hash open Spec.Hash.Incremental open Spec.Hash.Incremental.Definitions open Spec.Hash.Lemmas friend Spec.Agile.HMAC friend Spec.Agile.Hash let _: squash (inversion hash_alg) = allow_inversion hash_alg #set-options "--max_fuel 0 --max_ifuel 0 --z3rlimit 50" /// Helpers inline_for_extraction val xor_bytes_inplace: a: B.buffer uint8 -> b: B.buffer uint8 -> len: UInt32.t {v len = B.length a /\ v len = B.length b} -> Stack unit (requires fun h0 -> B.disjoint a b /\ B.live h0 a /\ B.live h0 b) (ensures fun h0 _ h1 -> B.(modifies (loc_buffer a) h0 h1) /\ B.as_seq h1 a == Spec.Loops.seq_map2 ( ^. ) (B.as_seq h0 a) (B.as_seq h0 b)) inline_for_extraction let xor_bytes_inplace a b len = C.Loops.in_place_map2 a b len ( ^. ) /// Agile implementation // we rely on the output being zero-initialized for the correctness of padding inline_for_extraction noextract let wrap_key_st (a: fixed_len_alg) = output: B.buffer uint8 { B.length output == block_length a } -> key: B.buffer uint8 {B.length key `less_than_max_input_length` a /\ B.disjoint output key} -> len: UInt32.t {v len = B.length key} -> Stack unit (requires fun h0 -> B.live h0 output /\ B.live h0 key /\ B.as_seq h0 output == Seq.create (block_length a) (u8 0)) (ensures fun h0 _ h1 -> B.(modifies (loc_buffer output) h0 h1) /\ B.as_seq h1 output == wrap a (B.as_seq h0 key)) /// This one is only to avoid a warning about a pattern that is not encoding properly. inline_for_extraction let helper_smtpat (a: fixed_len_alg) (len: uint32_t{ v len `less_than_max_input_length` a }): x:uint32_t { x `FStar.UInt32.lte` D.block_len a } = if len `FStar.UInt32.lte` D.block_len a then len else D.hash_len a #set-options "--z3rlimit 40" inline_for_extraction noextract let mk_wrap_key (a: fixed_len_alg) (hash: D.hash_st a): wrap_key_st a = fun output key len -> [@inline_let] //18-08-02 does *not* prevents unused-but-set-variable warning in C let i = helper_smtpat a len in let nkey = B.sub output 0ul i in let zeroes = B.sub output i (D.block_len a `FStar.UInt32.sub` i) in LowStar.Ignore.ignore zeroes; (**) assert B.(loc_disjoint (loc_buffer nkey) (loc_buffer zeroes)); (**) let h0 = ST.get () in (**) assert (Seq.equal (B.as_seq h0 zeroes) (Seq.create (v (D.block_len a `FStar.UInt32.sub` i)) (u8 0))); if len `FStar.UInt32.lte` D.block_len a then begin B.blit key 0ul nkey 0ul len; let h1 = ST.get () in (**) assert (Seq.equal (B.as_seq h1 zeroes) (B.as_seq h0 zeroes)); (**) assert (Seq.equal (B.as_seq h1 nkey) (B.as_seq h0 key)); (**) assert (Seq.equal (B.as_seq h1 output) (S.append (B.as_seq h1 nkey) (B.as_seq h1 zeroes))); (**) Seq.lemma_eq_elim (B.as_seq h1 output) (S.append (B.as_seq h1 nkey) (B.as_seq h1 zeroes)); (**) assert (B.as_seq h1 output == wrap a (B.as_seq h0 key)) end else begin hash nkey key len; (**) let h1 = ST.get () in (**) assert (Seq.equal (B.as_seq h1 zeroes) (B.as_seq h0 zeroes)); (**) assert (Seq.equal (B.as_seq h1 nkey) (Spec.Agile.Hash.hash a (B.as_seq h0 key))); (**) assert (Seq.equal (B.as_seq h1 output) (S.append (B.as_seq h1 nkey) (B.as_seq h1 zeroes))); (**) Seq.lemma_eq_elim (B.as_seq h1 output) (S.append (B.as_seq h1 nkey) (B.as_seq h1 zeroes)); (**) assert (B.as_seq h1 output == wrap a (B.as_seq h0 key)) end inline_for_extraction noextract let block_len_as_len (a: fixed_len_alg { not (is_keccak a) }): Tot (l:len_t a { len_v a l = block_length a }) = let open FStar.Int.Cast.Full in assert_norm (128 < pow2 32); match a with | MD5 | SHA1 | SHA2_224 | SHA2_256 | Blake2S -> uint32_to_uint64 (D.block_len a) | SHA2_384 | SHA2_512 | Blake2B -> uint64_to_uint128 (uint32_to_uint64 (D.block_len a)) /// This implementation is optimized by reusing an existing hash state ``s`` /// rather than allocating a new one. Note that the disjointness hypotheses are /// voluntarily very loose (in particular, the hash state and the key are not /// necessarily disjoint). inline_for_extraction noextract val part2: a: fixed_len_alg -> m : D.m_spec a -> init: D.init_st (|a, m|) -> update_multi: D.update_multi_st (|a, m|) -> update_last: D.update_last_st (|a, m|) -> finish: D.finish_st (|a, m|) -> s: D.state (|a, m|) -> dst: B.buffer uint8 { B.length dst = hash_length a } -> key: B.buffer uint8 { B.length key = block_length a } -> data: B.buffer uint8 -> len: UInt32.t { B.length data = v len } -> Stack unit (requires fun h0 -> B.disjoint s key /\ B.disjoint s data /\ B.disjoint s dst /\ MB.(all_live h0 [ buf s; buf dst; buf key; buf data ]) /\ D.as_seq h0 s == Spec.Agile.Hash.init a ) (ensures fun h0 _ h1 -> key_and_data_fits a; B.(modifies (loc_union (loc_buffer s) (loc_buffer dst)) h0 h1) /\ B.as_seq h1 dst `Seq.equal` Spec.Agile.Hash.hash a (S.append (B.as_seq h0 key) (B.as_seq h0 data))) // TODO: move (* We can't directly introduce uint128 literals *) inline_for_extraction noextract let zero_to_len (a:hash_alg) : (if is_keccak a then unit else (x:len_t a { len_v a x == 0 })) = match a with | MD5 | SHA1 | SHA2_224 | SHA2_256 | Blake2S -> UInt64.uint_to_t 0 | SHA2_384 | SHA2_512 | Blake2B -> FStar.Int.Cast.Full.uint64_to_uint128 (UInt64.uint_to_t 0) | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> () inline_for_extraction noextract val part2_update_empty: a: fixed_len_alg -> m : D.m_spec a -> init: D.init_st (|a, m|) -> update_multi: D.update_multi_st (|a, m|) -> update_last: D.update_last_st (|a, m|) -> s: D.state (|a, m|) -> key: B.buffer uint8 { B.length key = block_length a } -> data: B.buffer uint8 -> len: UInt32.t { B.length data = v len } -> Stack unit (requires fun h0 -> v len = 0 /\ B.disjoint s key /\ B.disjoint s data /\ MB.(all_live h0 [ buf s; buf key; buf data ])) (ensures fun h0 _ h1 -> key_and_data_fits a; B.(modifies (loc_buffer s) h0 h1) /\ (let bs, l = split_blocks a (S.append (B.as_seq h0 key) (B.as_seq h0 data)) in D.as_seq h1 s `Seq.equal` Spec.Hash.Incremental.Definitions.update_last a (Spec.Agile.Hash.update_multi a (D.as_seq h0 s) (init_extra_state a) bs) (if is_keccak a then () else S.length bs) l)) let lemma_split_one_block (a:hash_alg) (s:bytes) : Lemma (requires S.length s == block_length a) (ensures (key_and_data_fits a; split_blocks a s == (S.empty, s))) = () let part2_update_empty a m init update_multi update_last s key data len = (**) let h0 = ST.get () in (**) let key_v0 : Ghost.erased _ = B.as_seq h0 key in (**) let data_v0 : Ghost.erased _ = B.as_seq h0 data in (**) let key_data_v0 : Ghost.erased _ = Seq.append key_v0 data_v0 in (**) key_and_data_fits a; update_last s (zero_to_len a) key (D.block_len a); (**) assert(key_data_v0 `S.equal` key_v0); (if not (is_blake a) then (**) Spec.Hash.Lemmas.update_multi_zero a (D.as_seq h0 s) else (**) Spec.Hash.Lemmas.update_multi_zero_blake a 0 (D.as_seq h0 s)); (**) lemma_split_one_block a key_v0 inline_for_extraction noextract let uint32_to_ev (a:hash_alg) (n:UInt32.t{v n % block_length a == 0}) : ev:D.extra_state a {if is_blake a then D.ev_v #a ev == v n else True} = match a with | MD5 | SHA1 | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> () | Blake2S -> FStar.Int.Cast.uint32_to_uint64 n | Blake2B -> FStar.Int.Cast.Full.uint64_to_uint128 (FStar.Int.Cast.uint32_to_uint64 n) noextract inline_for_extraction val len_add32 (a: hash_alg{not (is_keccak a)}) (prev_len: len_t a) (input_len: UInt32.t { (UInt32.v input_len + len_v a prev_len) `less_than_max_input_length` a }): x:len_t a { len_v a x = len_v a prev_len + UInt32.v input_len } noextract inline_for_extraction let len_add32 a prev_len input_len = let open FStar.Int.Cast.Full in match a with | SHA2_224 | SHA2_256 | MD5 | SHA1 | Blake2S -> assert_norm (pow2 61 < pow2 64); FStar.UInt64.(prev_len +^ uint32_to_uint64 input_len) | SHA2_384 | SHA2_512 | Blake2B -> assert_norm (pow2 125 < pow2 128); FStar.UInt128.(prev_len +^ uint64_to_uint128 (uint32_to_uint64 input_len)) inline_for_extraction noextract val part2_update_nonempty: a: fixed_len_alg -> m : D.m_spec a -> init: D.init_st (|a, m|) -> update_multi: D.update_multi_st (|a, m|) -> update_last: D.update_last_st (|a, m|) -> s: D.state (|a, m|) -> key: B.buffer uint8 { B.length key = block_length a } -> data: B.buffer uint8 -> len: UInt32.t { B.length data = v len } -> Stack unit (requires fun h0 -> v len > 0 /\ B.disjoint s key /\ B.disjoint s data /\ MB.(all_live h0 [ buf s; buf key; buf data ])) (ensures fun h0 _ h1 -> key_and_data_fits a; B.(modifies (loc_buffer s) h0 h1) /\ (let bs, l = split_blocks a (S.append (B.as_seq h0 key) (B.as_seq h0 data)) in D.as_seq h1 s `Seq.equal` Spec.Hash.Incremental.Definitions.update_last a (Spec.Agile.Hash.update_multi a (D.as_seq h0 s) (init_extra_state a) bs) (if is_keccak a then () else S.length bs) l)) open FStar.Mul val split_nb_rem_extend_one_block (l:pos) (d:pos) : Lemma ( let nb, rem = Lib.UpdateMulti.split_at_last_lazy_nb_rem l (d + l) in let nb', rem' = Lib.UpdateMulti.split_at_last_lazy_nb_rem l d in rem == rem' /\ nb == nb' + 1) let split_nb_rem_extend_one_block l d = FStar.Math.Lemmas.add_div_mod_1 d l #push-options "--z3rlimit 400" let part2_update_nonempty a m init update_multi update_last s key data len = (**) let h0 = ST.get () in (**) let key_v0 : Ghost.erased _ = B.as_seq h0 key in (**) let data_v0 : Ghost.erased _ = B.as_seq h0 data in (**) let key_data_v0 : Ghost.erased _ = Seq.append key_v0 data_v0 in (**) key_and_data_fits a; let block_len = D.block_len a in let n_blocks, rem_len = Lib.UpdateMulti.split_at_last_st block_len len in let full_blocks_len = n_blocks `FStar.UInt32.mul` block_len in let full_blocks = B.sub data 0ul full_blocks_len in let rem = B.sub data full_blocks_len rem_len in (**) assert (S.length key_data_v0 == v len + block_length a); (**) split_nb_rem_extend_one_block (block_length a) (v len); (**) assert (let bs, l = split_blocks a key_data_v0 in bs `S.equal` (key_v0 `S.append` B.as_seq h0 full_blocks) /\ l `S.equal` B.as_seq h0 rem); [@inline_let] let ev = if is_blake a then zero_to_len a else () in (**) assert (D.ev_v ev == init_extra_state a); (**) assert (B.length key == block_length a * 1); update_multi s ev key 1ul; (**) let h1 = ST.get () in (**) assert (D.as_seq h1 s == (**) Spec.Agile.Hash.(update_multi a (D.as_seq h0 s) (init_extra_state a) key_v0)); [@inline_let] let ev1 = uint32_to_ev a block_len in update_multi s ev1 full_blocks n_blocks; (**) let h2 = ST.get () in (**) let aux () : Lemma (D.as_seq h2 s == Spec.Agile.Hash.(update_multi a (D.as_seq h0 s) (init_extra_state a) (S.append key_v0 (B.as_seq h0 full_blocks)))) (**) = if is_blake a then (**) update_multi_associative_blake a (D.as_seq h0 s) (init_extra_state a) (v block_len) key_v0 (B.as_seq h0 full_blocks) (**) else (**) update_multi_associative a (D.as_seq h0 s) key_v0 (B.as_seq h0 full_blocks) (**) in (**) aux (); [@inline_let] let prev_len: prev_len:D.prev_len_t a { if is_keccak a then True else len_v a prev_len % block_length a = 0 } = if is_keccak a then () else len_add32 a (block_len_as_len a) full_blocks_len in update_last s prev_len rem rem_len #pop-options inline_for_extraction noextract let part2 a m init update_multi update_last finish s dst key data len = (**) key_and_data_fits a; (**) let h0 = ST.get () in (**) let key_v0 : Ghost.erased _ = B.as_seq h0 key in (**) let data_v0 : Ghost.erased _ = B.as_seq h0 data in (**) let key_data_v0 : Ghost.erased _ = Seq.append key_v0 data_v0 in (**) let h1 = ST.get () in (**) assert(B.(modifies (loc_buffer s) h0 h1)); (**) let init_v : Ghost.erased (init_t a) = Spec.Agile.Hash.init a in (**) assert (D.as_seq h1 s == Ghost.reveal init_v); if len = 0ul then ( part2_update_empty a m init update_multi update_last s key data len ) else ( part2_update_nonempty a m init update_multi update_last s key data len ); (**) let h3 = ST.get () in (**) B.(modifies_trans (loc_union (loc_buffer s) (loc_buffer dst)) h0 h1 (loc_union (loc_buffer s) (loc_buffer dst)) h3); finish s dst; (**) let h4 = ST.get () in (**) B.(modifies_trans (loc_union (loc_buffer s) (loc_buffer dst)) h0 h3 (loc_union (loc_buffer s) (loc_buffer dst)) h4); (**) assert (B.as_seq h4 dst == hash_incremental a key_data_v0 ()); calc (Seq.equal) { B.as_seq h4 dst; (Seq.equal) { } hash_incremental a key_data_v0 (); (Seq.equal) { hash_is_hash_incremental' a key_data_v0 () } hash' a key_data_v0 (); (Seq.equal) { } hash a key_data_v0; } /// This implementation is optimized. First, it reuses an existing hash state /// ``s`` rather than allocating a new one. Second, it writes out the result of /// the hash directly in its parameter ``key`` rather than taking a destination /// output buffer. inline_for_extraction noextract val part1: a: fixed_len_alg -> m : D.m_spec a -> init: D.init_st (|a, m|) -> update_multi: D.update_multi_st (|a, m|) -> update_last: D.update_last_st (|a, m|) -> finish: D.finish_st (|a, m|) -> s: D.state (|a, m|) -> key: B.buffer uint8 { B.length key = block_length a } -> data: B.buffer uint8 -> len: UInt32.t { B.length data = v len } -> Stack unit (requires fun h0 -> B.disjoint s key /\ B.disjoint s data /\ MB.(all_live h0 [ buf s; buf key; buf data ]) /\ D.as_seq h0 s == Spec.Agile.Hash.init a ) (ensures fun h0 _ h1 -> key_and_data_fits a; B.(modifies (loc_union (loc_buffer s) (loc_buffer key)) h0 h1) /\ S.slice (B.as_seq h1 key) 0 (hash_length a) `Seq.equal` Spec.Agile.Hash.hash a (S.append (B.as_seq h0 key) (B.as_seq h0 data))) let part1 a m init update_multi update_last finish s key data len = let dst = B.sub key 0ul (D.hash_len a) in part2 a m init update_multi update_last finish s dst key data len let block_len_positive (a: hash_alg): Lemma (D.block_len a `FStar.UInt32.gt` 0ul) = () let hash_lt_block (a: fixed_len_alg): Lemma (hash_length a < block_length a) = ()
{ "checked_file": "/", "dependencies": [ "Spec.Loops.fst.checked", "Spec.Hash.Lemmas.fsti.checked", "Spec.Hash.Incremental.Definitions.fst.checked", "Spec.Hash.Incremental.fsti.checked", "Spec.Hash.Definitions.fst.checked", "Spec.Agile.HMAC.fst.checked", "Spec.Agile.HMAC.fst.checked", "Spec.Agile.Hash.fst.checked", "Spec.Agile.Hash.fst.checked", "prims.fst.checked", "LowStar.Monotonic.Buffer.fsti.checked", "LowStar.Ignore.fsti.checked", "LowStar.BufferOps.fst.checked", "LowStar.Buffer.fst.checked", "Lib.UpdateMulti.fst.checked", "Hacl.Streaming.SHA2.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Hash.SHA2.fsti.checked", "Hacl.Hash.SHA1.fsti.checked", "Hacl.Hash.Definitions.fst.checked", "Hacl.Hash.Blake2s_32.fsti.checked", "Hacl.Hash.Blake2b_32.fsti.checked", "FStar.UInt64.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt128.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.Int.Cast.Full.fst.checked", "FStar.Int.Cast.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.Ghost.fsti.checked", "FStar.Calc.fsti.checked", "C.Loops.fst.checked" ], "interface_file": true, "source_file": "Hacl.HMAC.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Lemmas", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Incremental.Definitions", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Incremental", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile.Hash", "short_module": null }, { "abbrev": false, "full_module": "LowStar.BufferOps", "short_module": null }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "C" }, { "abbrev": true, "full_module": "LowStar.Monotonic.Buffer", "short_module": "MB" }, { "abbrev": true, "full_module": "FStar.HyperStack.ST", "short_module": "ST" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "EverCrypt.Helpers", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile.HMAC", "short_module": null }, { "abbrev": true, "full_module": "Hacl.Hash.Definitions", "short_module": "D" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": false, "full_module": "Hacl", "short_module": null }, { "abbrev": false, "full_module": "Hacl", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": 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": 200, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
i: Hacl.Hash.Definitions.fixed_len_impl -> hash: Hacl.Hash.Definitions.hash_st (Hacl.Hash.Definitions.get_alg i) -> alloca: Hacl.Hash.Definitions.alloca_st i -> init: Hacl.Hash.Definitions.init_st i -> update_multi: Hacl.Hash.Definitions.update_multi_st i -> update_last: Hacl.Hash.Definitions.update_last_st i -> finish: Hacl.Hash.Definitions.finish_st i -> Hacl.HMAC.compute_st (Hacl.Hash.Definitions.get_alg i)
Prims.Tot
[ "total" ]
[]
[ "Hacl.Hash.Definitions.fixed_len_impl", "Hacl.Hash.Definitions.hash_st", "Hacl.Hash.Definitions.get_alg", "Hacl.Hash.Definitions.alloca_st", "Hacl.Hash.Definitions.init_st", "Hacl.Hash.Definitions.update_multi_st", "Hacl.Hash.Definitions.update_last_st", "Hacl.Hash.Definitions.finish_st", "LowStar.Buffer.buffer", "Lib.IntTypes.uint8", "Prims.eq2", "Prims.nat", "LowStar.Monotonic.Buffer.length", "LowStar.Buffer.trivial_preorder", "Spec.Hash.Definitions.hash_length", "Prims.l_and", "Spec.Agile.HMAC.keysized", "LowStar.Monotonic.Buffer.disjoint", "FStar.UInt32.t", "Prims.b2t", "Prims.op_Equality", "Prims.int", "Prims.l_or", "FStar.UInt.size", "FStar.UInt32.n", "Prims.op_GreaterThanOrEqual", "FStar.UInt32.v", "Prims.op_LessThan", "Prims.op_Addition", "Spec.Hash.Definitions.block_length", "Prims.pow2", "LowStar.Monotonic.Buffer.modifies_fresh_frame_popped", "LowStar.Monotonic.Buffer.loc_buffer", "Prims.unit", "Prims._assert", "LowStar.Monotonic.Buffer.modifies", "LowStar.Monotonic.Buffer.loc_union", "Hacl.Hash.Definitions.impl_word", "FStar.Monotonic.HyperStack.mem", "FStar.HyperStack.ST.get", "FStar.HyperStack.ST.pop_frame", "FStar.Seq.Base.equal", "LowStar.Monotonic.Buffer.as_seq", "Spec.Agile.HMAC.hmac", "Hacl.HMAC.part2", "Hacl.Hash.Definitions.hash_len", "LowStar.Monotonic.Buffer.mbuffer", "Lib.IntTypes.int_t", "Lib.IntTypes.U8", "Lib.IntTypes.SEC", "LowStar.Buffer.sub", "FStar.UInt32.__uint_to_t", "FStar.Ghost.hide", "FStar.Seq.Base.lemma_eq_intro", "FStar.Seq.Base.slice", "Spec.Agile.Hash.hash", "FStar.Seq.Base.append", "Spec.Agile.HMAC.xor", "Lib.IntTypes.u8", "Spec.Agile.HMAC.wrap", "Hacl.HMAC.key_and_data_fits", "Hacl.HMAC.part1", "Hacl.Hash.Definitions.state", "Hacl.HMAC.xor_bytes_inplace", "Prims.op_Negation", "LowStar.Monotonic.Buffer.g_is_null", "LowStar.Buffer.alloca", "Hacl.HMAC.mk_wrap_key", "Lib.IntTypes.U32", "Lib.IntTypes.PUB", "Lib.IntTypes.range", "Prims.op_disEquality", "Lib.IntTypes.v", "Hacl.Hash.Definitions.block_len", "FStar.HyperStack.ST.push_frame", "Hacl.HMAC.hash_lt_block", "Hacl.HMAC.block_len_positive", "Hacl.Hash.Definitions.m_spec", "Hacl.Hash.Definitions.get_spec", "Spec.Hash.Definitions.hash_alg" ]
[]
false
false
false
false
false
let mk_compute i hash alloca init update_multi update_last finish dst key key_len data data_len =
[@@ inline_let ]let a = D.get_alg i in [@@ inline_let ]let m = D.get_spec i in block_len_positive a; hash_lt_block a; let h0 = ST.get () in push_frame (); let h1 = ST.get () in let l = D.block_len a in let key_block = B.alloca (u8 0x00) l in mk_wrap_key a hash key_block key key_len; let h2 = ST.get () in assert ((B.as_seq h2 key_block) `Seq.equal` (wrap a (B.as_seq h0 key))); let ipad = B.alloca (u8 0x36) l in xor_bytes_inplace ipad key_block l; let h3 = ST.get () in assert ((B.as_seq h3 ipad) `Seq.equal` S.(xor (u8 0x36) (wrap a (B.as_seq h0 key)))); let opad = B.alloca (u8 0x5c) l in xor_bytes_inplace opad key_block l; let h4 = ST.get () in assert B.(modifies (((loc_buffer key_block) `loc_union` (loc_buffer ipad)) `loc_union` (loc_buffer opad)) h1 h4); S.lemma_eq_intro (B.as_seq h4 ipad) (let open S in xor (u8 0x36) (wrap a (B.as_seq h0 key))); S.lemma_eq_intro (B.as_seq h4 opad) (let open S in xor (u8 0x5c) (wrap a (B.as_seq h0 key))); S.lemma_eq_intro (B.as_seq h4 data) (B.as_seq h0 data); let s = alloca () in part1 a m init update_multi update_last finish s ipad data data_len; key_and_data_fits a; let h5 = ST.get () in S.lemma_eq_intro (S.slice (B.as_seq h5 ipad) 0 (hash_length a)) (Spec.Agile.Hash.hash a S.(append (xor (u8 0x36) (wrap a (B.as_seq h0 key))) (B.as_seq h0 data))); let hash1 = B.sub ipad 0ul (D.hash_len a) in init s; part2 a m init update_multi update_last finish s dst opad hash1 (D.hash_len a); let h6 = ST.get () in assert ((B.as_seq h6 dst) `S.equal` (hmac a (B.as_seq h0 key) (B.as_seq h0 data))); pop_frame (); let h7 = ST.get () in assert B.(modifies ((((loc_buffer key_block) `loc_union` (loc_buffer ipad)) `loc_union` (loc_buffer opad)) `loc_union` (loc_buffer s)) h1 h2); LowStar.Monotonic.Buffer.modifies_fresh_frame_popped h0 h1 (B.loc_buffer dst) h6 h7
false
Ast.fst
Ast.print_opt
val print_opt (o: option 'a) (f: ('a -> string)) : string
val print_opt (o: option 'a) (f: ('a -> string)) : string
let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 17, "end_line": 1082, "start_col": 0, "start_line": 1079 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p))))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: FStar.Pervasives.Native.option 'a -> f: (_: 'a -> Prims.string) -> Prims.string
Prims.Tot
[ "total" ]
[]
[ "FStar.Pervasives.Native.option", "Prims.string" ]
[]
false
false
false
true
false
let print_opt (o: option 'a) (f: ('a -> string)) : string =
match o with | None -> "" | Some x -> f x
false
Hacl.Impl.Ed25519.RecoverX.fst
Hacl.Impl.Ed25519.RecoverX.recover_x
val recover_x: x:lbuffer uint64 5ul -> y:lbuffer uint64 5ul -> sign:uint64{v sign = 0 \/ v sign = 1} -> Stack bool (requires fun h -> live h x /\ live h y /\ disjoint x y /\ F51.mul_inv_t h x /\ F51.felem_fits h y (1, 1, 1, 1, 1) ) (ensures fun h0 z h1 -> modifies (loc x) h0 h1 /\ (z ==> F51.mul_inv_t h1 x) /\ (let res = SE.recover_x (F51.as_nat h0 y) (uint_v #U64 sign <> 0) in (Some? res <==> z) /\ (Some? res ==> F51.fevalh h1 x == Some?.v res)) )
val recover_x: x:lbuffer uint64 5ul -> y:lbuffer uint64 5ul -> sign:uint64{v sign = 0 \/ v sign = 1} -> Stack bool (requires fun h -> live h x /\ live h y /\ disjoint x y /\ F51.mul_inv_t h x /\ F51.felem_fits h y (1, 1, 1, 1, 1) ) (ensures fun h0 z h1 -> modifies (loc x) h0 h1 /\ (z ==> F51.mul_inv_t h1 x) /\ (let res = SE.recover_x (F51.as_nat h0 y) (uint_v #U64 sign <> 0) in (Some? res <==> z) /\ (Some? res ==> F51.fevalh h1 x == Some?.v res)) )
let recover_x x y sign = push_frame(); let tmp = create 15ul (u64 0) in let res = recover_x_ x y sign tmp in pop_frame(); res
{ "file_name": "code/ed25519/Hacl.Impl.Ed25519.RecoverX.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 5, "end_line": 324, "start_col": 0, "start_line": 319 }
module Hacl.Impl.Ed25519.RecoverX module ST = FStar.HyperStack.ST open FStar.HyperStack.All open FStar.Mul open Lib.IntTypes open Lib.Buffer open Hacl.Bignum25519 module F51 = Hacl.Impl.Ed25519.Field51 module S51 = Hacl.Spec.Curve25519.Field51.Definition module SC = Spec.Curve25519 module SE = Spec.Ed25519 #reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0" inline_for_extraction noextract let elemB = lbuffer uint64 5ul val is_0: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.as_nat h x == F51.fevalh h x) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.fevalh h0 x == SC.zero))) [@CInline] let is_0 x = let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 =^ 0uL && u64_to_UInt64 x1 =^ 0uL && u64_to_UInt64 x2 =^ 0uL && u64_to_UInt64 x3 =^ 0uL && u64_to_UInt64 x4 =^ 0uL) inline_for_extraction noextract val gte_q: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.felem_fits h x (1, 1, 1, 1, 1)) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.as_nat h0 x >= SC.prime))) let gte_q x = let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 >=^ 0x7ffffffffffeduL && u64_to_UInt64 x1 =^ 0x7ffffffffffffuL && u64_to_UInt64 x2 =^ 0x7ffffffffffffuL && u64_to_UInt64 x3 =^ 0x7ffffffffffffuL && u64_to_UInt64 x4 =^ 0x7ffffffffffffuL) val mul_modp_sqrt_m1: x:elemB -> Stack unit (requires fun h -> live h x /\ F51.mul_inv_t h x) (ensures fun h0 _ h1 -> modifies (loc x) h0 h1 /\ F51.mul_inv_t h1 x /\ F51.fevalh h1 x == F51.fevalh h0 x `SC.fmul` SE.modp_sqrt_m1) [@CInline] let mul_modp_sqrt_m1 x = [@inline_let] let (x0, x1, x2, x3, x4) = (u64 0x00061b274a0ea0b0, u64 0x0000d5a5fc8f189d, u64 0x0007ef5e9cbd0c60, u64 0x00078595a6804c9e, u64 0x0002b8324804fc1d) in push_frame(); let sqrt_m1 = create 5ul (u64 0) in make_u64_5 sqrt_m1 x0 x1 x2 x3 x4; assert_norm (S51.as_nat5 (x0, x1, x2, x3, x4) == SE.modp_sqrt_m1); fmul x x sqrt_m1; pop_frame() inline_for_extraction noextract val x_mod_2: x:felem -> Stack uint64 (requires fun h -> live h x) (ensures fun h0 z h1 -> h0 == h1 /\ v z < 2 /\ v z == F51.as_nat h0 x % 2) let x_mod_2 x = let x0 = x.(0ul) in let z = x0 &. u64 1 in mod_mask_lemma x0 1ul; Lib.IntTypes.Compatibility.uintv_extensionality (u64 1) (mod_mask #U64 1ul); z inline_for_extraction noextract val recover_x_step_1: x2:elemB -> y:elemB -> Stack unit (requires fun h -> live h x2 /\ live h y /\ disjoint x2 y /\ F51.mul_inv_t h y) (ensures fun h0 _ h1 -> modifies (loc x2) h0 h1 /\ F51.fevalh h1 x2 == F51.as_nat h1 x2 /\ F51.mul_inv_t h1 x2 /\ (let y = F51.fevalh h0 y in let x2 = F51.fevalh h1 x2 in let y2 = y `SC.fmul` y in x2 == (y2 `SC.fsub` SC.one) `SC.fmul` (SC.finv ((SE.d `SC.fmul` y2) `SC.fadd` SC.one)))) let recover_x_step_1 x2 y = push_frame(); let tmp = create 20ul (u64 0) in let one = sub tmp 0ul 5ul in let y2 = sub tmp 5ul 5ul in let dyyi = sub tmp 10ul 5ul in let dyy = sub tmp 15ul 5ul in make_one one; fsquare y2 y; // y2 = y * y times_d dyy y2; // dyy = d * y2 fsum dyy dyy one; // dyy = (d * y2) + one reduce_513 dyy; inverse dyyi dyy; // dyyi = modp_inv ((d * y2) + one) fdifference x2 y2 one; // x2 = y2 - one fmul x2 x2 dyyi; // x2 = (y2 - one) * dyyi reduce x2; pop_frame() inline_for_extraction noextract val recover_x_step_2: x:elemB -> sign:uint64 -> x2:elemB -> Stack uint8 (requires fun h -> live h x2 /\ live h x /\ disjoint x x2 /\ F51.mul_inv_t h x /\ F51.fevalh h x2 == F51.as_nat h x2) (ensures fun h0 z h1 -> modifies (loc x) h0 h1 /\ F51.mul_inv_t h1 x /\ (if F51.fevalh h0 x2 = 0 then ( if v sign = 0 then F51.fevalh h1 x = 0 /\ z == u8 1 else h0 == h1 /\ z == u8 0) else h0 == h1 /\ z == u8 2)) let recover_x_step_2 x sign x2 = let open Lib.RawIntTypes in let open FStar.UInt64 in let x2_is_0 = is_0 x2 in if x2_is_0 then begin if u64_to_UInt64 sign =^ 0uL then (make_zero x; u8 1) else u8 0 end else u8 2 inline_for_extraction noextract val recover_x_step_3: tmp:lbuffer uint64 15ul -> Stack unit (requires fun h -> live h tmp /\ F51.mul_inv_t h (gsub tmp 0ul 5ul)) (ensures fun h0 _ h1 -> modifies (loc tmp) h0 h1 /\ F51.mul_inv_t h1 (gsub tmp 5ul 5ul) /\ F51.fevalh h0 (gsub tmp 0ul 5ul) == F51.fevalh h1 (gsub tmp 0ul 5ul) /\ F51.mul_inv_t h1 (gsub tmp 0ul 5ul) /\ (let x2 = F51.fevalh h0 (gsub tmp 0ul 5ul) in let x = x2 `SC.fpow` ((SC.prime + 3) / 8) in let x = if ((x `SC.fmul` x) `SC.fsub` x2) <> 0 then (x `SC.fmul` SE.modp_sqrt_m1) else x in F51.fevalh h1 (gsub tmp 5ul 5ul) == x)) let recover_x_step_3 tmp = let x2 = sub tmp 0ul 5ul in let x3 = sub tmp 5ul 5ul in // x let t0 = sub tmp 10ul 5ul in Hacl.Impl.Ed25519.Pow2_252m2.pow2_252m2 x3 x2; // x3 = x2^((prime + 3) / 8) fsquare t0 x3; // t0 = x3 * x3 fdifference t0 t0 x2; // t0 = t0 - x2 reduce_513 t0; reduce t0; let t0_is_0 = is_0 t0 in if t0_is_0 then () else mul_modp_sqrt_m1 x3 inline_for_extraction noextract val recover_x_step_4: tmp:lbuffer uint64 15ul -> Stack bool (requires fun h -> live h tmp /\ F51.mul_inv_t h (gsub tmp 0ul 5ul) /\ F51.mul_inv_t h (gsub tmp 5ul 5ul)) (ensures fun h0 z h1 -> modifies (loc tmp) h0 h1 /\ F51.fevalh h0 (gsub tmp 0ul 5ul) == F51.fevalh h1 (gsub tmp 0ul 5ul) /\ F51.mul_inv_t h1 (gsub tmp 0ul 5ul) /\ F51.fevalh h0 (gsub tmp 5ul 5ul) == F51.fevalh h1 (gsub tmp 5ul 5ul) /\ F51.mul_inv_t h1 (gsub tmp 5ul 5ul) /\ (let u = F51.fevalh h0 (gsub tmp 5ul 5ul) in let v = F51.fevalh h0 (gsub tmp 0ul 5ul) in let y = (u `SC.fmul` u) `SC.fsub` v in (z <==> y == SC.zero))) let recover_x_step_4 tmp = let x2 = sub tmp 0ul 5ul in let x3 = sub tmp 5ul 5ul in let t0 = sub tmp 10ul 5ul in fsquare t0 x3; // t0 = x3 * x3 fdifference t0 t0 x2; // t0 - x2 reduce_513 t0; reduce t0; is_0 t0 inline_for_extraction noextract val recover_x_step_5: x:elemB -> y:elemB -> sign:uint64{v sign = 0 \/ v sign = 1} -> tmp:lbuffer uint64 15ul -> Stack unit (requires fun h -> live h x /\ live h tmp /\ live h y /\ disjoint x y /\ disjoint tmp x /\ disjoint tmp y /\ F51.mul_inv_t h (gsub tmp 5ul 5ul) /\ (let y = F51.as_nat h y in let sign = (uint_v #U64 sign <> 0) in let x = F51.fevalh h (gsub tmp 5ul 5ul) in let x2 = F51.fevalh h (gsub tmp 0ul 5ul) in ((x `SC.fmul` x) `SC.fsub` x2) == SC.zero /\ SE.recover_x y sign == (if ((x `SC.fmul` x) `SC.fsub` x2) <> SC.zero then None else ( let x = if (x % 2 = 1) <> sign then (SC.prime - x) % SC.prime else x in Some x)))) (ensures fun h0 _ h1 -> modifies (loc x |+| loc tmp) h0 h1 /\ F51.mul_inv_t h1 x /\ F51.fevalh h1 x == Some?.v (SE.recover_x (F51.as_nat h0 y) (uint_v #U64 sign <> 0))) let recover_x_step_5 x y sign tmp = let x3 = sub tmp 5ul 5ul in let t0 = sub tmp 10ul 5ul in reduce x3; let x0 = x_mod_2 x3 in let open Lib.RawIntTypes in let open FStar.UInt64 in if not (u64_to_UInt64 x0 =^ u64_to_UInt64 sign) then ( let h0 = ST.get () in make_zero t0; fdifference x3 t0 x3; // x3 = (-x) % prime reduce_513 x3; reduce x3; (**) assert_norm (SC.prime % SC.prime = SC.zero % SC.prime); (**) FStar.Math.Lemmas.mod_add_both SC.prime SC.zero (- (F51.fevalh h0 x3)) SC.prime); copy x x3 inline_for_extraction noextract val recover_x_: x:elemB -> y:elemB -> sign:uint64{v sign = 0 \/ v sign = 1} -> tmp:lbuffer uint64 15ul -> Stack bool (requires fun h -> live h tmp /\ live h x /\ live h y /\ disjoint x y /\ disjoint tmp x /\ disjoint tmp y /\ F51.mul_inv_t h x /\ F51.felem_fits h y (1, 1, 1, 1, 1) ) (ensures fun h0 z h1 -> modifies (loc x |+| loc tmp) h0 h1 /\ (z ==> F51.mul_inv_t h1 x) /\ (let res = SE.recover_x (F51.as_nat h0 y) (uint_v #U64 sign <> 0) in (Some? res <==> z) /\ (Some? res ==> F51.fevalh h1 x == Some?.v res)) ) let recover_x_ x y sign tmp = let x2 = sub tmp 0ul 5ul in let open Lib.RawIntTypes in let open FStar.UInt8 in let h0 = ST.get() in let b = gte_q y in let res = if b then false else ( (**) FStar.Math.Lemmas.small_mod (F51.as_nat h0 y) SC.prime; recover_x_step_1 x2 y; let z = recover_x_step_2 x sign x2 in if (u8_to_UInt8 z =^ 0uy) then false else if (u8_to_UInt8 z =^ 1uy) then true else ( recover_x_step_3 tmp; let z = recover_x_step_4 tmp in let h1 = ST.get() in if z = false then false else ( recover_x_step_5 x y sign tmp; true) ) ) in res val recover_x: x:lbuffer uint64 5ul -> y:lbuffer uint64 5ul -> sign:uint64{v sign = 0 \/ v sign = 1} -> Stack bool (requires fun h -> live h x /\ live h y /\ disjoint x y /\ F51.mul_inv_t h x /\ F51.felem_fits h y (1, 1, 1, 1, 1) ) (ensures fun h0 z h1 -> modifies (loc x) h0 h1 /\ (z ==> F51.mul_inv_t h1 x) /\ (let res = SE.recover_x (F51.as_nat h0 y) (uint_v #U64 sign <> 0) in (Some? res <==> z) /\ (Some? res ==> F51.fevalh h1 x == Some?.v res)) )
{ "checked_file": "/", "dependencies": [ "Spec.Ed25519.fst.checked", "Spec.Curve25519.fst.checked", "prims.fst.checked", "Lib.RawIntTypes.fsti.checked", "Lib.IntTypes.Compatibility.fst.checked", "Lib.IntTypes.fsti.checked", "Lib.Buffer.fsti.checked", "Hacl.Spec.Curve25519.Field51.Definition.fst.checked", "Hacl.Impl.Ed25519.Pow2_252m2.fst.checked", "Hacl.Impl.Ed25519.Field51.fst.checked", "Hacl.Bignum25519.fsti.checked", "FStar.UInt8.fsti.checked", "FStar.UInt64.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.All.fst.checked" ], "interface_file": false, "source_file": "Hacl.Impl.Ed25519.RecoverX.fst" }
[ { "abbrev": true, "full_module": "Spec.Ed25519", "short_module": "SE" }, { "abbrev": true, "full_module": "Spec.Curve25519", "short_module": "SC" }, { "abbrev": true, "full_module": "Hacl.Spec.Curve25519.Field51.Definition", "short_module": "S51" }, { "abbrev": true, "full_module": "Hacl.Impl.Ed25519.Field51", "short_module": "F51" }, { "abbrev": false, "full_module": "Hacl.Bignum25519", "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": true, "full_module": "FStar.HyperStack.ST", "short_module": "ST" }, { "abbrev": false, "full_module": "Hacl.Impl.Ed25519", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Impl.Ed25519", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: Lib.Buffer.lbuffer Lib.IntTypes.uint64 5ul -> y: Lib.Buffer.lbuffer Lib.IntTypes.uint64 5ul -> sign: Lib.IntTypes.uint64{Lib.IntTypes.v sign = 0 \/ Lib.IntTypes.v sign = 1} -> FStar.HyperStack.ST.Stack Prims.bool
FStar.HyperStack.ST.Stack
[]
[]
[ "Lib.Buffer.lbuffer", "Lib.IntTypes.uint64", "FStar.UInt32.__uint_to_t", "Prims.l_or", "Prims.b2t", "Prims.op_Equality", "Prims.int", "Lib.IntTypes.v", "Lib.IntTypes.U64", "Lib.IntTypes.SEC", "Prims.bool", "Prims.unit", "FStar.HyperStack.ST.pop_frame", "Hacl.Impl.Ed25519.RecoverX.recover_x_", "Lib.Buffer.lbuffer_t", "Lib.Buffer.MUT", "Lib.IntTypes.int_t", "FStar.UInt32.uint_to_t", "FStar.UInt32.t", "Lib.Buffer.create", "Lib.IntTypes.u64", "FStar.HyperStack.ST.push_frame" ]
[]
false
true
false
false
false
let recover_x x y sign =
push_frame (); let tmp = create 15ul (u64 0) in let res = recover_x_ x y sign tmp in pop_frame (); res
false
Ast.fst
Ast.subst_case
val subst_case (s: subst) (c: case) : ML case
val subst_case (s: subst) (c: case) : ML case
let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 57, "end_line": 895, "start_col": 0, "start_line": 868 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.subst -> c: Ast.case -> FStar.All.ML Ast.case
FStar.All.ML
[ "ml" ]
[ "subst_field", "subst_atomic_field", "subst_record", "subst_case", "subst_switch_case" ]
[ "Ast.subst", "Ast.case", "Ast.expr", "Ast.with_meta_t", "Ast.field'", "Ast.Case", "Ast.subst_field", "Ast.field", "Ast.subst_expr", "Ast.DefaultCase" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec subst_case (s: subst) (c: case) : ML case =
match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f)
false
Spec.Agile.Hash.fst
Spec.Agile.Hash.update
val update (a:md_alg): update_t a
val update (a:md_alg): update_t a
let update (a: md_alg) = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.update a | MD5 -> Spec.MD5.update | SHA1 -> Spec.SHA1.update
{ "file_name": "specs/Spec.Agile.Hash.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 22, "end_line": 34, "start_col": 0, "start_line": 27 }
module Spec.Agile.Hash module S = FStar.Seq open Spec.Hash.Definitions open Spec.Hash.MD open FStar.Mul open Lib.IntTypes unfold let coerce (#b #a:Type) (x:a{a == b}) : b = x let init a = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.init a | MD5 -> Spec.MD5.init | SHA1 -> Spec.SHA1.init | Blake2S -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2S Spec.Blake2.blake2s_default_params 0 32 | Blake2B -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2B Spec.Blake2.blake2b_default_params 0 64 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> Lib.Sequence.create 25 (u64 0) // Intentionally restricting this one to MD hashes... we want clients to AVOID
{ "checked_file": "/", "dependencies": [ "Spec.SHA3.fst.checked", "Spec.SHA2.fsti.checked", "Spec.SHA1.fsti.checked", "Spec.MD5.fsti.checked", "Spec.Hash.MD.fst.checked", "Spec.Hash.Definitions.fst.checked", "Spec.Blake2.fst.checked", "prims.fst.checked", "Lib.UpdateMulti.fst.checked", "Lib.Sequence.fsti.checked", "Lib.LoopCombinators.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "Spec.Agile.Hash.fst" }
[ { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.MD", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Spec.Hash.Definitions.md_alg -> Spec.Hash.Definitions.update_t a
Prims.Tot
[ "total" ]
[]
[ "Spec.Hash.Definitions.md_alg", "Spec.SHA2.update", "Spec.MD5.update", "Spec.SHA1.update", "Spec.Hash.Definitions.update_t" ]
[]
false
false
false
false
false
let update (a: md_alg) =
match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.update a | MD5 -> Spec.MD5.update | SHA1 -> Spec.SHA1.update
false
Ast.fst
Ast.print_bitfield
val print_bitfield : bf: FStar.Pervasives.Native.option Ast.field_bitwidth_t -> FStar.All.ALL Prims.string
let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 34, "end_line": 1092, "start_col": 0, "start_line": 1084 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
bf: FStar.Pervasives.Native.option Ast.field_bitwidth_t -> FStar.All.ALL Prims.string
FStar.All.ALL
[]
[]
[ "FStar.Pervasives.Native.option", "Ast.field_bitwidth_t", "Prims.string", "Ast.with_meta_t", "Prims.int", "FStar.Printf.sprintf", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.bitfield_attr'", "Ast.range", "Ast.comments", "Ast.__proj__Mkbitfield_attr'__item__bitfield_to", "Ast.__proj__Mkbitfield_attr'__item__bitfield_from", "Ast.__proj__Mkbitfield_attr'__item__bitfield_width", "Ast.__proj__Mkbitfield_attr'__item__bitfield_identifier", "Ast.print_typ", "Ast.__proj__Mkbitfield_attr'__item__bitfield_type" ]
[]
false
true
false
false
false
let print_bitfield (bf: option field_bitwidth_t) =
match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr { v = a }) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to
false
Hacl.Impl.Ed25519.RecoverX.fst
Hacl.Impl.Ed25519.RecoverX.mul_modp_sqrt_m1
val mul_modp_sqrt_m1: x:elemB -> Stack unit (requires fun h -> live h x /\ F51.mul_inv_t h x) (ensures fun h0 _ h1 -> modifies (loc x) h0 h1 /\ F51.mul_inv_t h1 x /\ F51.fevalh h1 x == F51.fevalh h0 x `SC.fmul` SE.modp_sqrt_m1)
val mul_modp_sqrt_m1: x:elemB -> Stack unit (requires fun h -> live h x /\ F51.mul_inv_t h x) (ensures fun h0 _ h1 -> modifies (loc x) h0 h1 /\ F51.mul_inv_t h1 x /\ F51.fevalh h1 x == F51.fevalh h0 x `SC.fmul` SE.modp_sqrt_m1)
let mul_modp_sqrt_m1 x = [@inline_let] let (x0, x1, x2, x3, x4) = (u64 0x00061b274a0ea0b0, u64 0x0000d5a5fc8f189d, u64 0x0007ef5e9cbd0c60, u64 0x00078595a6804c9e, u64 0x0002b8324804fc1d) in push_frame(); let sqrt_m1 = create 5ul (u64 0) in make_u64_5 sqrt_m1 x0 x1 x2 x3 x4; assert_norm (S51.as_nat5 (x0, x1, x2, x3, x4) == SE.modp_sqrt_m1); fmul x x sqrt_m1; pop_frame()
{ "file_name": "code/ed25519/Hacl.Impl.Ed25519.RecoverX.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 13, "end_line": 86, "start_col": 0, "start_line": 73 }
module Hacl.Impl.Ed25519.RecoverX module ST = FStar.HyperStack.ST open FStar.HyperStack.All open FStar.Mul open Lib.IntTypes open Lib.Buffer open Hacl.Bignum25519 module F51 = Hacl.Impl.Ed25519.Field51 module S51 = Hacl.Spec.Curve25519.Field51.Definition module SC = Spec.Curve25519 module SE = Spec.Ed25519 #reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0" inline_for_extraction noextract let elemB = lbuffer uint64 5ul val is_0: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.as_nat h x == F51.fevalh h x) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.fevalh h0 x == SC.zero))) [@CInline] let is_0 x = let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 =^ 0uL && u64_to_UInt64 x1 =^ 0uL && u64_to_UInt64 x2 =^ 0uL && u64_to_UInt64 x3 =^ 0uL && u64_to_UInt64 x4 =^ 0uL) inline_for_extraction noextract val gte_q: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.felem_fits h x (1, 1, 1, 1, 1)) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.as_nat h0 x >= SC.prime))) let gte_q x = let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 >=^ 0x7ffffffffffeduL && u64_to_UInt64 x1 =^ 0x7ffffffffffffuL && u64_to_UInt64 x2 =^ 0x7ffffffffffffuL && u64_to_UInt64 x3 =^ 0x7ffffffffffffuL && u64_to_UInt64 x4 =^ 0x7ffffffffffffuL) val mul_modp_sqrt_m1: x:elemB -> Stack unit (requires fun h -> live h x /\ F51.mul_inv_t h x) (ensures fun h0 _ h1 -> modifies (loc x) h0 h1 /\ F51.mul_inv_t h1 x /\ F51.fevalh h1 x == F51.fevalh h0 x `SC.fmul` SE.modp_sqrt_m1)
{ "checked_file": "/", "dependencies": [ "Spec.Ed25519.fst.checked", "Spec.Curve25519.fst.checked", "prims.fst.checked", "Lib.RawIntTypes.fsti.checked", "Lib.IntTypes.Compatibility.fst.checked", "Lib.IntTypes.fsti.checked", "Lib.Buffer.fsti.checked", "Hacl.Spec.Curve25519.Field51.Definition.fst.checked", "Hacl.Impl.Ed25519.Pow2_252m2.fst.checked", "Hacl.Impl.Ed25519.Field51.fst.checked", "Hacl.Bignum25519.fsti.checked", "FStar.UInt8.fsti.checked", "FStar.UInt64.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.All.fst.checked" ], "interface_file": false, "source_file": "Hacl.Impl.Ed25519.RecoverX.fst" }
[ { "abbrev": true, "full_module": "Spec.Ed25519", "short_module": "SE" }, { "abbrev": true, "full_module": "Spec.Curve25519", "short_module": "SC" }, { "abbrev": true, "full_module": "Hacl.Spec.Curve25519.Field51.Definition", "short_module": "S51" }, { "abbrev": true, "full_module": "Hacl.Impl.Ed25519.Field51", "short_module": "F51" }, { "abbrev": false, "full_module": "Hacl.Bignum25519", "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": true, "full_module": "FStar.HyperStack.ST", "short_module": "ST" }, { "abbrev": false, "full_module": "Hacl.Impl.Ed25519", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Impl.Ed25519", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: Hacl.Impl.Ed25519.RecoverX.elemB -> FStar.HyperStack.ST.Stack Prims.unit
FStar.HyperStack.ST.Stack
[]
[]
[ "Hacl.Impl.Ed25519.RecoverX.elemB", "Lib.IntTypes.uint64", "FStar.HyperStack.ST.pop_frame", "Prims.unit", "Hacl.Bignum25519.fmul", "FStar.Pervasives.assert_norm", "Prims.eq2", "Prims.nat", "Hacl.Spec.Curve25519.Field51.Definition.as_nat5", "FStar.Pervasives.Native.Mktuple5", "Spec.Ed25519.PointOps.modp_sqrt_m1", "Hacl.Bignum25519.make_u64_5", "Lib.Buffer.lbuffer_t", "Lib.Buffer.MUT", "Lib.IntTypes.int_t", "Lib.IntTypes.U64", "Lib.IntTypes.SEC", "FStar.UInt32.uint_to_t", "FStar.UInt32.t", "Lib.Buffer.create", "FStar.UInt32.__uint_to_t", "Lib.IntTypes.u64", "Lib.Buffer.lbuffer", "FStar.HyperStack.ST.push_frame", "FStar.Pervasives.Native.tuple5" ]
[]
false
true
false
false
false
let mul_modp_sqrt_m1 x =
[@@ inline_let ]let x0, x1, x2, x3, x4 = (u64 0x00061b274a0ea0b0, u64 0x0000d5a5fc8f189d, u64 0x0007ef5e9cbd0c60, u64 0x00078595a6804c9e, u64 0x0002b8324804fc1d) in push_frame (); let sqrt_m1 = create 5ul (u64 0) in make_u64_5 sqrt_m1 x0 x1 x2 x3 x4; assert_norm (S51.as_nat5 (x0, x1, x2, x3, x4) == SE.modp_sqrt_m1); fmul x x sqrt_m1; pop_frame ()
false
Hacl.Impl.Ed25519.RecoverX.fst
Hacl.Impl.Ed25519.RecoverX.gte_q
val gte_q: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.felem_fits h x (1, 1, 1, 1, 1)) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.as_nat h0 x >= SC.prime)))
val gte_q: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.felem_fits h x (1, 1, 1, 1, 1)) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.as_nat h0 x >= SC.prime)))
let gte_q x = let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 >=^ 0x7ffffffffffeduL && u64_to_UInt64 x1 =^ 0x7ffffffffffffuL && u64_to_UInt64 x2 =^ 0x7ffffffffffffuL && u64_to_UInt64 x3 =^ 0x7ffffffffffffuL && u64_to_UInt64 x4 =^ 0x7ffffffffffffuL)
{ "file_name": "code/ed25519/Hacl.Impl.Ed25519.RecoverX.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 41, "end_line": 63, "start_col": 0, "start_line": 51 }
module Hacl.Impl.Ed25519.RecoverX module ST = FStar.HyperStack.ST open FStar.HyperStack.All open FStar.Mul open Lib.IntTypes open Lib.Buffer open Hacl.Bignum25519 module F51 = Hacl.Impl.Ed25519.Field51 module S51 = Hacl.Spec.Curve25519.Field51.Definition module SC = Spec.Curve25519 module SE = Spec.Ed25519 #reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0" inline_for_extraction noextract let elemB = lbuffer uint64 5ul val is_0: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.as_nat h x == F51.fevalh h x) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.fevalh h0 x == SC.zero))) [@CInline] let is_0 x = let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 =^ 0uL && u64_to_UInt64 x1 =^ 0uL && u64_to_UInt64 x2 =^ 0uL && u64_to_UInt64 x3 =^ 0uL && u64_to_UInt64 x4 =^ 0uL) inline_for_extraction noextract val gte_q: x:elemB -> Stack bool (requires fun h -> live h x /\ F51.felem_fits h x (1, 1, 1, 1, 1)) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> (F51.as_nat h0 x >= SC.prime)))
{ "checked_file": "/", "dependencies": [ "Spec.Ed25519.fst.checked", "Spec.Curve25519.fst.checked", "prims.fst.checked", "Lib.RawIntTypes.fsti.checked", "Lib.IntTypes.Compatibility.fst.checked", "Lib.IntTypes.fsti.checked", "Lib.Buffer.fsti.checked", "Hacl.Spec.Curve25519.Field51.Definition.fst.checked", "Hacl.Impl.Ed25519.Pow2_252m2.fst.checked", "Hacl.Impl.Ed25519.Field51.fst.checked", "Hacl.Bignum25519.fsti.checked", "FStar.UInt8.fsti.checked", "FStar.UInt64.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.All.fst.checked" ], "interface_file": false, "source_file": "Hacl.Impl.Ed25519.RecoverX.fst" }
[ { "abbrev": true, "full_module": "Spec.Ed25519", "short_module": "SE" }, { "abbrev": true, "full_module": "Spec.Curve25519", "short_module": "SC" }, { "abbrev": true, "full_module": "Hacl.Spec.Curve25519.Field51.Definition", "short_module": "S51" }, { "abbrev": true, "full_module": "Hacl.Impl.Ed25519.Field51", "short_module": "F51" }, { "abbrev": false, "full_module": "Hacl.Bignum25519", "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": true, "full_module": "FStar.HyperStack.ST", "short_module": "ST" }, { "abbrev": false, "full_module": "Hacl.Impl.Ed25519", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Impl.Ed25519", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: Hacl.Impl.Ed25519.RecoverX.elemB -> FStar.HyperStack.ST.Stack Prims.bool
FStar.HyperStack.ST.Stack
[]
[]
[ "Hacl.Impl.Ed25519.RecoverX.elemB", "Prims.op_AmpAmp", "FStar.UInt64.op_Greater_Equals_Hat", "Lib.RawIntTypes.u64_to_UInt64", "FStar.UInt64.__uint_to_t", "FStar.UInt64.op_Equals_Hat", "Prims.bool", "Lib.IntTypes.int_t", "Lib.IntTypes.U64", "Lib.IntTypes.SEC", "Lib.Buffer.op_Array_Access", "Lib.Buffer.MUT", "Lib.IntTypes.uint64", "FStar.UInt32.__uint_to_t" ]
[]
false
true
false
false
false
let gte_q x =
let open Lib.RawIntTypes in let open FStar.UInt64 in let x0 = x.(0ul) in let x1 = x.(1ul) in let x2 = x.(2ul) in let x3 = x.(3ul) in let x4 = x.(4ul) in (u64_to_UInt64 x0 >=^ 0x7ffffffffffeduL && u64_to_UInt64 x1 =^ 0x7ffffffffffffuL && u64_to_UInt64 x2 =^ 0x7ffffffffffffuL && u64_to_UInt64 x3 =^ 0x7ffffffffffffuL && u64_to_UInt64 x4 =^ 0x7ffffffffffffuL)
false
Spec.Agile.Hash.fst
Spec.Agile.Hash.coerce
val coerce (#b #a: Type) (x: a{a == b}) : b
val coerce (#b #a: Type) (x: a{a == b}) : b
let coerce (#b #a:Type) (x:a{a == b}) : b = x
{ "file_name": "specs/Spec.Agile.Hash.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 52, "end_line": 10, "start_col": 7, "start_line": 10 }
module Spec.Agile.Hash module S = FStar.Seq open Spec.Hash.Definitions open Spec.Hash.MD open FStar.Mul open Lib.IntTypes
{ "checked_file": "/", "dependencies": [ "Spec.SHA3.fst.checked", "Spec.SHA2.fsti.checked", "Spec.SHA1.fsti.checked", "Spec.MD5.fsti.checked", "Spec.Hash.MD.fst.checked", "Spec.Hash.Definitions.fst.checked", "Spec.Blake2.fst.checked", "prims.fst.checked", "Lib.UpdateMulti.fst.checked", "Lib.Sequence.fsti.checked", "Lib.LoopCombinators.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "Spec.Agile.Hash.fst" }
[ { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.MD", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: a{a == b} -> b
Prims.Tot
[ "total" ]
[]
[ "Prims.eq2" ]
[]
false
false
false
false
false
let coerce (#b #a: Type) (x: a{a == b}) : b =
x
false
Ast.fst
Ast.weak_kind_glb
val weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind
val weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind
let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 19, "end_line": 1227, "start_col": 0, "start_line": 1224 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
w1: Ast.weak_kind -> w2: Ast.weak_kind -> Ast.weak_kind
Prims.Tot
[ "total" ]
[]
[ "Ast.weak_kind", "Prims.op_Equality", "Prims.bool", "Ast.WeakKindWeak" ]
[]
false
false
false
true
false
let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind =
if w1 = w2 then w1 else WeakKindWeak
false
FStar.UInt16.fst
FStar.UInt16.v
val v (x:t) : Tot (uint_t n)
val v (x:t) : Tot (uint_t n)
let v x = x.v
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 13, "end_line": 28, "start_col": 0, "start_line": 28 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: FStar.UInt16.t -> FStar.UInt.uint_t FStar.UInt16.n
Prims.Tot
[ "total" ]
[]
[ "FStar.UInt16.t", "FStar.UInt16.__proj__Mk__item__v", "FStar.UInt.uint_t", "FStar.UInt16.n" ]
[]
false
false
false
true
false
let v x =
x.v
false
Ast.fst
Ast.decl'_prune_actions
val decl'_prune_actions (d: decl') : Tot decl'
val decl'_prune_actions (d: decl') : Tot decl'
let decl'_prune_actions (d: decl') : Tot decl' = match d with | ModuleAbbrev _ _ | Define _ _ _ | TypeAbbrev _ _ | Enum _ _ _ | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d | Record names params where fields -> Record names params where (record_prune_actions fields) | CaseType names params cases -> CaseType names params (switch_case_prune_actions cases)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 59, "end_line": 1296, "start_col": 0, "start_line": 1281 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak" let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak let field_tag_equal (f0 f1:field) = match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false (* Pruning actions out of the surface ast (to generate validators checking Z3 test cases) *) let atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field' = { a with field_action = None } let atomic_field_prune_actions (a: atomic_field) : Tot atomic_field = { a with v = atomic_field'_prune_actions a.v } let rec field'_prune_actions (f: field') : Tot field' = match f with | AtomicField a -> AtomicField (atomic_field_prune_actions a) | RecordField r i -> RecordField (record_prune_actions r) i | SwitchCaseField s i -> SwitchCaseField (switch_case_prune_actions s) i and field_prune_actions (f: field) : Tot field = { f with v = field'_prune_actions f.v } and record_prune_actions (r: record) : Tot record = match r with | [] -> [] | f :: r' -> field_prune_actions f :: record_prune_actions r' and case_prune_actions (c: case) : Tot case = match c with | Case e f -> Case e (field_prune_actions f) | DefaultCase f -> DefaultCase (field_prune_actions f) and cases_prune_actions (l: list case) : Tot (list case) = match l with | [] -> [] | c :: l' -> case_prune_actions c :: cases_prune_actions l' and switch_case_prune_actions (s: switch_case) : Tot switch_case = let (e, l) = s in (e, cases_prune_actions l)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
d: Ast.decl' -> Ast.decl'
Prims.Tot
[ "total" ]
[]
[ "Ast.decl'", "Ast.ident", "FStar.Pervasives.Native.option", "Ast.typ", "Ast.constant", "Prims.list", "Ast.enum_case", "Ast.out_typ", "Ast.typedef_names", "Ast.param", "Ast.expr", "Ast.record", "Ast.Record", "Ast.record_prune_actions", "Ast.switch_case", "Ast.CaseType", "Ast.switch_case_prune_actions" ]
[]
false
false
false
true
false
let decl'_prune_actions (d: decl') : Tot decl' =
match d with | ModuleAbbrev _ _ | Define _ _ _ | TypeAbbrev _ _ | Enum _ _ _ | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d | Record names params where fields -> Record names params where (record_prune_actions fields) | CaseType names params cases -> CaseType names params (switch_case_prune_actions cases)
false
Ast.fst
Ast.print_expr
val print_expr (e: expr) : Tot string
val print_expr (e: expr) : Tot string
let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 45, "end_line": 1022, "start_col": 0, "start_line": 974 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
e: Ast.expr -> Prims.string
Prims.Tot
[ "total" ]
[ "print_expr", "print_exprs" ]
[ "Ast.expr", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.expr'", "Ast.constant", "Ast.print_constant", "Ast.ident", "Ast.print_ident", "Ast.with_meta_t", "FStar.Printf.sprintf", "Ast.print_expr", "FStar.Pervasives.Native.option", "Ast.integer_type", "Ast.print_op", "Ast.op", "Ast.__proj__App__item___0", "Ast.Cast", "Prims.string", "Prims.list", "Ast.Ext", "FStar.String.concat", "Ast.print_exprs" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec print_expr (e: expr) : Tot string =
match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1 ; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1 ; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1 ; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1 ; e2] | App (Minus _) [e1 ; e2] | App (Mul _) [e1 ; e2] | App (Division _) [e1 ; e2] | App (Remainder _) [e1 ; e2] | App (BitwiseAnd _) [e1 ; e2] | App (BitwiseOr _) [e1 ; e2] | App (BitwiseXor _) [e1 ; e2] | App (ShiftLeft _) [e1 ; e2] | App (ShiftRight _) [e1 ; e2] | App (LT _) [e1 ; e2] | App (GT _) [e1 ; e2] | App (LE _) [e1 ; e2] | App (GE _) [e1 ; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es))
false
Ast.fst
Ast.print_decl'
val print_decl' (d: decl') : ML string
val print_decl' (d: decl') : ML string
let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD"
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 59, "end_line": 1200, "start_col": 0, "start_line": 1156 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
d: Ast.decl' -> FStar.All.ML Prims.string
FStar.All.ML
[ "ml" ]
[]
[ "Ast.decl'", "Ast.ident", "FStar.Printf.sprintf", "Ast.print_ident", "Prims.string", "Ast.constant", "Ast.print_constant", "Ast.typ", "Ast.print_typ", "Prims.list", "Ast.enum_case", "Ast.ident_to_string", "FStar.String.concat", "FStar.List.map", "FStar.Pervasives.Native.tuple2", "FStar.Pervasives.Native.option", "Ast.either", "Prims.int", "Ast.typedef_names", "Ast.param", "Ast.expr", "Ast.record", "Ast.__proj__Mktypedef_names__item__typedef_ptr_abbrev", "Ast.__proj__Mktypedef_names__item__typedef_abbrev", "Prims.op_Hat", "Ast.print_expr", "Ast.__proj__Mktypedef_names__item__typedef_name", "Ast.print_params", "Ast.with_meta_t", "Ast.field'", "Ast.print_field", "Ast.switch_case", "Ast.print_switch_case", "Ast.out_typ" ]
[]
false
true
false
false
false
let print_decl' (d: decl') : ML string =
match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n%s \n}" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n%s \n} %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n%s \n} %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD"
false
Ast.fst
Ast.print_switch_case
val print_switch_case (s: switch_case) : ML string
val print_switch_case (s: switch_case) : ML string
let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases))
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 65, "end_line": 1154, "start_col": 0, "start_line": 1094 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.switch_case -> FStar.All.ML Prims.string
FStar.All.ML
[ "ml" ]
[ "print_field", "print_record", "print_atomic_field", "print_switch_case" ]
[ "Ast.switch_case", "Ast.expr", "Prims.list", "Ast.case", "FStar.Printf.sprintf", "Ast.print_expr", "Prims.string", "FStar.String.concat", "FStar.List.map", "Ast.with_meta_t", "Ast.field'", "Ast.print_field" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec print_switch_case (s: switch_case) : ML string =
let head, cases = s in let print_case (c: case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n\r\n %s\n}" (print_expr head) (String.concat "\n" (List.map print_case cases))
false
Ast.fst
Ast.print_exprs
val print_exprs (es: list expr) : Tot (list string)
val print_exprs (es: list expr) : Tot (list string)
let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 45, "end_line": 1022, "start_col": 0, "start_line": 974 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
es: Prims.list Ast.expr -> Prims.list Prims.string
Prims.Tot
[ "total" ]
[ "print_expr", "print_exprs" ]
[ "Prims.list", "Ast.expr", "Prims.Nil", "Prims.string", "Prims.Cons", "Ast.print_expr", "Ast.print_exprs" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec print_exprs (es: list expr) : Tot (list string) =
match es with | [] -> [] | hd :: tl -> print_expr hd :: print_exprs tl
false
Ast.fst
Ast.print_field
val print_field (f: field) : ML string
val print_field (f: field) : ML string
let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases))
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 65, "end_line": 1154, "start_col": 0, "start_line": 1094 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.field -> FStar.All.ML Prims.string
FStar.All.ML
[ "ml" ]
[ "print_field", "print_record", "print_atomic_field", "print_switch_case" ]
[ "Ast.field", "Ast.__proj__Mkwith_meta_t__item__comments", "Ast.field'", "Prims.list", "Prims.string", "FStar.Printf.sprintf", "FStar.String.concat", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.with_meta_t", "Ast.atomic_field'", "Ast.print_atomic_field", "Ast.ident", "Ast.__proj__Mkident'__item__name", "Ast.ident'", "Ast.print_record", "FStar.Pervasives.Native.tuple2", "Ast.expr", "Ast.case", "Ast.print_switch_case" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec print_field (f: field) : ML string =
let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v.name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field
false
Spec.Agile.Hash.fst
Spec.Agile.Hash.init
val init (a:hash_alg): init_t a
val init (a:hash_alg): init_t a
let init a = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.init a | MD5 -> Spec.MD5.init | SHA1 -> Spec.SHA1.init | Blake2S -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2S Spec.Blake2.blake2s_default_params 0 32 | Blake2B -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2B Spec.Blake2.blake2b_default_params 0 64 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> Lib.Sequence.create 25 (u64 0)
{ "file_name": "specs/Spec.Agile.Hash.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 36, "end_line": 23, "start_col": 0, "start_line": 12 }
module Spec.Agile.Hash module S = FStar.Seq open Spec.Hash.Definitions open Spec.Hash.MD open FStar.Mul open Lib.IntTypes unfold let coerce (#b #a:Type) (x:a{a == b}) : b = x
{ "checked_file": "/", "dependencies": [ "Spec.SHA3.fst.checked", "Spec.SHA2.fsti.checked", "Spec.SHA1.fsti.checked", "Spec.MD5.fsti.checked", "Spec.Hash.MD.fst.checked", "Spec.Hash.Definitions.fst.checked", "Spec.Blake2.fst.checked", "prims.fst.checked", "Lib.UpdateMulti.fst.checked", "Lib.Sequence.fsti.checked", "Lib.LoopCombinators.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "Spec.Agile.Hash.fst" }
[ { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.MD", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Spec.Hash.Definitions.hash_alg -> Spec.Hash.Definitions.init_t a
Prims.Tot
[ "total" ]
[]
[ "Spec.Hash.Definitions.hash_alg", "Spec.SHA2.init", "Spec.MD5.init", "Spec.SHA1.init", "Spec.Blake2.blake2_init_hash", "Spec.Blake2.Definitions.Blake2S", "Spec.Blake2.Definitions.blake2s_default_params", "Spec.Blake2.Definitions.Blake2B", "Spec.Blake2.Definitions.blake2b_default_params", "Lib.Sequence.create", "Spec.Hash.Definitions.word", "Lib.IntTypes.u64", "Spec.Hash.Definitions.init_t" ]
[]
false
false
false
false
false
let init a =
match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.init a | MD5 -> Spec.MD5.init | SHA1 -> Spec.SHA1.init | Blake2S -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2S Spec.Blake2.blake2s_default_params 0 32 | Blake2B -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2B Spec.Blake2.blake2b_default_params 0 64 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> Lib.Sequence.create 25 (u64 0)
false
Ast.fst
Ast.print_weak_kind
val print_weak_kind (k: weak_kind) : Tot string
val print_weak_kind (k: weak_kind) : Tot string
let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak"
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 34, "end_line": 1222, "start_col": 0, "start_line": 1218 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.weak_kind -> Prims.string
Prims.Tot
[ "total" ]
[]
[ "Ast.weak_kind", "Prims.string" ]
[]
false
false
false
true
false
let print_weak_kind (k: weak_kind) : Tot string =
match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak"
false
Ast.fst
Ast.print_atomic_field
val print_atomic_field (f: atomic_field) : ML string
val print_atomic_field (f: atomic_field) : ML string
let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases))
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 65, "end_line": 1154, "start_col": 0, "start_line": 1094 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.atomic_field -> FStar.All.ML Prims.string
FStar.All.ML
[ "ml" ]
[ "print_field", "print_record", "print_atomic_field", "print_switch_case" ]
[ "Ast.atomic_field", "Ast.print_opt", "Ast.probe_call", "Ast.__proj__Mkatomic_field'__item__field_probe", "FStar.Printf.sprintf", "Ast.ident", "Ast.__proj__Mkprobe_call__item__probe_fn", "Ast.print_ident", "Ast.print_expr", "Ast.__proj__Mkprobe_call__item__probe_length", "Ast.__proj__Mkprobe_call__item__probe_dest", "Prims.string", "Ast.expr", "Ast.__proj__Mkatomic_field'__item__field_constraint", "Ast.__proj__Mkatomic_field'__item__field_array_opt", "Ast.__proj__Mkatomic_field'__item__field_ident", "Ast.__proj__Mkatomic_field'__item__field_dependence", "Prims.bool", "Ast.print_typ", "Ast.__proj__Mkatomic_field'__item__field_type", "Ast.print_bitfield", "Ast.__proj__Mkatomic_field'__item__field_bitwidth", "Ast.atomic_field'", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.field_array_t", "Ast.array_qualifier" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec print_atomic_field (f: atomic_field) : ML string =
let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> (match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e)) | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest)))
false
FStar.UInt16.fst
FStar.UInt16.uint_to_t
val uint_to_t (x:uint_t n) : Pure t (requires True) (ensures (fun y -> v y = x))
val uint_to_t (x:uint_t n) : Pure t (requires True) (ensures (fun y -> v y = x))
let uint_to_t x = Mk x
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 22, "end_line": 31, "start_col": 0, "start_line": 31 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t let v x = x.v
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: FStar.UInt.uint_t FStar.UInt16.n -> Prims.Pure FStar.UInt16.t
Prims.Pure
[]
[]
[ "FStar.UInt.uint_t", "FStar.UInt16.n", "FStar.UInt16.Mk", "FStar.UInt16.t" ]
[]
false
false
false
false
false
let uint_to_t x =
Mk x
false
Spec.Agile.Hash.fst
Spec.Agile.Hash.finish_sha3
val finish_sha3 (a: keccak_alg) (s: words_state a) (l: output_length a) : Tot (bytes_hash' a l)
val finish_sha3 (a: keccak_alg) (s: words_state a) (l: output_length a) : Tot (bytes_hash' a l)
let finish_sha3 (a: keccak_alg) (s: words_state a) (l: output_length a): Tot (bytes_hash' a l) = let rateInBytes = rate a / 8 in match a with | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 -> let rateInBytes = rate a / 8 in let outputByteLen = hash_length a in assert (not (is_shake a)); Spec.SHA3.squeeze s rateInBytes outputByteLen | Shake128 | Shake256 -> Spec.SHA3.squeeze s rateInBytes l
{ "file_name": "specs/Spec.Agile.Hash.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 39, "end_line": 69, "start_col": 0, "start_line": 60 }
module Spec.Agile.Hash module S = FStar.Seq open Spec.Hash.Definitions open Spec.Hash.MD open FStar.Mul open Lib.IntTypes unfold let coerce (#b #a:Type) (x:a{a == b}) : b = x let init a = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.init a | MD5 -> Spec.MD5.init | SHA1 -> Spec.SHA1.init | Blake2S -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2S Spec.Blake2.blake2s_default_params 0 32 | Blake2B -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2B Spec.Blake2.blake2b_default_params 0 64 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> Lib.Sequence.create 25 (u64 0) // Intentionally restricting this one to MD hashes... we want clients to AVOID // juggling between mk_update_multi update vs. repeati for non-MD hashes. let update (a: md_alg) = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.update a | MD5 -> Spec.MD5.update | SHA1 -> Spec.SHA1.update let update_multi a hash prev blocks = match a with | MD5 | SHA1 | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Lib.UpdateMulti.mk_update_multi (block_length a) (update a) hash blocks | Blake2B | Blake2S -> let nb = S.length blocks / block_length a in let a' = to_blake_alg a in Lib.LoopCombinators.repeati #(words_state a) nb (Spec.Blake2.blake2_update1 a' prev blocks) hash | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> let open Spec.SHA3 in let rateInBytes = rate a / 8 in Lib.Sequence.repeat_blocks_multi #_ #(words_state a) rateInBytes blocks (absorb_inner rateInBytes) hash (** Extracting the hash, which we call "finish" *) (* Unflatten the hash from the sequence of words to bytes up to the correct size *) let finish_md (a:md_alg) (hashw:words_state a): Tot (bytes_hash a) = let hash_final_w = S.slice hashw 0 (hash_word_length a) in bytes_of_words a #(hash_word_length a) hash_final_w let finish_blake (a:blake_alg) (hash:words_state a): Tot (bytes_hash a) = let alg = to_blake_alg a in Spec.Blake2.blake2_finish alg hash (Spec.Blake2.max_output alg)
{ "checked_file": "/", "dependencies": [ "Spec.SHA3.fst.checked", "Spec.SHA2.fsti.checked", "Spec.SHA1.fsti.checked", "Spec.MD5.fsti.checked", "Spec.Hash.MD.fst.checked", "Spec.Hash.Definitions.fst.checked", "Spec.Blake2.fst.checked", "prims.fst.checked", "Lib.UpdateMulti.fst.checked", "Lib.Sequence.fsti.checked", "Lib.LoopCombinators.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "Spec.Agile.Hash.fst" }
[ { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.MD", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Spec.Hash.Definitions.keccak_alg -> s: Spec.Hash.Definitions.words_state a -> l: Spec.Hash.Definitions.output_length a -> Spec.Hash.Definitions.bytes_hash' a l
Prims.Tot
[ "total" ]
[]
[ "Spec.Hash.Definitions.keccak_alg", "Spec.Hash.Definitions.words_state", "Spec.Hash.Definitions.output_length", "Spec.SHA3.squeeze", "Prims.unit", "Prims._assert", "Prims.b2t", "Prims.op_Negation", "Spec.Hash.Definitions.is_shake", "Prims.nat", "Prims.op_LessThanOrEqual", "Prims.op_Subtraction", "Prims.pow2", "Prims.op_GreaterThan", "Spec.Hash.Definitions.hash_length", "Prims.int", "Prims.op_Division", "Spec.Hash.Definitions.rate", "Spec.Hash.Definitions.bytes_hash'" ]
[]
false
false
false
false
false
let finish_sha3 (a: keccak_alg) (s: words_state a) (l: output_length a) : Tot (bytes_hash' a l) =
let rateInBytes = rate a / 8 in match a with | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 -> let rateInBytes = rate a / 8 in let outputByteLen = hash_length a in assert (not (is_shake a)); Spec.SHA3.squeeze s rateInBytes outputByteLen | Shake128 | Shake256 -> Spec.SHA3.squeeze s rateInBytes l
false
Spec.Agile.Hash.fst
Spec.Agile.Hash.finish_md
val finish_md (a: md_alg) (hashw: words_state a) : Tot (bytes_hash a)
val finish_md (a: md_alg) (hashw: words_state a) : Tot (bytes_hash a)
let finish_md (a:md_alg) (hashw:words_state a): Tot (bytes_hash a) = let hash_final_w = S.slice hashw 0 (hash_word_length a) in bytes_of_words a #(hash_word_length a) hash_final_w
{ "file_name": "specs/Spec.Agile.Hash.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 53, "end_line": 54, "start_col": 0, "start_line": 52 }
module Spec.Agile.Hash module S = FStar.Seq open Spec.Hash.Definitions open Spec.Hash.MD open FStar.Mul open Lib.IntTypes unfold let coerce (#b #a:Type) (x:a{a == b}) : b = x let init a = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.init a | MD5 -> Spec.MD5.init | SHA1 -> Spec.SHA1.init | Blake2S -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2S Spec.Blake2.blake2s_default_params 0 32 | Blake2B -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2B Spec.Blake2.blake2b_default_params 0 64 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> Lib.Sequence.create 25 (u64 0) // Intentionally restricting this one to MD hashes... we want clients to AVOID // juggling between mk_update_multi update vs. repeati for non-MD hashes. let update (a: md_alg) = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.update a | MD5 -> Spec.MD5.update | SHA1 -> Spec.SHA1.update let update_multi a hash prev blocks = match a with | MD5 | SHA1 | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Lib.UpdateMulti.mk_update_multi (block_length a) (update a) hash blocks | Blake2B | Blake2S -> let nb = S.length blocks / block_length a in let a' = to_blake_alg a in Lib.LoopCombinators.repeati #(words_state a) nb (Spec.Blake2.blake2_update1 a' prev blocks) hash | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> let open Spec.SHA3 in let rateInBytes = rate a / 8 in Lib.Sequence.repeat_blocks_multi #_ #(words_state a) rateInBytes blocks (absorb_inner rateInBytes) hash (** Extracting the hash, which we call "finish" *)
{ "checked_file": "/", "dependencies": [ "Spec.SHA3.fst.checked", "Spec.SHA2.fsti.checked", "Spec.SHA1.fsti.checked", "Spec.MD5.fsti.checked", "Spec.Hash.MD.fst.checked", "Spec.Hash.Definitions.fst.checked", "Spec.Blake2.fst.checked", "prims.fst.checked", "Lib.UpdateMulti.fst.checked", "Lib.Sequence.fsti.checked", "Lib.LoopCombinators.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "Spec.Agile.Hash.fst" }
[ { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.MD", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Spec.Hash.Definitions.md_alg -> hashw: Spec.Hash.Definitions.words_state a -> Spec.Hash.Definitions.bytes_hash a
Prims.Tot
[ "total" ]
[]
[ "Spec.Hash.Definitions.md_alg", "Spec.Hash.Definitions.words_state", "Spec.Hash.Definitions.bytes_of_words", "Spec.Hash.Definitions.hash_word_length", "FStar.Seq.Base.seq", "Spec.Hash.Definitions.word", "FStar.Seq.Base.slice", "Spec.Hash.Definitions.bytes_hash" ]
[]
false
false
false
false
false
let finish_md (a: md_alg) (hashw: words_state a) : Tot (bytes_hash a) =
let hash_final_w = S.slice hashw 0 (hash_word_length a) in bytes_of_words a #(hash_word_length a) hash_final_w
false
Spec.Agile.Hash.fst
Spec.Agile.Hash.update_multi
val update_multi (a:hash_alg) (hash:words_state a) (prev:extra_state a) (blocks:bytes_blocks a): Pure (words_state a) (requires update_multi_pre a prev blocks) (ensures fun _ -> True)
val update_multi (a:hash_alg) (hash:words_state a) (prev:extra_state a) (blocks:bytes_blocks a): Pure (words_state a) (requires update_multi_pre a prev blocks) (ensures fun _ -> True)
let update_multi a hash prev blocks = match a with | MD5 | SHA1 | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Lib.UpdateMulti.mk_update_multi (block_length a) (update a) hash blocks | Blake2B | Blake2S -> let nb = S.length blocks / block_length a in let a' = to_blake_alg a in Lib.LoopCombinators.repeati #(words_state a) nb (Spec.Blake2.blake2_update1 a' prev blocks) hash | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> let open Spec.SHA3 in let rateInBytes = rate a / 8 in Lib.Sequence.repeat_blocks_multi #_ #(words_state a) rateInBytes blocks (absorb_inner rateInBytes) hash
{ "file_name": "specs/Spec.Agile.Hash.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 109, "end_line": 47, "start_col": 0, "start_line": 36 }
module Spec.Agile.Hash module S = FStar.Seq open Spec.Hash.Definitions open Spec.Hash.MD open FStar.Mul open Lib.IntTypes unfold let coerce (#b #a:Type) (x:a{a == b}) : b = x let init a = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.init a | MD5 -> Spec.MD5.init | SHA1 -> Spec.SHA1.init | Blake2S -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2S Spec.Blake2.blake2s_default_params 0 32 | Blake2B -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2B Spec.Blake2.blake2b_default_params 0 64 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> Lib.Sequence.create 25 (u64 0) // Intentionally restricting this one to MD hashes... we want clients to AVOID // juggling between mk_update_multi update vs. repeati for non-MD hashes. let update (a: md_alg) = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.update a | MD5 -> Spec.MD5.update | SHA1 -> Spec.SHA1.update
{ "checked_file": "/", "dependencies": [ "Spec.SHA3.fst.checked", "Spec.SHA2.fsti.checked", "Spec.SHA1.fsti.checked", "Spec.MD5.fsti.checked", "Spec.Hash.MD.fst.checked", "Spec.Hash.Definitions.fst.checked", "Spec.Blake2.fst.checked", "prims.fst.checked", "Lib.UpdateMulti.fst.checked", "Lib.Sequence.fsti.checked", "Lib.LoopCombinators.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "Spec.Agile.Hash.fst" }
[ { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.MD", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Spec.Hash.Definitions.hash_alg -> hash: Spec.Hash.Definitions.words_state a -> prev: Spec.Hash.Definitions.extra_state a -> blocks: Spec.Hash.Definitions.bytes_blocks a -> Prims.Pure (Spec.Hash.Definitions.words_state a)
Prims.Pure
[]
[]
[ "Spec.Hash.Definitions.hash_alg", "Spec.Hash.Definitions.words_state", "Spec.Hash.Definitions.extra_state", "Spec.Hash.Definitions.bytes_blocks", "Lib.UpdateMulti.mk_update_multi", "Spec.Hash.Definitions.block_length", "Spec.Agile.Hash.update", "Lib.LoopCombinators.repeati", "Spec.Blake2.blake2_update1", "Spec.Blake2.Definitions.alg", "Spec.Hash.Definitions.to_blake_alg", "Prims.int", "Prims.op_Division", "FStar.Seq.Base.length", "Lib.IntTypes.uint8", "Lib.Sequence.repeat_blocks_multi", "Spec.SHA3.absorb_inner", "Spec.Hash.Definitions.rate" ]
[]
false
false
false
false
false
let update_multi a hash prev blocks =
match a with | MD5 | SHA1 | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Lib.UpdateMulti.mk_update_multi (block_length a) (update a) hash blocks | Blake2B | Blake2S -> let nb = S.length blocks / block_length a in let a' = to_blake_alg a in Lib.LoopCombinators.repeati #(words_state a) nb (Spec.Blake2.blake2_update1 a' prev blocks) hash | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> let open Spec.SHA3 in let rateInBytes = rate a / 8 in Lib.Sequence.repeat_blocks_multi #_ #(words_state a) rateInBytes blocks (absorb_inner rateInBytes) hash
false
FStar.UInt16.fst
FStar.UInt16.zero
val zero : x:t{v x = 0}
val zero : x:t{v x = 0}
let zero = uint_to_t 0
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 22, "end_line": 39, "start_col": 0, "start_line": 39 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t let v x = x.v irreducible let uint_to_t x = Mk x let uv_inv _ = () let vu_inv _ = () let v_inj _ _ = ()
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: FStar.UInt16.t{FStar.UInt16.v x = 0}
Prims.Tot
[ "total" ]
[]
[ "FStar.UInt16.uint_to_t" ]
[]
false
false
false
false
false
let zero =
uint_to_t 0
false
FStar.UInt16.fst
FStar.UInt16.add
val add (a:t) (b:t) : Pure t (requires (size (v a + v b) n)) (ensures (fun c -> v a + v b = v c))
val add (a:t) (b:t) : Pure t (requires (size (v a + v b) n)) (ensures (fun c -> v a + v b = v c))
let add a b = Mk (add (v a) (v b))
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 34, "end_line": 43, "start_col": 0, "start_line": 43 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t let v x = x.v irreducible let uint_to_t x = Mk x let uv_inv _ = () let vu_inv _ = () let v_inj _ _ = () let zero = uint_to_t 0 let one = uint_to_t 1
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: FStar.UInt16.t -> b: FStar.UInt16.t -> Prims.Pure FStar.UInt16.t
Prims.Pure
[]
[]
[ "FStar.UInt16.t", "FStar.UInt16.Mk", "FStar.UInt.add", "FStar.UInt16.n", "FStar.UInt16.v" ]
[]
false
false
false
false
false
let add a b =
Mk (add (v a) (v b))
false
Pulse.Lib.Stick.fst
Pulse.Lib.Stick.stick
val stick : (hyp : vprop) -> (concl : vprop) -> vprop
val stick : (hyp : vprop) -> (concl : vprop) -> vprop
let stick (p q : vprop) = T.trade p q
{ "file_name": "share/steel/examples/pulse/lib/Pulse.Lib.Stick.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 13, "end_line": 33, "start_col": 0, "start_line": 32 }
(* Copyright 2023 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Pulse.Lib.Stick open Pulse.Lib.Pervasives module T = Pulse.Lib.Trade (* This lemma needed to typecheck the definitions below. *) let emp_unit_left (p:vprop) : Lemma (emp ** p == p) [SMTPat (emp ** p)] = elim_vprop_equiv (vprop_equiv_unit p) (* This module is just a special case of trades. The tactic instantiates the implicit InvList to [] everywhere. We do not even need to use the Pulse checker for it. *)
{ "checked_file": "/", "dependencies": [ "Pulse.Lib.Trade.fsti.checked", "Pulse.Lib.Pervasives.fst.checked", "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": true, "source_file": "Pulse.Lib.Stick.fst" }
[ { "abbrev": true, "full_module": "Pulse.Lib.Trade", "short_module": "T" }, { "abbrev": false, "full_module": "Pulse.Lib.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Lib.Core", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Lib", "short_module": null }, { "abbrev": false, "full_module": "Pulse.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": 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
hyp: Pulse.Lib.Core.vprop -> concl: Pulse.Lib.Core.vprop -> Pulse.Lib.Core.vprop
Prims.Tot
[ "total" ]
[]
[ "Pulse.Lib.Core.vprop", "Pulse.Lib.Trade.trade", "Pulse.Lib.InvList.invlist_empty" ]
[]
false
false
false
true
false
let stick (p q: vprop) =
T.trade p q
false
FStar.UInt16.fst
FStar.UInt16.one
val one : x:t{v x = 1}
val one : x:t{v x = 1}
let one = uint_to_t 1
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 21, "end_line": 41, "start_col": 0, "start_line": 41 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t let v x = x.v irreducible let uint_to_t x = Mk x let uv_inv _ = () let vu_inv _ = () let v_inj _ _ = () let zero = uint_to_t 0
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: FStar.UInt16.t{FStar.UInt16.v x = 1}
Prims.Tot
[ "total" ]
[]
[ "FStar.UInt16.uint_to_t" ]
[]
false
false
false
false
false
let one =
uint_to_t 1
false
Ast.fst
Ast.field'_prune_actions
val field'_prune_actions (f: field') : Tot field'
val field'_prune_actions (f: field') : Tot field'
let rec field'_prune_actions (f: field') : Tot field' = match f with | AtomicField a -> AtomicField (atomic_field_prune_actions a) | RecordField r i -> RecordField (record_prune_actions r) i | SwitchCaseField s i -> SwitchCaseField (switch_case_prune_actions s) i and field_prune_actions (f: field) : Tot field = { f with v = field'_prune_actions f.v } and record_prune_actions (r: record) : Tot record = match r with | [] -> [] | f :: r' -> field_prune_actions f :: record_prune_actions r' and case_prune_actions (c: case) : Tot case = match c with | Case e f -> Case e (field_prune_actions f) | DefaultCase f -> DefaultCase (field_prune_actions f) and cases_prune_actions (l: list case) : Tot (list case) = match l with | [] -> [] | c :: l' -> case_prune_actions c :: cases_prune_actions l' and switch_case_prune_actions (s: switch_case) : Tot switch_case = let (e, l) = s in (e, cases_prune_actions l)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 28, "end_line": 1279, "start_col": 0, "start_line": 1249 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak" let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak let field_tag_equal (f0 f1:field) = match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false (* Pruning actions out of the surface ast (to generate validators checking Z3 test cases) *) let atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field' = { a with field_action = None } let atomic_field_prune_actions (a: atomic_field) : Tot atomic_field = { a with v = atomic_field'_prune_actions a.v }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.field' -> Ast.field'
Prims.Tot
[ "total" ]
[ "field'_prune_actions", "field_prune_actions", "record_prune_actions", "case_prune_actions", "cases_prune_actions", "switch_case_prune_actions" ]
[ "Ast.field'", "Ast.with_meta_t", "Ast.atomic_field'", "Ast.AtomicField", "Ast.atomic_field_prune_actions", "Prims.list", "Ast.ident", "Ast.RecordField", "Ast.record_prune_actions", "FStar.Pervasives.Native.tuple2", "Ast.expr", "Ast.case", "Ast.SwitchCaseField", "Ast.switch_case_prune_actions" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec field'_prune_actions (f: field') : Tot field' =
match f with | AtomicField a -> AtomicField (atomic_field_prune_actions a) | RecordField r i -> RecordField (record_prune_actions r) i | SwitchCaseField s i -> SwitchCaseField (switch_case_prune_actions s) i
false
Ast.fst
Ast.print_record
val print_record (f: record) : ML string
val print_record (f: record) : ML string
let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases))
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 65, "end_line": 1154, "start_col": 0, "start_line": 1094 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.record -> FStar.All.ML Prims.string
FStar.All.ML
[ "ml" ]
[ "print_field", "print_record", "print_atomic_field", "print_switch_case" ]
[ "Ast.record", "FStar.String.concat", "Prims.string", "Prims.list", "FStar.List.map", "Ast.with_meta_t", "Ast.field'", "Ast.print_field" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec print_record (f: record) : ML string =
List.map print_field f |> String.concat ";\n"
false
FStar.UInt16.fst
FStar.UInt16.add_mod
val add_mod (a:t) (b:t) : Pure t (requires True) (ensures (fun c -> FStar.UInt.add_mod (v a) (v b) = v c))
val add_mod (a:t) (b:t) : Pure t (requires True) (ensures (fun c -> FStar.UInt.add_mod (v a) (v b) = v c))
let add_mod a b = Mk (add_mod (v a) (v b))
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 42, "end_line": 47, "start_col": 0, "start_line": 47 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t let v x = x.v irreducible let uint_to_t x = Mk x let uv_inv _ = () let vu_inv _ = () let v_inj _ _ = () let zero = uint_to_t 0 let one = uint_to_t 1 let add a b = Mk (add (v a) (v b)) let add_underspec a b = Mk (add_underspec (v a) (v b))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: FStar.UInt16.t -> b: FStar.UInt16.t -> Prims.Pure FStar.UInt16.t
Prims.Pure
[]
[]
[ "FStar.UInt16.t", "FStar.UInt16.Mk", "FStar.UInt.add_mod", "FStar.UInt16.n", "FStar.UInt16.v" ]
[]
false
false
false
false
false
let add_mod a b =
Mk (add_mod (v a) (v b))
false
Ast.fst
Ast.field_prune_actions
val field_prune_actions (f: field) : Tot field
val field_prune_actions (f: field) : Tot field
let rec field'_prune_actions (f: field') : Tot field' = match f with | AtomicField a -> AtomicField (atomic_field_prune_actions a) | RecordField r i -> RecordField (record_prune_actions r) i | SwitchCaseField s i -> SwitchCaseField (switch_case_prune_actions s) i and field_prune_actions (f: field) : Tot field = { f with v = field'_prune_actions f.v } and record_prune_actions (r: record) : Tot record = match r with | [] -> [] | f :: r' -> field_prune_actions f :: record_prune_actions r' and case_prune_actions (c: case) : Tot case = match c with | Case e f -> Case e (field_prune_actions f) | DefaultCase f -> DefaultCase (field_prune_actions f) and cases_prune_actions (l: list case) : Tot (list case) = match l with | [] -> [] | c :: l' -> case_prune_actions c :: cases_prune_actions l' and switch_case_prune_actions (s: switch_case) : Tot switch_case = let (e, l) = s in (e, cases_prune_actions l)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 28, "end_line": 1279, "start_col": 0, "start_line": 1249 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak" let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak let field_tag_equal (f0 f1:field) = match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false (* Pruning actions out of the surface ast (to generate validators checking Z3 test cases) *) let atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field' = { a with field_action = None } let atomic_field_prune_actions (a: atomic_field) : Tot atomic_field = { a with v = atomic_field'_prune_actions a.v }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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: Ast.field -> Ast.field
Prims.Tot
[ "total" ]
[ "field'_prune_actions", "field_prune_actions", "record_prune_actions", "case_prune_actions", "cases_prune_actions", "switch_case_prune_actions" ]
[ "Ast.field", "Ast.Mkwith_meta_t", "Ast.field'", "Ast.field'_prune_actions", "Ast.__proj__Mkwith_meta_t__item__v", "Ast.__proj__Mkwith_meta_t__item__range", "Ast.__proj__Mkwith_meta_t__item__comments" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec field_prune_actions (f: field) : Tot field =
{ f with v = field'_prune_actions f.v }
false
Spec.Agile.Hash.fst
Spec.Agile.Hash.finish_blake
val finish_blake (a: blake_alg) (hash: words_state a) : Tot (bytes_hash a)
val finish_blake (a: blake_alg) (hash: words_state a) : Tot (bytes_hash a)
let finish_blake (a:blake_alg) (hash:words_state a): Tot (bytes_hash a) = let alg = to_blake_alg a in Spec.Blake2.blake2_finish alg hash (Spec.Blake2.max_output alg)
{ "file_name": "specs/Spec.Agile.Hash.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 65, "end_line": 58, "start_col": 0, "start_line": 56 }
module Spec.Agile.Hash module S = FStar.Seq open Spec.Hash.Definitions open Spec.Hash.MD open FStar.Mul open Lib.IntTypes unfold let coerce (#b #a:Type) (x:a{a == b}) : b = x let init a = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.init a | MD5 -> Spec.MD5.init | SHA1 -> Spec.SHA1.init | Blake2S -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2S Spec.Blake2.blake2s_default_params 0 32 | Blake2B -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2B Spec.Blake2.blake2b_default_params 0 64 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> Lib.Sequence.create 25 (u64 0) // Intentionally restricting this one to MD hashes... we want clients to AVOID // juggling between mk_update_multi update vs. repeati for non-MD hashes. let update (a: md_alg) = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.update a | MD5 -> Spec.MD5.update | SHA1 -> Spec.SHA1.update let update_multi a hash prev blocks = match a with | MD5 | SHA1 | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Lib.UpdateMulti.mk_update_multi (block_length a) (update a) hash blocks | Blake2B | Blake2S -> let nb = S.length blocks / block_length a in let a' = to_blake_alg a in Lib.LoopCombinators.repeati #(words_state a) nb (Spec.Blake2.blake2_update1 a' prev blocks) hash | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> let open Spec.SHA3 in let rateInBytes = rate a / 8 in Lib.Sequence.repeat_blocks_multi #_ #(words_state a) rateInBytes blocks (absorb_inner rateInBytes) hash (** Extracting the hash, which we call "finish" *) (* Unflatten the hash from the sequence of words to bytes up to the correct size *) let finish_md (a:md_alg) (hashw:words_state a): Tot (bytes_hash a) = let hash_final_w = S.slice hashw 0 (hash_word_length a) in bytes_of_words a #(hash_word_length a) hash_final_w
{ "checked_file": "/", "dependencies": [ "Spec.SHA3.fst.checked", "Spec.SHA2.fsti.checked", "Spec.SHA1.fsti.checked", "Spec.MD5.fsti.checked", "Spec.Hash.MD.fst.checked", "Spec.Hash.Definitions.fst.checked", "Spec.Blake2.fst.checked", "prims.fst.checked", "Lib.UpdateMulti.fst.checked", "Lib.Sequence.fsti.checked", "Lib.LoopCombinators.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "Spec.Agile.Hash.fst" }
[ { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.MD", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Spec.Hash.Definitions.blake_alg -> hash: Spec.Hash.Definitions.words_state a -> Spec.Hash.Definitions.bytes_hash a
Prims.Tot
[ "total" ]
[]
[ "Spec.Hash.Definitions.blake_alg", "Spec.Hash.Definitions.words_state", "Spec.Blake2.blake2_finish", "Spec.Blake2.Definitions.max_output", "Spec.Blake2.Definitions.alg", "Spec.Hash.Definitions.to_blake_alg", "Spec.Hash.Definitions.bytes_hash" ]
[]
false
false
false
false
false
let finish_blake (a: blake_alg) (hash: words_state a) : Tot (bytes_hash a) =
let alg = to_blake_alg a in Spec.Blake2.blake2_finish alg hash (Spec.Blake2.max_output alg)
false
FStar.UInt16.fst
FStar.UInt16.sub_underspec
val sub_underspec (a:t) (b:t) : Pure t (requires True) (ensures (fun c -> size (v a - v b) n ==> v a - v b = v c))
val sub_underspec (a:t) (b:t) : Pure t (requires True) (ensures (fun c -> size (v a - v b) n ==> v a - v b = v c))
let sub_underspec a b = Mk (sub_underspec (v a) (v b))
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 54, "end_line": 51, "start_col": 0, "start_line": 51 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t let v x = x.v irreducible let uint_to_t x = Mk x let uv_inv _ = () let vu_inv _ = () let v_inj _ _ = () let zero = uint_to_t 0 let one = uint_to_t 1 let add a b = Mk (add (v a) (v b)) let add_underspec a b = Mk (add_underspec (v a) (v b)) let add_mod a b = Mk (add_mod (v a) (v b)) let sub a b = Mk (sub (v a) (v b))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: FStar.UInt16.t -> b: FStar.UInt16.t -> Prims.Pure FStar.UInt16.t
Prims.Pure
[]
[]
[ "FStar.UInt16.t", "FStar.UInt16.Mk", "FStar.UInt.sub_underspec", "FStar.UInt16.n", "FStar.UInt16.v" ]
[]
false
false
false
false
false
let sub_underspec a b =
Mk (sub_underspec (v a) (v b))
false
FStar.UInt16.fst
FStar.UInt16.add_underspec
val add_underspec (a:t) (b:t) : Pure t (requires True) (ensures (fun c -> size (v a + v b) n ==> v a + v b = v c))
val add_underspec (a:t) (b:t) : Pure t (requires True) (ensures (fun c -> size (v a + v b) n ==> v a + v b = v c))
let add_underspec a b = Mk (add_underspec (v a) (v b))
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 54, "end_line": 45, "start_col": 0, "start_line": 45 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t let v x = x.v irreducible let uint_to_t x = Mk x let uv_inv _ = () let vu_inv _ = () let v_inj _ _ = () let zero = uint_to_t 0 let one = uint_to_t 1 let add a b = Mk (add (v a) (v b))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: FStar.UInt16.t -> b: FStar.UInt16.t -> Prims.Pure FStar.UInt16.t
Prims.Pure
[]
[]
[ "FStar.UInt16.t", "FStar.UInt16.Mk", "FStar.UInt.add_underspec", "FStar.UInt16.n", "FStar.UInt16.v" ]
[]
false
false
false
false
false
let add_underspec a b =
Mk (add_underspec (v a) (v b))
false
FStar.UInt16.fst
FStar.UInt16.mul
val mul (a:t) (b:t) : Pure t (requires (size (v a * v b) n)) (ensures (fun c -> v a * v b = v c))
val mul (a:t) (b:t) : Pure t (requires (size (v a * v b) n)) (ensures (fun c -> v a * v b = v c))
let mul a b = Mk (mul (v a) (v b))
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 34, "end_line": 55, "start_col": 0, "start_line": 55 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t let v x = x.v irreducible let uint_to_t x = Mk x let uv_inv _ = () let vu_inv _ = () let v_inj _ _ = () let zero = uint_to_t 0 let one = uint_to_t 1 let add a b = Mk (add (v a) (v b)) let add_underspec a b = Mk (add_underspec (v a) (v b)) let add_mod a b = Mk (add_mod (v a) (v b)) let sub a b = Mk (sub (v a) (v b)) let sub_underspec a b = Mk (sub_underspec (v a) (v b)) let sub_mod a b = Mk (sub_mod (v a) (v b))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: FStar.UInt16.t -> b: FStar.UInt16.t -> Prims.Pure FStar.UInt16.t
Prims.Pure
[]
[]
[ "FStar.UInt16.t", "FStar.UInt16.Mk", "FStar.UInt.mul", "FStar.UInt16.n", "FStar.UInt16.v" ]
[]
false
false
false
false
false
let mul a b =
Mk (mul (v a) (v b))
false
Ast.fst
Ast.case_prune_actions
val case_prune_actions (c: case) : Tot case
val case_prune_actions (c: case) : Tot case
let rec field'_prune_actions (f: field') : Tot field' = match f with | AtomicField a -> AtomicField (atomic_field_prune_actions a) | RecordField r i -> RecordField (record_prune_actions r) i | SwitchCaseField s i -> SwitchCaseField (switch_case_prune_actions s) i and field_prune_actions (f: field) : Tot field = { f with v = field'_prune_actions f.v } and record_prune_actions (r: record) : Tot record = match r with | [] -> [] | f :: r' -> field_prune_actions f :: record_prune_actions r' and case_prune_actions (c: case) : Tot case = match c with | Case e f -> Case e (field_prune_actions f) | DefaultCase f -> DefaultCase (field_prune_actions f) and cases_prune_actions (l: list case) : Tot (list case) = match l with | [] -> [] | c :: l' -> case_prune_actions c :: cases_prune_actions l' and switch_case_prune_actions (s: switch_case) : Tot switch_case = let (e, l) = s in (e, cases_prune_actions l)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 28, "end_line": 1279, "start_col": 0, "start_line": 1249 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak" let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak let field_tag_equal (f0 f1:field) = match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false (* Pruning actions out of the surface ast (to generate validators checking Z3 test cases) *) let atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field' = { a with field_action = None } let atomic_field_prune_actions (a: atomic_field) : Tot atomic_field = { a with v = atomic_field'_prune_actions a.v }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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
c: Ast.case -> Ast.case
Prims.Tot
[ "total" ]
[ "field'_prune_actions", "field_prune_actions", "record_prune_actions", "case_prune_actions", "cases_prune_actions", "switch_case_prune_actions" ]
[ "Ast.case", "Ast.expr", "Ast.with_meta_t", "Ast.field'", "Ast.Case", "Ast.field_prune_actions", "Ast.DefaultCase" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec case_prune_actions (c: case) : Tot case =
match c with | Case e f -> Case e (field_prune_actions f) | DefaultCase f -> DefaultCase (field_prune_actions f)
false
FStar.UInt16.fst
FStar.UInt16.sub
val sub (a:t) (b:t) : Pure t (requires (size (v a - v b) n)) (ensures (fun c -> v a - v b = v c))
val sub (a:t) (b:t) : Pure t (requires (size (v a - v b) n)) (ensures (fun c -> v a - v b = v c))
let sub a b = Mk (sub (v a) (v b))
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 34, "end_line": 49, "start_col": 0, "start_line": 49 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t let v x = x.v irreducible let uint_to_t x = Mk x let uv_inv _ = () let vu_inv _ = () let v_inj _ _ = () let zero = uint_to_t 0 let one = uint_to_t 1 let add a b = Mk (add (v a) (v b)) let add_underspec a b = Mk (add_underspec (v a) (v b)) let add_mod a b = Mk (add_mod (v a) (v b))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: FStar.UInt16.t -> b: FStar.UInt16.t -> Prims.Pure FStar.UInt16.t
Prims.Pure
[]
[]
[ "FStar.UInt16.t", "FStar.UInt16.Mk", "FStar.UInt.sub", "FStar.UInt16.n", "FStar.UInt16.v" ]
[]
false
false
false
false
false
let sub a b =
Mk (sub (v a) (v b))
false
FStar.UInt16.fst
FStar.UInt16.sub_mod
val sub_mod (a:t) (b:t) : Pure t (requires True) (ensures (fun c -> FStar.UInt.sub_mod (v a) (v b) = v c))
val sub_mod (a:t) (b:t) : Pure t (requires True) (ensures (fun c -> FStar.UInt.sub_mod (v a) (v b) = v c))
let sub_mod a b = Mk (sub_mod (v a) (v b))
{ "file_name": "ulib/FStar.UInt16.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 42, "end_line": 53, "start_col": 0, "start_line": 53 }
(* Copyright 2008-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 FStar.UInt16 (**** THIS MODULE IS GENERATED AUTOMATICALLY USING [mk_int.sh], DO NOT EDIT DIRECTLY ****) open FStar.UInt open FStar.Mul #set-options "--max_fuel 0 --max_ifuel 0" type t : eqtype = | Mk: v:uint_t n -> t let v x = x.v irreducible let uint_to_t x = Mk x let uv_inv _ = () let vu_inv _ = () let v_inj _ _ = () let zero = uint_to_t 0 let one = uint_to_t 1 let add a b = Mk (add (v a) (v b)) let add_underspec a b = Mk (add_underspec (v a) (v b)) let add_mod a b = Mk (add_mod (v a) (v b)) let sub a b = Mk (sub (v a) (v b)) let sub_underspec a b = Mk (sub_underspec (v a) (v b))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "FStar.UInt16.fst" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.UInt", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: FStar.UInt16.t -> b: FStar.UInt16.t -> Prims.Pure FStar.UInt16.t
Prims.Pure
[]
[]
[ "FStar.UInt16.t", "FStar.UInt16.Mk", "FStar.UInt.sub_mod", "FStar.UInt16.n", "FStar.UInt16.v" ]
[]
false
false
false
false
false
let sub_mod a b =
Mk (sub_mod (v a) (v b))
false
Ast.fst
Ast.record_prune_actions
val record_prune_actions (r: record) : Tot record
val record_prune_actions (r: record) : Tot record
let rec field'_prune_actions (f: field') : Tot field' = match f with | AtomicField a -> AtomicField (atomic_field_prune_actions a) | RecordField r i -> RecordField (record_prune_actions r) i | SwitchCaseField s i -> SwitchCaseField (switch_case_prune_actions s) i and field_prune_actions (f: field) : Tot field = { f with v = field'_prune_actions f.v } and record_prune_actions (r: record) : Tot record = match r with | [] -> [] | f :: r' -> field_prune_actions f :: record_prune_actions r' and case_prune_actions (c: case) : Tot case = match c with | Case e f -> Case e (field_prune_actions f) | DefaultCase f -> DefaultCase (field_prune_actions f) and cases_prune_actions (l: list case) : Tot (list case) = match l with | [] -> [] | c :: l' -> case_prune_actions c :: cases_prune_actions l' and switch_case_prune_actions (s: switch_case) : Tot switch_case = let (e, l) = s in (e, cases_prune_actions l)
{ "file_name": "src/3d/Ast.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 28, "end_line": 1279, "start_col": 0, "start_line": 1249 }
(* 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 Ast (* The source abstract syntax for the 3d frontend to EverParse *) open FStar.All let reserved_prefix = "___" //redefining either because we need to serialize to Json [@@ PpxDerivingYoJson ] type either a b = | Inl of a | Inr of b /// pos: Source locations type pos = { filename: string; line:int; col:int } noeq type comments_buffer_t = { push: string & pos & pos -> ML unit; flush: unit -> ML (list string); flush_until: pos -> ML (list string); } #push-options "--warn_error -272" //top-level effect; ok let comments_buffer : comments_buffer_t = let buffer : ref (list (string & pos & pos)) = FStar.ST.alloc [] in let buffer_comment (c, s, p) = let c = String.substring c 2 (String.length c - 2) in buffer := (c, s, p) :: !buffer in let flush_comments () = let cs = !buffer in buffer := []; (List.rev cs) |> List.map (fun (c, _, _) -> c) in let flush_until pos : ML (list string) = let cs = !buffer in let preceding, following = List.partition (fun (c, _, end_pos) -> Options.debug_print_string (Printf.sprintf "Requesting comments until line %d,\nAt line %d we have comment (*%s*)\n" pos.line end_pos.line c); end_pos.line <= pos.line) cs in buffer := following; preceding |> List.map (fun (c, _, _) -> c) in { push = buffer_comment; flush = flush_comments; flush_until = flush_until } #pop-options let string_of_pos p = Printf.sprintf "%s:(%d,%d)" p.filename p.line p.col /// range: A source extent let range = pos * pos /// comment: A list of line comments, i.e., a list of strings let comments = list string let string_of_range r = let p, q = r in if p.filename = q.filename then Printf.sprintf "%s:(%d,%d--%d,%d)" p.filename p.line p.col q.line q.col else Printf.sprintf "%s -- %s" (string_of_pos p) (string_of_pos q) let dummy_pos = { filename=""; line=0; col=0; } noeq type with_meta_t 'a = { v:'a; range:range; comments: comments } (* Override the json serializers for with_meta_t to avoid polluting the generated JSON with ranges everywhere *) let with_meta_t_of_yojson (#a #b #c:Type) (f:(a -> b)) (x:a) : ML c = failwith "No reading yojson" let with_meta_t_to_yojson (f:('a -> 'b)) (x:with_meta_t 'a) : 'b = f x.v let with_range_and_comments (x:'a) r c : with_meta_t 'a = { v = x; range = r; comments = c } let with_range (x:'a) (r:range) : with_meta_t 'a = with_range_and_comments x r [] [@@ PpxDerivingYoJson ] type ident' = { modul_name : option string; name : string } [@@ PpxDerivingYoJson ] let ident = with_meta_t ident' let ident_to_string i = Printf.sprintf "%s%s" (match i.v.modul_name with | None -> "" | Some m -> m ^ ".") i.v.name let ident_name i = i.v.name exception Error of string let error #a msg (r:range) : ML a = raise (Error (Printf.sprintf "%s: (Error) %s\n" (string_of_pos (fst r)) msg)) let warning msg (r:range) : ML unit = FStar.IO.print_string (Printf.sprintf "%s: (Warning) %s\n" (string_of_pos (fst r)) msg) let check_reserved_identifier (i:ident) = let open FStar.String in let s = i.v.name in if length s >= 3 && sub s 0 3 = reserved_prefix then error "Identifiers cannot begin with \"___\"" i.range [@@ PpxDerivingYoJson ] type integer_type = | UInt8 | UInt16 | UInt32 | UInt64 let parse_int_suffix (i:string) : string * option integer_type = let l = String.length i in if l >= 2 then let suffix = String.sub i (l - 2) 2 in let prefix = String.sub i 0 (l - 2) in match suffix with | "uy" -> prefix, Some UInt8 | "us" -> prefix, Some UInt16 | "ul" -> prefix, Some UInt32 | "uL" -> prefix, Some UInt64 | _ -> i, None else i, None let smallest_integer_type_of r (i:int) : ML integer_type = if FStar.UInt.fits i 8 then UInt8 else if FStar.UInt.fits i 16 then UInt16 else if FStar.UInt.fits i 32 then UInt32 else if FStar.UInt.fits i 64 then UInt64 else error (Printf.sprintf "Integer %d is too large for all supported fixed-width types" i) r let integer_type_lub (t1 t2: integer_type) : Tot integer_type = match t1, t2 with | UInt64, _ | _, UInt64 -> UInt64 | _, UInt32 | UInt32, _ -> UInt32 | _, UInt16 | UInt16, _ -> UInt16 | UInt8, UInt8 -> UInt8 let integer_type_leq (t1 t2: integer_type) : bool = integer_type_lub t1 t2 = t2 let maybe_as_integer_typ (i:ident) : Tot (option integer_type) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some UInt8 | "UINT16" -> Some UInt16 | "UINT32" -> Some UInt32 | "UINT64" -> Some UInt64 | "UINT8BE" -> Some UInt8 | "UINT16BE" -> Some UInt16 | "UINT32BE" -> Some UInt32 | "UINT64BE" -> Some UInt64 | _ -> None let as_integer_typ (i:ident) : ML integer_type = match maybe_as_integer_typ i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Bit order for bitfields [@@ PpxDerivingYoJson ] type bitfield_bit_order = | LSBFirst (* Least-significant bit first (MSVC default) *) | MSBFirst (* Most-significant bit first (necessary for many IETF protocols) *) let maybe_bit_order_of (i:ident) : Pure (option bitfield_bit_order) (requires True) (ensures (fun y -> Some? y == Some? (maybe_as_integer_typ i) )) = if i.v.modul_name <> None then None else match i.v.name with | "UINT8" -> Some LSBFirst | "UINT16" -> Some LSBFirst | "UINT32" -> Some LSBFirst | "UINT64" -> Some LSBFirst | "UINT8BE" -> Some MSBFirst | "UINT16BE" -> Some MSBFirst | "UINT32BE" -> Some MSBFirst | "UINT64BE" -> Some MSBFirst | _ -> None let bit_order_of (i:ident) : ML bitfield_bit_order = match maybe_bit_order_of i with | None -> error ("Unknown integer type: " ^ ident_to_string i) i.range | Some t -> t /// Integer, hex and boolean constants [@@ PpxDerivingYoJson ] type constant = | Unit | Int : integer_type -> int -> constant | XInt: integer_type -> string -> constant //hexadecimal constants | Bool of bool /// Operators supported in refinement expressions [@@ PpxDerivingYoJson ] type op = | Eq | Neq | And | Or | Not | Plus of option integer_type | Minus of option integer_type | Mul of option integer_type | Division of option integer_type | Remainder of option integer_type | BitwiseAnd of option integer_type | BitwiseXor of option integer_type | BitwiseOr of option integer_type | BitwiseNot of option integer_type | ShiftRight of option integer_type | ShiftLeft of option integer_type | LT of option integer_type | GT of option integer_type | LE of option integer_type | GE of option integer_type | IfThenElse | BitFieldOf: sz: int -> order: bitfield_bit_order -> op //BitFieldOf_n(i, from, to); the integer is the size of i in bits | SizeOf | Cast : from:option integer_type -> to:integer_type -> op | Ext of string //OffsetOf ? /// Expressions used in refinements /// Expressions have no binding structure /// Names are represented using concrete identifiers, i.e., strings /// We enforce that all names are unique in a scope, i.e., no shadowing allowed [@@ PpxDerivingYoJson ] noeq type expr' = | Constant of constant | Identifier of ident | Static of expr //the guard of a #if; must be made from compile-time constants only | This | App : op -> list expr -> expr' and expr = with_meta_t expr' /// A non-pointer type in the AST (see typ below) may be /// - A spec type, i.e. a type that has an interpretation in 3d, that 3d understands /// - An output type, may be used as the type of the parse tree constructed as part of actions /// This includes structs and unions, and actions support assignment to fields of output types /// - An extern type, an abstract, uninterpreted type [@@ PpxDerivingYoJson ] type t_kind = | KindSpec | KindOutput | KindExtern /// Syntax for output expressions /// /// Output expressions may appear as type parameters or as lhs of assignment actions [@@ PpxDerivingYoJson ] noeq type out_expr' = | OE_id : ident -> out_expr' | OE_star : out_expr -> out_expr' | OE_addrof : out_expr -> out_expr' | OE_deref : out_expr -> ident -> out_expr' //deref a field | OE_dot : out_expr -> ident -> out_expr' //read a field /// Output expressions maintain metadata /// (base type, type of the expr and its bitwidth, in case the expression is of a bitfield type) /// /// where base type is the type of the base identifier, /// and type of the output expression /// /// The metadata is initially None after parsing, /// and is populated after typechecking (in Binding.fst) /// /// It is used during emitting F* and C code /// For each output expression, we emit an action (external function call) /// whose signature requires all this /// /// TODO: could we also store the source string for pretty printing? and out_expr_meta_t = { out_expr_base_t : typ; out_expr_t : typ; out_expr_bit_width : option int; } and out_expr = { out_expr_node: with_meta_t out_expr'; out_expr_meta: option out_expr_meta_t } /// A type parameter is either an expression or an output expression and typ_param = either expr out_expr /// Types: all types are named and fully instantiated to expressions only /// i.e., no type-parameterized types /// /// The t_kind field maintains the kind /// /// It is set during the desugaring phase, the parser always sets it to KindSpec /// We could move it to the parser itself /// /// Keeping this makes it easy to check whether a type is an output type or an extern type /// Alternatively we would have to carry some environment along and typ' = | Type_app : ident -> t_kind -> list typ_param -> typ' | Pointer : typ -> typ' and typ = with_meta_t typ' let field_typ = t:typ { Type_app? t.v } [@@ PpxDerivingYoJson ] noeq type atomic_action = | Action_return of expr | Action_abort | Action_field_pos_64 | Action_field_pos_32 | Action_field_ptr | Action_field_ptr_after: sz:expr -> write_to:out_expr -> atomic_action | Action_deref of ident | Action_assignment : lhs:out_expr -> rhs:expr -> atomic_action | Action_call : f:ident -> args:list expr -> atomic_action noeq [@@ PpxDerivingYoJson ] type action' = | Atomic_action of atomic_action | Action_seq : hd:atomic_action -> tl:action -> action' | Action_ite : hd:expr -> then_:action -> else_:option action -> action' | Action_let : i:ident -> a:atomic_action -> k:action -> action' | Action_act : action -> action' and action = with_meta_t action' open FStar.List.Tot let sequence_non_failing_actions (a0:action{Action_act? a0.v}) (a1:action {Action_act? a1.v}) : a:action{Action_act? a.v} = let rec seq (a0:action) = let w a = with_range_and_comments a a1.range (a0.comments @ a1.comments) in let Action_act a1 = a1.v in match a0.v with | Atomic_action a -> w (Action_seq a a1) | Action_seq a0 tl -> w (Action_seq a0 (seq tl)) | Action_ite hd th el -> let th = seq th in let el = match el with | None -> Some a1 | Some el -> Some (seq el) in w (Action_ite hd th el) | Action_let i a k -> w (Action_let i a (seq k)) | Action_act a -> seq a in let res = seq a0 in with_range_and_comments (Action_act res) res.range res.comments [@@ PpxDerivingYoJson ] type qualifier = | Immutable | Mutable /// Parameters: Type definitions can be parameterized by values /// Parameters have a name and are always annoted with their type [@@ PpxDerivingYoJson ] type param = typ & ident & qualifier [@@ PpxDerivingYoJson ] noeq type bitfield_attr' = { bitfield_width : int; bitfield_identifier : int; bitfield_type : typ; bitfield_from : int; bitfield_to: int } and bitfield_attr = with_meta_t bitfield_attr' [@@ PpxDerivingYoJson ] let field_bitwidth_t = either (with_meta_t int) bitfield_attr [@@ PpxDerivingYoJson ] type array_qualifier = | ByteArrayByteSize //[ | ArrayByteSize //[:byte-size | ArrayByteSizeAtMost //[:byte-size-single-element-array-at-most | ArrayByteSizeSingleElementArray //[:byte-size-single-element-array [@@ PpxDerivingYoJson ] noeq type field_array_t = | FieldScalar | FieldArrayQualified of (expr & array_qualifier) //array size in bytes, the qualifier indicates whether this is a variable-length suffix or not | FieldString of (option expr) | FieldConsumeAll // [:consume-all] [@@ PpxDerivingYoJson ] noeq type probe_call = { probe_fn:option ident; probe_length:expr; probe_dest:ident } [@@ PpxDerivingYoJson ] noeq type atomic_field' = { field_dependence:bool; //computed; whether or not the rest of the struct depends on this field field_ident:ident; //name of the field field_type:typ; //type of the field field_array_opt: field_array_t; field_constraint:option expr; //refinement constraint field_bitwidth:option field_bitwidth_t; //bits used for the field; elaborate from Inl to Inr field_action:option (action & bool); //bool indicates if the action depends on the field value field_probe:option probe_call; //set in case this field has to be probed then validated } and atomic_field = with_meta_t atomic_field' and field' = | AtomicField of atomic_field | RecordField : record -> ident -> field' | SwitchCaseField : switch_case -> ident -> field' and field = with_meta_t field' and record = list field and case = | Case : expr -> field -> case | DefaultCase : field -> case and switch_case = expr & list case [@@ PpxDerivingYoJson ] type attribute = | Entrypoint | Aligned /// Typedefs are given 2 names by convention and can be tagged as an /// "entrypoint" for the validator /// /// E.g., /// typedef [entrypoint] struct _T { ... } T, *PTR_T; [@@ PpxDerivingYoJson ] noeq type typedef_names = { typedef_name: ident; typedef_abbrev: ident; typedef_ptr_abbrev: ident; typedef_attributes: list attribute } [@@ PpxDerivingYoJson ] let enum_case = ident & option (either int ident) /// Specification of output types /// /// Output types contain atomic fields with optional bitwidths for bitfield types, /// but they may also contain anonymous structs and unions [@@ PpxDerivingYoJson ] noeq type out_field = | Out_field_named: ident -> typ -> bit_width:option int -> out_field | Out_field_anon : list out_field -> is_union:bool -> out_field [@@ PpxDerivingYoJson ] noeq type out_typ = { out_typ_names : typedef_names; out_typ_fields : list out_field; out_typ_is_union : bool; //TODO: unclear if this field is needed } /// A 3d specification a list of declarations /// - Define: macro definitions for constants /// - TypeAbbrev: macro definition of types /// - Enum: enumerated type using existing constants or newly defined constants /// - Record: a struct with refinements /// - CaseType: an untagged union /// /// - OutputType: an output type definition /// no validators are generated for these types, /// they are used only in the parse trees construction in the actions /// - ExternType: An abstract type declaration /// - ExternFn: An abstract function declaration, may be used in the actions [@@ PpxDerivingYoJson ] noeq type decl' = | ModuleAbbrev: ident -> ident -> decl' | Define: ident -> option typ -> constant -> decl' | TypeAbbrev: typ -> ident -> decl' | Enum: typ -> ident -> list enum_case -> decl' | Record: names:typedef_names -> params:list param -> where:option expr -> fields:record -> decl' | CaseType: typedef_names -> list param -> switch_case -> decl' | OutputType : out_typ -> decl' | ExternType : typedef_names -> decl' | ExternFn : ident -> typ -> list param -> decl' | ExternProbe : ident -> decl' [@@ PpxDerivingYoJson ] noeq type decl = { d_decl : with_meta_t decl'; d_exported : bool } let mk_decl (d:decl') r c (is_exported:bool) : decl = { d_decl = with_range_and_comments d r c; d_exported = is_exported } let decl_with_v (d:decl) (v:decl') : decl = { d with d_decl = { d.d_decl with v = v } } [@@ PpxDerivingYoJson ] noeq type type_refinement = { includes:list string; type_map:list (ident * option ident) } [@@ PpxDerivingYoJson ] let prog = list decl & option type_refinement //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// (** Entrypoint and export definitions *) let has_entrypoint (l:list attribute) : Tot bool = Some? (List.Tot.tryFind (function Entrypoint -> true | _ -> false) l) let is_entrypoint_or_export d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> if has_entrypoint (names.typedef_attributes) then true else d.d_exported | _ -> d.d_exported let is_entrypoint d = match d.d_decl.v with | Record names _ _ _ | CaseType names _ _ -> has_entrypoint (names.typedef_attributes) | _ -> false (** Determine if there are output type expressions: which cases in TranslateForInterpreter introduce the Output_type_expr constructor? *) /// Matches translate_action_assignment, translate_action_field_ptr_after let out_expr_is_out_type_expr (lhs: out_expr) : Tot bool = match lhs.out_expr_node.v with | OE_star ({out_expr_node = {v=OE_id i}}) -> false | _ -> true /// Matches translate_atomic_action let atomic_action_has_out_expr (a: atomic_action) : Tot bool = match a with | Action_field_ptr_after _ write_to | Action_assignment write_to _ -> out_expr_is_out_type_expr write_to | _ -> false /// Matches translate_action let rec action_has_out_expr (a: action) : Tot bool = match a.v with | Atomic_action a -> atomic_action_has_out_expr a | Action_seq hd tl -> if atomic_action_has_out_expr hd then true else action_has_out_expr tl | Action_ite _ then_ (Some else_) -> if action_has_out_expr then_ then true else action_has_out_expr else_ | Action_ite _ then_ None -> action_has_out_expr then_ | Action_let _ a k -> if atomic_action_has_out_expr a then true else action_has_out_expr k | Action_act a -> action_has_out_expr a let field_action_has_out_expr (f: option (action & bool)) : Tot bool = match f with | None -> false | Some (a, _) -> action_has_out_expr a /// Matches translate_atomic_field let atomic_field_has_out_expr (f: atomic_field) : Tot bool = let sf = f.v in field_action_has_out_expr sf.field_action /// Matches field_as_grouped_fields let rec field_has_out_expr (f: field) : Tot bool = match f.v with | AtomicField af -> atomic_field_has_out_expr af | RecordField fs _ -> record_has_out_expr fs | SwitchCaseField sw _ -> switch_case_has_out_expr sw and record_has_out_expr (fs: record) : Tot bool = match fs with | [] -> false | f :: fs' -> if field_has_out_expr f then true else record_has_out_expr fs' and switch_case_has_out_expr (sw: switch_case) : Tot bool = let (_, c) = sw in cases_have_out_expr c and cases_have_out_expr (cs: list case) : Tot bool = match cs with | [] -> false | c :: cs -> if case_has_out_expr c then true else cases_have_out_expr cs and case_has_out_expr (c: case) : Tot bool = match c with | Case _ f | DefaultCase f -> field_has_out_expr f /// Matches parse_field let decl_has_out_expr (d: decl) : Tot bool = match d.d_decl.v with | Record _ _ _ ast_fields -> record_has_out_expr ast_fields | CaseType _ _ switch_case -> switch_case_has_out_expr switch_case | _ -> false (** Equality on expressions and types **) /// eq_expr partially decides equality on expressions, by requiring /// syntactic equality let rec eq_expr (e1 e2:expr) : Tot bool (decreases e1) = match e1.v, e2.v with | Constant i, Constant j -> i = j | Identifier i, Identifier j -> i.v = j.v | This, This -> true | App op1 es1, App op2 es2 -> op1 = op2 && eq_exprs es1 es2 | _ -> false and eq_exprs (es1 es2:list expr) : Tot bool = match es1, es2 with | [], [] -> true | hd1::es1, hd2::es2 -> eq_expr hd1 hd2 && eq_exprs es1 es2 | _ -> false let eq_idents (i1 i2:ident) : Tot bool = i1.v.modul_name = i2.v.modul_name && i1.v.name = i2.v.name /// eq_typ: syntactic equalty of types let rec eq_out_expr (o1 o2:out_expr) : bool = match o1.out_expr_node.v, o2.out_expr_node.v with | OE_id i1, OE_id i2 -> eq_idents i1 i2 | OE_star o1, OE_star o2 | OE_addrof o1, OE_addrof o2 -> eq_out_expr o1 o2 | OE_deref o1 i1, OE_deref o2 i2 | OE_dot o1 i1, OE_dot o2 i2 -> eq_idents i1 i2 && eq_out_expr o1 o2 | _ -> false let eq_typ_param (p1 p2:typ_param) : bool = match p1, p2 with | Inl e1, Inl e2 -> eq_expr e1 e2 | Inr o1, Inr o2 -> eq_out_expr o1 o2 | _ -> false let rec eq_typ_params (ps1 ps2:list typ_param) : bool = match ps1, ps2 with | [], [] -> true | p1::ps1, p2::ps2 -> eq_typ_param p1 p2 && eq_typ_params ps1 ps2 | _ -> false let rec eq_typ (t1 t2:typ) : Tot bool = match t1.v, t2.v with | Type_app hd1 k1 ps1, Type_app hd2 k2 ps2 -> eq_idents hd1 hd2 && k1 = k2 && eq_typ_params ps1 ps2 | Pointer t1, Pointer t2 -> eq_typ t1 t2 | _ -> false (** Common AST constants and builders **) let dummy_range = dummy_pos, dummy_pos let with_dummy_range x = with_range x dummy_range let to_ident' x = {modul_name=None;name=x} let mk_prim_t x = with_dummy_range (Type_app (with_dummy_range (to_ident' x)) KindSpec []) let tbool = mk_prim_t "Bool" let tunit = mk_prim_t "unit" let tuint8 = mk_prim_t "UINT8" let tuint8be = mk_prim_t "UINT8BE" let puint8 = mk_prim_t "PUINT8" let tuint16 = mk_prim_t "UINT16" let tuint32 = mk_prim_t "UINT32" let tuint64 = mk_prim_t "UINT64" let tcopybuffer = mk_prim_t "EVERPARSE_COPY_BUFFER_T" let tunknown = mk_prim_t "?" let unit_atomic_field rng = let dummy_identifier = with_range (to_ident' "_empty_") rng in let f = { field_dependence=false; field_ident=dummy_identifier; field_type=tunit; field_array_opt=FieldScalar; field_constraint=None; field_bitwidth=None; field_action=None; field_probe=None } in with_range f rng let map_opt (f:'a -> ML 'b) (o:option 'a) : ML (option 'b) = match o with | None -> None | Some x -> Some (f x) //////////////////////////////////////////////////////////////////////////////// // Substitutions //////////////////////////////////////////////////////////////////////////////// module H = Hashtable let subst = H.t ident' expr let mk_subst (s:list (ident * expr)) : ML subst = let h = H.create 10 in List.iter (fun (i, e) -> H.insert h i.v e) s; h let apply (s:subst) (id:ident) : ML expr = match H.try_find s id.v with | None -> with_range (Identifier id) id.range | Some e -> e let rec subst_expr (s:subst) (e:expr) : ML expr = match e.v with | Constant _ | This -> e | Identifier i -> apply s i | Static e -> { e with v = Static (subst_expr s e) } | App op es -> {e with v = App op (List.map (subst_expr s) es)} let subst_atomic_action (s:subst) (aa:atomic_action) : ML atomic_action = match aa with | Action_return e -> Action_return (subst_expr s e) | Action_assignment lhs rhs -> Action_assignment lhs (subst_expr s rhs) | Action_call f args -> Action_call f (List.map (subst_expr s) args) | _ -> aa //action mutable identifiers are not subject to substitution let rec subst_action (s:subst) (a:action) : ML action = match a.v with | Atomic_action aa -> {a with v = Atomic_action (subst_atomic_action s aa)} | Action_seq hd tl -> {a with v = Action_seq (subst_atomic_action s hd) (subst_action s tl) } | Action_ite hd then_ else_ -> {a with v = Action_ite (subst_expr s hd) (subst_action s then_) (subst_action_opt s else_) } | Action_let i aa k -> {a with v = Action_let i (subst_atomic_action s aa) (subst_action s k) } | Action_act a -> {a with v = Action_act (subst_action s a) } and subst_action_opt (s:subst) (a:option action) : ML (option action) = match a with | None -> None | Some a -> Some (subst_action s a) //No need to substitute in output expressions let subst_out_expr (s:subst) (o:out_expr) : out_expr = o let subst_typ_param (s:subst) (p:typ_param) : ML typ_param = match p with | Inl e -> Inl (subst_expr s e) | Inr oe -> Inr (subst_out_expr s oe) let rec subst_typ (s:subst) (t:typ) : ML typ = match t.v with | Type_app hd k ps -> { t with v = Type_app hd k (List.map (subst_typ_param s) ps) } | Pointer t -> {t with v = Pointer (subst_typ s t) } let subst_field_array (s:subst) (f:field_array_t) : ML field_array_t = match f with | FieldScalar -> f | FieldArrayQualified (e, q) -> FieldArrayQualified (subst_expr s e, q) | FieldString sz -> FieldString (map_opt (subst_expr s) sz) | FieldConsumeAll -> f let rec subst_field (s:subst) (ff:field) : ML field = match ff.v with | AtomicField f -> {ff with v = AtomicField (subst_atomic_field s f)} | RecordField f i -> {ff with v = RecordField (subst_record s f) i} | SwitchCaseField f i -> {ff with v = SwitchCaseField (subst_switch_case s f) i} and subst_atomic_field (s:subst) (f:atomic_field) : ML atomic_field = let sf = f.v in let a = match sf.field_action with | None -> None | Some (a, b) -> Some (subst_action s a, b) in let sf = { sf with field_type = subst_typ s sf.field_type; field_array_opt = subst_field_array s sf.field_array_opt; field_constraint = map_opt (subst_expr s) sf.field_constraint; field_action = a } in { f with v = sf } and subst_record (s:subst) (f:record) : ML record = List.map (subst_field s) f and subst_case (s:subst) (c:case) : ML case = match c with | Case e f -> Case (subst_expr s e) (subst_field s f) | DefaultCase f -> DefaultCase (subst_field s f) and subst_switch_case (s:subst) (sc:switch_case) : ML switch_case = subst_expr s (fst sc), List.map (subst_case s) (snd sc) let subst_params (s:subst) (p:list param) : ML (list param) = List.map (fun (t, i, q) -> subst_typ s t, i, q) p let subst_decl' (s:subst) (d:decl') : ML decl' = match d with | ModuleAbbrev _ _ -> d | Define i None _ -> d | Define i (Some t) c -> Define i (Some (subst_typ s t)) c | TypeAbbrev t i -> TypeAbbrev (subst_typ s t) i | Enum t i is -> Enum (subst_typ s t) i is | Record names params where fields -> Record names (subst_params s params) (map_opt (subst_expr s) where) (List.map (subst_field s) fields) | CaseType names params cases -> CaseType names (subst_params s params) (subst_switch_case s cases) | OutputType _ | ExternType _ | ExternFn _ _ _ | ExternProbe _ -> d let subst_decl (s:subst) (d:decl) : ML decl = decl_with_v d (subst_decl' s d.d_decl.v) (*** Printing the source AST; for debugging only **) let print_constant (c:constant) = let print_tag = function | UInt8 -> "uy" | UInt16 -> "us" | UInt32 -> "ul" | UInt64 -> "uL" in match c with | Unit -> "()" | Int tag i -> Printf.sprintf "%d%s" i (print_tag tag) | XInt tag x -> let tag = print_tag tag in if String.length x >= 2 && String.sub x (String.length x - 2) 2 = tag then x else Printf.sprintf "%s%s" x tag | Bool b -> Printf.sprintf "%b" b let print_ident (i:ident) = ident_to_string i let print_integer_type = function | UInt8 -> "UINT8" | UInt16 -> "UINT16" | UInt32 -> "UINT32" | UInt64 -> "UINT64" let print_bitfield_bit_order = function | LSBFirst -> "LSBFirst" | MSBFirst -> "MSBFirst" let print_op = function | Eq -> "=" | Neq -> "!=" | And -> "&&" | Or -> "||" | Not -> "!" | Plus _ -> "+" | Minus _ -> "-" | Mul _ -> "*" | Division _ -> "/" | Remainder _ -> "%" | BitwiseAnd _ -> "&" | BitwiseOr _ -> "|" | BitwiseXor _ -> "^" | BitwiseNot _ -> "~" | ShiftLeft _ -> "<<" | ShiftRight _ -> ">>" | LT _ -> "<" | GT _ -> ">" | LE _ -> "<=" | GE _ -> ">=" | IfThenElse -> "ifthenelse" | BitFieldOf i o -> Printf.sprintf "bitfield_of(%d, %s)" i (print_bitfield_bit_order o) | SizeOf -> "sizeof" | Cast _ t -> "(" ^ print_integer_type t ^ ")" | Ext s -> s let rec print_expr (e:expr) : Tot string = match e.v with | Constant c -> print_constant c | Identifier i -> print_ident i | This -> "this" | Static e -> Printf.sprintf "static(%s)" (print_expr e) | App Eq [e1; e2] -> Printf.sprintf "(%s = %s)" (print_expr e1) (print_expr e2) | App And [e1; e2] -> Printf.sprintf "(%s && %s)" (print_expr e1) (print_expr e2) | App Or [e1; e2] -> Printf.sprintf "(%s || %s)" (print_expr e1) (print_expr e2) | App Not [e1] -> Printf.sprintf "(! %s)" (print_expr e1) | App (BitwiseNot _) [e1] -> Printf.sprintf "(~ %s)" (print_expr e1) | App (Plus _) [e1; e2] | App (Minus _) [e1; e2] | App (Mul _) [e1; e2] | App (Division _) [e1; e2] | App (Remainder _) [e1; e2] | App (BitwiseAnd _) [e1; e2] | App (BitwiseOr _) [e1; e2] | App (BitwiseXor _) [e1; e2] | App (ShiftLeft _) [e1; e2] | App (ShiftRight _) [e1; e2] | App (LT _) [e1; e2] | App (GT _) [e1; e2] | App (LE _) [e1; e2] | App (GE _) [e1; e2] -> let op = App?._0 e.v in Printf.sprintf "(%s %s %s)" (print_expr e1) (print_op op) (print_expr e2) | App SizeOf [e1] -> Printf.sprintf "(sizeof %s)" (print_expr e1) | App (Cast i j) [e] -> Printf.sprintf "%s %s" (print_op (Cast i j)) (print_expr e) | App (Ext s) es -> Printf.sprintf "%s(%s)" (print_op (Ext s)) (String.concat ", " (print_exprs es)) | App op es -> Printf.sprintf "(?? %s %s)" (print_op op) (String.concat ", " (print_exprs es)) and print_exprs (es:list expr) : Tot (list string) = match es with | [] -> [] | hd::tl -> print_expr hd :: print_exprs tl let rec print_out_expr o : ML string = match o.out_expr_node.v with | OE_id i -> ident_to_string i | OE_star o -> Printf.sprintf "*(%s)" (print_out_expr o) | OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr o) | OE_deref o i -> Printf.sprintf "(%s)->(%s)" (print_out_expr o) (ident_to_string i) | OE_dot o i -> Printf.sprintf "(%s).(%s)" (print_out_expr o) (ident_to_string i) let print_typ_param p : ML string = match p with | Inl e -> print_expr e | Inr o -> print_out_expr o let rec print_typ t : ML string = match t.v with | Type_app i _k ps -> begin match ps with | [] -> ident_to_string i | _ -> Printf.sprintf "%s(%s)" (ident_to_string i) (String.concat ", " (List.map print_typ_param ps)) end | Pointer t -> Printf.sprintf "(pointer %s)" (print_typ t) let typ_as_integer_type (t:typ) : ML integer_type = match t.v with | Type_app i _k [] -> as_integer_typ i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let bit_order_of_typ (t:typ) : ML bitfield_bit_order = match t.v with | Type_app i _k [] -> bit_order_of i | _ -> error ("Expected an integer type; got: " ^ (print_typ t)) t.range let print_qual = function | Mutable -> "mutable" | Immutable -> "" let print_params (ps:list param) = match ps with | [] -> "" | _ -> Printf.sprintf "(%s)" (String.concat ", " (ps |> List.map (fun (t, p, q) -> Printf.sprintf "%s%s %s" (print_qual q) (print_typ t) (print_ident p)))) let print_opt (o:option 'a) (f:'a -> string) : string = match o with | None -> "" | Some x -> f x let print_bitfield (bf:option field_bitwidth_t) = match bf with | None -> "" | Some (Inl x) -> Printf.sprintf ": %d " x.v | Some (Inr {v=a}) -> Printf.sprintf ": (|width=%d, id=%d, type=%s, from=%d, to=%d|) " a.bitfield_width a.bitfield_identifier (print_typ a.bitfield_type) a.bitfield_from a.bitfield_to let rec print_field (f:field) : ML string = let field = match f.v with | AtomicField f -> print_atomic_field f | RecordField f i -> Printf.sprintf "%s %s" (print_record f) i.v.name | SwitchCaseField f i -> Printf.sprintf "%s %s" (print_switch_case f) i.v. name in match f.comments with | [] -> field | comms -> Printf.sprintf "//%s\n%s" (String.concat "; " comms) field and print_record (f:record) : ML string = List.map print_field f |> String.concat ";\n" and print_atomic_field (f:atomic_field) : ML string = let print_array eq : Tot string = match eq with | FieldScalar -> "" | FieldArrayQualified (e, q) -> begin match q with | ByteArrayByteSize -> Printf.sprintf "[%s]" (print_expr e) | ArrayByteSize -> Printf.sprintf "[:byte-size %s]" (print_expr e) | ArrayByteSizeAtMost -> Printf.sprintf "[:byte-size-single-element-array-at-most %s]" (print_expr e) | ArrayByteSizeSingleElementArray -> Printf.sprintf "[:byte-size-single-element-array %s]" (print_expr e) end | FieldString None -> Printf.sprintf "[::zeroterm]" | FieldString (Some sz) -> Printf.sprintf "[:zeroterm-byte-size-at-most %s]" (print_expr sz) | FieldConsumeAll -> Printf.sprintf "[:consume-all]" in let sf = f.v in Printf.sprintf "%s%s %s%s%s%s%s;" (if sf.field_dependence then "dependent " else "") (print_typ sf.field_type) (print_ident sf.field_ident) (print_bitfield sf.field_bitwidth) (print_array sf.field_array_opt) (print_opt sf.field_constraint (fun e -> Printf.sprintf "{%s}" (print_expr e))) (print_opt sf.field_probe (fun p -> Printf.sprintf "probe %s (length=%s, destination=%s)" (print_opt p.probe_fn print_ident) (print_expr p.probe_length) (print_ident p.probe_dest))) and print_switch_case (s:switch_case) : ML string = let head, cases = s in let print_case (c:case) : ML string = match c with | Case e f -> Printf.sprintf "case %s: %s;" (print_expr e) (print_field f) | DefaultCase f -> Printf.sprintf "default: %s;" (print_field f) in Printf.sprintf "switch (%s) {\n %s\n\ }" (print_expr head) (String.concat "\n" (List.map print_case cases)) let print_decl' (d:decl') : ML string = match d with | ModuleAbbrev i m -> Printf.sprintf "module %s = %s" (print_ident i) (print_ident m) | Define i None c -> Printf.sprintf "#define %s %s;" (print_ident i) (print_constant c) | Define i (Some t) c -> Printf.sprintf "#define %s : %s %s;" (print_ident i) (print_typ t) (print_constant c) | TypeAbbrev t i -> Printf.sprintf "typedef %s %s;" (print_typ t) (print_ident i) | Enum t i ls -> let print_enum_case (i, jopt) = match jopt with | None -> print_ident i | Some (Inl j) -> Printf.sprintf "%s = %d" (print_ident i) j | Some (Inr j) -> Printf.sprintf "%s = %s" (print_ident i) (print_ident j) in Printf.sprintf "%s enum %s {\n\ %s \n\ }" (print_typ t) (ident_to_string i) (String.concat ",\n" (List.map print_enum_case ls)) | Record td params wopt fields -> Printf.sprintf "typedef struct %s%s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (match wopt with | None -> "" | Some e -> " where " ^ print_expr e) (String.concat "\n" (List.map print_field fields)) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | CaseType td params switch_case -> Printf.sprintf "casetype %s%s {\n\ %s \n\ } %s, *%s" (ident_to_string td.typedef_name) (print_params params) (print_switch_case switch_case) (ident_to_string td.typedef_abbrev) (ident_to_string td.typedef_ptr_abbrev) | OutputType out_t -> "Printing for output types is TBD" | ExternType _ -> "Printing for extern types is TBD" | ExternFn _ _ _ | ExternProbe _ -> "Printing for extern functions is TBD" let print_decl (d:decl) : ML string = match d.d_decl.comments with | [] -> print_decl' d.d_decl.v | cs -> Printf.sprintf "/* %s */\n%s" (String.concat "\n" cs) (print_decl' d.d_decl.v) let print_decls (ds:list decl) : ML string = List.map print_decl ds |> String.concat "\n" type weak_kind = | WeakKindWeak | WeakKindStrongPrefix | WeakKindConsumesAll let print_weak_kind (k: weak_kind) : Tot string = match k with | WeakKindConsumesAll -> "WeakKindConsumesAll" | WeakKindStrongPrefix -> "WeakKindStrongPrefix" | WeakKindWeak -> "WeakKindWeak" let weak_kind_glb (w1 w2: weak_kind) : Tot weak_kind = if w1 = w2 then w1 else WeakKindWeak let field_tag_equal (f0 f1:field) = match f0.v, f1.v with | AtomicField _, AtomicField _ | RecordField _ _, RecordField _ _ | SwitchCaseField _ _, SwitchCaseField _ _ -> true | _ -> false (* Pruning actions out of the surface ast (to generate validators checking Z3 test cases) *) let atomic_field'_prune_actions (a: atomic_field') : Tot atomic_field' = { a with field_action = None } let atomic_field_prune_actions (a: atomic_field) : Tot atomic_field = { a with v = atomic_field'_prune_actions a.v }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Options.fsti.checked", "Hashtable.fsti.checked", "FStar.UInt.fsti.checked", "FStar.String.fsti.checked", "FStar.ST.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked", "FStar.IO.fst.checked", "FStar.All.fst.checked" ], "interface_file": false, "source_file": "Ast.fst" }
[ { "abbrev": true, "full_module": "Hashtable", "short_module": "H" }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "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.record -> Ast.record
Prims.Tot
[ "total" ]
[ "field'_prune_actions", "field_prune_actions", "record_prune_actions", "case_prune_actions", "cases_prune_actions", "switch_case_prune_actions" ]
[ "Ast.record", "Prims.Nil", "Ast.with_meta_t", "Ast.field'", "Prims.list", "Prims.Cons", "Ast.field_prune_actions", "Ast.record_prune_actions" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec record_prune_actions (r: record) : Tot record =
match r with | [] -> [] | f :: r' -> field_prune_actions f :: record_prune_actions r'
false
Spec.Agile.Hash.fst
Spec.Agile.Hash.finish
val finish (a:hash_alg): Spec.Hash.Definitions.finish_t a
val finish (a:hash_alg): Spec.Hash.Definitions.finish_t a
let finish (a:hash_alg) (hashw:words_state a) (l: output_length a): Tot (bytes_hash' a l) = if is_blake a then finish_blake a hashw else if is_keccak a then finish_sha3 a hashw l else finish_md a hashw
{ "file_name": "specs/Spec.Agile.Hash.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 21, "end_line": 77, "start_col": 0, "start_line": 71 }
module Spec.Agile.Hash module S = FStar.Seq open Spec.Hash.Definitions open Spec.Hash.MD open FStar.Mul open Lib.IntTypes unfold let coerce (#b #a:Type) (x:a{a == b}) : b = x let init a = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.init a | MD5 -> Spec.MD5.init | SHA1 -> Spec.SHA1.init | Blake2S -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2S Spec.Blake2.blake2s_default_params 0 32 | Blake2B -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2B Spec.Blake2.blake2b_default_params 0 64 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> Lib.Sequence.create 25 (u64 0) // Intentionally restricting this one to MD hashes... we want clients to AVOID // juggling between mk_update_multi update vs. repeati for non-MD hashes. let update (a: md_alg) = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.update a | MD5 -> Spec.MD5.update | SHA1 -> Spec.SHA1.update let update_multi a hash prev blocks = match a with | MD5 | SHA1 | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Lib.UpdateMulti.mk_update_multi (block_length a) (update a) hash blocks | Blake2B | Blake2S -> let nb = S.length blocks / block_length a in let a' = to_blake_alg a in Lib.LoopCombinators.repeati #(words_state a) nb (Spec.Blake2.blake2_update1 a' prev blocks) hash | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> let open Spec.SHA3 in let rateInBytes = rate a / 8 in Lib.Sequence.repeat_blocks_multi #_ #(words_state a) rateInBytes blocks (absorb_inner rateInBytes) hash (** Extracting the hash, which we call "finish" *) (* Unflatten the hash from the sequence of words to bytes up to the correct size *) let finish_md (a:md_alg) (hashw:words_state a): Tot (bytes_hash a) = let hash_final_w = S.slice hashw 0 (hash_word_length a) in bytes_of_words a #(hash_word_length a) hash_final_w let finish_blake (a:blake_alg) (hash:words_state a): Tot (bytes_hash a) = let alg = to_blake_alg a in Spec.Blake2.blake2_finish alg hash (Spec.Blake2.max_output alg) let finish_sha3 (a: keccak_alg) (s: words_state a) (l: output_length a): Tot (bytes_hash' a l) = let rateInBytes = rate a / 8 in match a with | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 -> let rateInBytes = rate a / 8 in let outputByteLen = hash_length a in assert (not (is_shake a)); Spec.SHA3.squeeze s rateInBytes outputByteLen | Shake128 | Shake256 -> Spec.SHA3.squeeze s rateInBytes l
{ "checked_file": "/", "dependencies": [ "Spec.SHA3.fst.checked", "Spec.SHA2.fsti.checked", "Spec.SHA1.fsti.checked", "Spec.MD5.fsti.checked", "Spec.Hash.MD.fst.checked", "Spec.Hash.Definitions.fst.checked", "Spec.Blake2.fst.checked", "prims.fst.checked", "Lib.UpdateMulti.fst.checked", "Lib.Sequence.fsti.checked", "Lib.LoopCombinators.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "Spec.Agile.Hash.fst" }
[ { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.MD", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Spec.Hash.Definitions.hash_alg -> Spec.Hash.Definitions.finish_t a
Prims.Tot
[ "total" ]
[]
[ "Spec.Hash.Definitions.hash_alg", "Spec.Hash.Definitions.words_state", "Spec.Hash.Definitions.output_length", "Spec.Hash.Definitions.is_blake", "Spec.Agile.Hash.finish_blake", "Prims.bool", "Spec.Hash.Definitions.is_keccak", "Spec.Agile.Hash.finish_sha3", "Spec.Agile.Hash.finish_md", "Spec.Hash.Definitions.bytes_hash'" ]
[]
false
false
false
false
false
let finish (a: hash_alg) (hashw: words_state a) (l: output_length a) : Tot (bytes_hash' a l) =
if is_blake a then finish_blake a hashw else if is_keccak a then finish_sha3 a hashw l else finish_md a hashw
false
Spec.Agile.Hash.fst
Spec.Agile.Hash.hash'
val hash' (a:hash_alg) (input:bytes{S.length input `less_than_max_input_length` a}) (l: output_length a): Tot (Lib.ByteSequence.lbytes (Spec.Hash.Definitions.hash_length' a l))
val hash' (a:hash_alg) (input:bytes{S.length input `less_than_max_input_length` a}) (l: output_length a): Tot (Lib.ByteSequence.lbytes (Spec.Hash.Definitions.hash_length' a l))
let hash' a input l = if is_blake a then Spec.Blake2.blake2 (to_blake_alg a) input (Spec.Blake2.blake2_default_params (to_blake_alg a)) 0 Seq.empty (Spec.Blake2.max_output (to_blake_alg a)) else if is_md a then (* As defined in the NIST standard; pad, then update, then finish. *) let padding = pad a (S.length input) in finish_md a (update_multi a (init a) () S.(input @| padding)) else match a with | SHA3_224 -> Spec.SHA3.sha3_224 (Seq.length input) input | SHA3_256 -> Spec.SHA3.sha3_256 (Seq.length input) input | SHA3_384 -> Spec.SHA3.sha3_384 (Seq.length input) input | SHA3_512 -> Spec.SHA3.sha3_512 (Seq.length input) input | Shake128 -> Spec.SHA3.shake128 (Seq.length input) input l | Shake256 -> Spec.SHA3.shake256 (Seq.length input) input l
{ "file_name": "specs/Spec.Agile.Hash.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 63, "end_line": 97, "start_col": 0, "start_line": 84 }
module Spec.Agile.Hash module S = FStar.Seq open Spec.Hash.Definitions open Spec.Hash.MD open FStar.Mul open Lib.IntTypes unfold let coerce (#b #a:Type) (x:a{a == b}) : b = x let init a = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.init a | MD5 -> Spec.MD5.init | SHA1 -> Spec.SHA1.init | Blake2S -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2S Spec.Blake2.blake2s_default_params 0 32 | Blake2B -> Spec.Blake2.blake2_init_hash Spec.Blake2.Blake2B Spec.Blake2.blake2b_default_params 0 64 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> Lib.Sequence.create 25 (u64 0) // Intentionally restricting this one to MD hashes... we want clients to AVOID // juggling between mk_update_multi update vs. repeati for non-MD hashes. let update (a: md_alg) = match a with | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Spec.SHA2.update a | MD5 -> Spec.MD5.update | SHA1 -> Spec.SHA1.update let update_multi a hash prev blocks = match a with | MD5 | SHA1 | SHA2_224 | SHA2_256 | SHA2_384 | SHA2_512 -> Lib.UpdateMulti.mk_update_multi (block_length a) (update a) hash blocks | Blake2B | Blake2S -> let nb = S.length blocks / block_length a in let a' = to_blake_alg a in Lib.LoopCombinators.repeati #(words_state a) nb (Spec.Blake2.blake2_update1 a' prev blocks) hash | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | Shake128 | Shake256 -> let open Spec.SHA3 in let rateInBytes = rate a / 8 in Lib.Sequence.repeat_blocks_multi #_ #(words_state a) rateInBytes blocks (absorb_inner rateInBytes) hash (** Extracting the hash, which we call "finish" *) (* Unflatten the hash from the sequence of words to bytes up to the correct size *) let finish_md (a:md_alg) (hashw:words_state a): Tot (bytes_hash a) = let hash_final_w = S.slice hashw 0 (hash_word_length a) in bytes_of_words a #(hash_word_length a) hash_final_w let finish_blake (a:blake_alg) (hash:words_state a): Tot (bytes_hash a) = let alg = to_blake_alg a in Spec.Blake2.blake2_finish alg hash (Spec.Blake2.max_output alg) let finish_sha3 (a: keccak_alg) (s: words_state a) (l: output_length a): Tot (bytes_hash' a l) = let rateInBytes = rate a / 8 in match a with | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 -> let rateInBytes = rate a / 8 in let outputByteLen = hash_length a in assert (not (is_shake a)); Spec.SHA3.squeeze s rateInBytes outputByteLen | Shake128 | Shake256 -> Spec.SHA3.squeeze s rateInBytes l let finish (a:hash_alg) (hashw:words_state a) (l: output_length a): Tot (bytes_hash' a l) = if is_blake a then finish_blake a hashw else if is_keccak a then finish_sha3 a hashw l else finish_md a hashw #push-options "--fuel 0 --ifuel 0" // MD hashes are by definition the application of init / update_multi / pad / finish. // Blake2 does its own thing, and there is a slightly more involved proof that the hash is incremental.
{ "checked_file": "/", "dependencies": [ "Spec.SHA3.fst.checked", "Spec.SHA2.fsti.checked", "Spec.SHA1.fsti.checked", "Spec.MD5.fsti.checked", "Spec.Hash.MD.fst.checked", "Spec.Hash.Definitions.fst.checked", "Spec.Blake2.fst.checked", "prims.fst.checked", "Lib.UpdateMulti.fst.checked", "Lib.Sequence.fsti.checked", "Lib.LoopCombinators.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": true, "source_file": "Spec.Agile.Hash.fst" }
[ { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.MD", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "Spec.Agile", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": 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": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Spec.Hash.Definitions.hash_alg -> input: Spec.Hash.Definitions.bytes {Spec.Hash.Definitions.less_than_max_input_length (FStar.Seq.Base.length input) a} -> l: Spec.Hash.Definitions.output_length a -> Lib.ByteSequence.lbytes (Spec.Hash.Definitions.hash_length' a l)
Prims.Tot
[ "total" ]
[]
[ "Spec.Hash.Definitions.hash_alg", "Spec.Hash.Definitions.bytes", "Prims.b2t", "Spec.Hash.Definitions.less_than_max_input_length", "FStar.Seq.Base.length", "Lib.IntTypes.uint8", "Spec.Hash.Definitions.output_length", "Spec.Hash.Definitions.is_blake", "Spec.Blake2.blake2", "Spec.Hash.Definitions.to_blake_alg", "Spec.Blake2.Definitions.blake2_default_params", "FStar.Seq.Base.empty", "Lib.IntTypes.uint_t", "Lib.IntTypes.U8", "Lib.IntTypes.SEC", "Spec.Blake2.Definitions.max_output", "Prims.bool", "Spec.Hash.Definitions.is_md", "Spec.Agile.Hash.finish_md", "Spec.Agile.Hash.update_multi", "Spec.Agile.Hash.init", "FStar.Seq.Base.op_At_Bar", "Prims.op_Equality", "Prims.int", "Prims.op_Modulus", "Prims.op_Addition", "Lib.IntTypes.int_t", "Spec.Hash.Definitions.block_length", "Spec.Hash.MD.pad", "Spec.SHA3.sha3_224", "Spec.SHA3.sha3_256", "Spec.SHA3.sha3_384", "Spec.SHA3.sha3_512", "Spec.SHA3.shake128", "Spec.SHA3.shake256", "Lib.ByteSequence.lbytes", "Spec.Hash.Definitions.hash_length'" ]
[]
false
false
false
false
false
let hash' a input l =
if is_blake a then Spec.Blake2.blake2 (to_blake_alg a) input (Spec.Blake2.blake2_default_params (to_blake_alg a)) 0 Seq.empty (Spec.Blake2.max_output (to_blake_alg a)) else if is_md a then let padding = pad a (S.length input) in finish_md a (update_multi a (init a) () S.(input @| padding)) else match a with | SHA3_224 -> Spec.SHA3.sha3_224 (Seq.length input) input | SHA3_256 -> Spec.SHA3.sha3_256 (Seq.length input) input | SHA3_384 -> Spec.SHA3.sha3_384 (Seq.length input) input | SHA3_512 -> Spec.SHA3.sha3_512 (Seq.length input) input | Shake128 -> Spec.SHA3.shake128 (Seq.length input) input l | Shake256 -> Spec.SHA3.shake256 (Seq.length input) input l
false