diff options
Diffstat (limited to '')
45 files changed, 1947 insertions, 1885 deletions
diff --git a/compiler/AssociatedTypes.ml b/compiler/AssociatedTypes.ml index 7b928566..cce5a082 100644 --- a/compiler/AssociatedTypes.ml +++ b/compiler/AssociatedTypes.ml @@ -11,6 +11,7 @@ open TypesUtils open Values open LlbcAst open Contexts +open Errors module Subst = Substitute (** The local logger *) @@ -33,7 +34,7 @@ end module TyMap = Collections.MakeMap (TyOrd) -let compute_norm_trait_types_from_preds +let compute_norm_trait_types_from_preds (meta : Meta.meta option) (trait_type_constraints : trait_type_constraint list) : ty TraitTypeRefMap.t = (* Compute a union-find structure by recursively exploring the predicates and clauses *) @@ -50,7 +51,7 @@ let compute_norm_trait_types_from_preds (* Sanity check: the type constraint can't make use of regions - Remark that it would be enough to only visit the field [ty] of the trait type constraint, but for safety we visit all the fields *) - assert (trait_type_constraint_no_regions c); + cassert_opt_meta (trait_type_constraint_no_regions c) meta "TODO: error message"; let { trait_ref; type_name; ty } : trait_type_constraint = c in let trait_ty = TTraitType (trait_ref, type_name) in let trait_ty_ref = get_ref trait_ty in @@ -79,10 +80,10 @@ let compute_norm_trait_types_from_preds in TraitTypeRefMap.of_list rbindings -let ctx_add_norm_trait_types_from_preds (ctx : eval_ctx) +let ctx_add_norm_trait_types_from_preds (meta : Meta.meta) (ctx : eval_ctx) (trait_type_constraints : trait_type_constraint list) : eval_ctx = let norm_trait_types = - compute_norm_trait_types_from_preds trait_type_constraints + compute_norm_trait_types_from_preds (Some meta) trait_type_constraints in { ctx with norm_trait_types } @@ -237,7 +238,8 @@ let rec norm_ctx_normalize_ty (ctx : norm_ctx) (ty : ty) : ty = match trait_ref.trait_id with | TraitRef { trait_id = TraitImpl impl_id; generics = ref_generics; _ } -> - assert (ref_generics = empty_generic_args); + let meta = (TraitImplId.Map.find impl_id ctx.trait_impls).meta in + cassert (ref_generics = empty_generic_args) meta "Higher order types are not supported yet TODO: error message"; log#ldebug (lazy ("norm_ctx_normalize_ty: trait type: trait ref: " @@ -277,7 +279,8 @@ let rec norm_ctx_normalize_ty (ctx : norm_ctx) (ty : ty) : ty = ^ trait_ref_to_string ctx trait_ref ^ "\n- raw trait ref:\n" ^ show_trait_ref trait_ref)); (* We can't project *) - assert (trait_instance_id_is_local_clause trait_ref.trait_id); + let meta = (TraitDeclId.Map.find trait_ref.trait_decl_ref.trait_decl_id ctx.trait_decls).meta in + cassert (trait_instance_id_is_local_clause trait_ref.trait_id) meta "TODO: error message"; TTraitType (trait_ref, type_name) in let tr : trait_type_ref = { trait_ref; type_name } in @@ -342,10 +345,11 @@ and norm_ctx_normalize_trait_instance_id (ctx : norm_ctx) | ParentClause (inst_id, decl_id, clause_id) -> ( let inst_id, impl = norm_ctx_normalize_trait_instance_id ctx inst_id in (* Check if the inst_id refers to a specific implementation, if yes project *) + let meta = (TraitDeclId.Map.find decl_id ctx.trait_decls).meta in match impl with | None -> (* This is actually a local clause *) - assert (trait_instance_id_is_local_clause inst_id); + cassert (trait_instance_id_is_local_clause inst_id) meta "TODO: error message"; (ParentClause (inst_id, decl_id, clause_id), None) | Some impl -> (* We figure out the parent clause by doing the following: @@ -371,12 +375,13 @@ and norm_ctx_normalize_trait_instance_id (ctx : norm_ctx) let clause = norm_ctx_normalize_trait_ref ctx clause in (TraitRef clause, Some clause)) | ItemClause (inst_id, decl_id, item_name, clause_id) -> ( + let meta = (TraitDeclId.Map.find decl_id ctx.trait_decls).meta in let inst_id, impl = norm_ctx_normalize_trait_instance_id ctx inst_id in (* Check if the inst_id refers to a specific implementation, if yes project *) match impl with | None -> (* This is actually a local clause *) - assert (trait_instance_id_is_local_clause inst_id); + cassert (trait_instance_id_is_local_clause inst_id) meta "Trait instance id is not a local clause"; (ItemClause (inst_id, decl_id, item_name, clause_id), None) | Some impl -> (* We figure out the item clause by doing the following: @@ -416,8 +421,9 @@ and norm_ctx_normalize_trait_instance_id (ctx : norm_ctx) | TraitRef trait_ref -> (* The trait instance id necessarily refers to a local sub-clause. We can't project over it and can only peel off the [TraitRef] wrapper *) - assert (trait_instance_id_is_local_clause trait_ref.trait_id); - assert (trait_ref.generics = empty_generic_args); + let meta = (TraitDeclId.Map.find trait_ref.trait_decl_ref.trait_decl_id ctx.trait_decls).meta in + cassert (trait_instance_id_is_local_clause trait_ref.trait_id) meta "Trait instance id is not a local sub-clause"; + cassert (trait_ref.generics = empty_generic_args) meta "TODO: error message"; (trait_ref.trait_id, None) | FnPointer ty -> let ty = norm_ctx_normalize_ty ctx ty in @@ -466,7 +472,8 @@ and norm_ctx_normalize_trait_ref (ctx : norm_ctx) (trait_ref : trait_ref) : (lazy ("norm_ctx_normalize_trait_ref: normalized to: " ^ trait_ref_to_string ctx trait_ref)); - assert (generics = empty_generic_args); + let meta = (TraitDeclId.Map.find trait_ref.trait_decl_ref.trait_decl_id ctx.trait_decls).meta in + cassert (generics = empty_generic_args) meta "TODO: error message"; trait_ref (* Not sure this one is really necessary *) @@ -528,10 +535,10 @@ let type_decl_get_inst_norm_field_rtypes (ctx : eval_ctx) (def : type_decl) List.map (ctx_normalize_ty ctx) types (** Same as [ctx_adt_value_get_instantiated_field_rtypes] but normalizes the types *) -let ctx_adt_value_get_inst_norm_field_rtypes (ctx : eval_ctx) (adt : adt_value) +let ctx_adt_value_get_inst_norm_field_rtypes (meta : Meta.meta) (ctx : eval_ctx) (adt : adt_value) (id : type_id) (generics : generic_args) : ty list = let types = - Subst.ctx_adt_value_get_instantiated_field_types ctx adt id generics + Subst.ctx_adt_value_get_instantiated_field_types meta ctx adt id generics in List.map (ctx_normalize_ty ctx) types diff --git a/compiler/Contexts.ml b/compiler/Contexts.ml index 6cdae078..558aaa4e 100644 --- a/compiler/Contexts.ml +++ b/compiler/Contexts.ml @@ -451,11 +451,11 @@ let erase_regions (ty : ty) : ty = (** Push an uninitialized variable (which thus maps to {!constructor:Values.value.VBottom}) *) let ctx_push_uninitialized_var (meta : Meta.meta) (ctx : eval_ctx) (var : var) : eval_ctx = - ctx_push_var meta ctx var (mk_bottom (erase_regions var.var_ty)) + ctx_push_var meta ctx var (mk_bottom meta (erase_regions var.var_ty)) (** Push a list of uninitialized variables (which thus map to {!constructor:Values.value.VBottom}) *) let ctx_push_uninitialized_vars (meta : Meta.meta) (ctx : eval_ctx) (vars : var list) : eval_ctx = - let vars = List.map (fun v -> (v, mk_bottom (erase_regions v.var_ty))) vars in + let vars = List.map (fun v -> (v, mk_bottom meta (erase_regions v.var_ty))) vars in ctx_push_vars meta ctx vars let env_find_abs (env : env) (pred : abs -> bool) : abs option = diff --git a/compiler/Errors.ml b/compiler/Errors.ml index 65c2cbb0..8fb65bc1 100644 --- a/compiler/Errors.ml +++ b/compiler/Errors.ml @@ -12,16 +12,31 @@ let format_error_message (meta : Meta.meta) msg = exception CFailure of string -let error_list : (Meta.meta * string) list ref = ref [] -let save_error (meta : Meta.meta ) (msg : string) = error_list := (meta, msg)::(!error_list) +let error_list : (Meta.meta option * string) list ref = ref [] +let save_error (meta : Meta.meta option) (msg : string) = error_list := (meta, msg)::(!error_list) let craise (meta : Meta.meta) (msg : string) = if !Config.fail_hard then raise (Failure (format_error_message meta msg)) else - let () = save_error meta msg in + let () = save_error (Some meta) msg in raise (CFailure msg) let cassert (b : bool) (meta : Meta.meta) (msg : string) = if b then - craise meta msg
\ No newline at end of file + craise meta msg + +let craise_opt_meta (meta : Meta.meta option) (msg : string) = + match meta with + | Some m -> craise m msg + | None -> + let () = save_error (None) msg in + raise (CFailure msg) + +let cassert_opt_meta (b : bool) (meta : Meta.meta option) (msg : string) = + match meta with + | Some m -> cassert b m msg + | None -> + if b then + let () = save_error (None) msg in + raise (CFailure msg)
\ No newline at end of file diff --git a/compiler/Extract.ml b/compiler/Extract.ml index aa097a4f..246fc82f 100644 --- a/compiler/Extract.ml +++ b/compiler/Extract.ml @@ -7,6 +7,7 @@ open Pure open PureUtils open TranslateCore open Config +open Errors include ExtractTypes (** Compute the names for all the pure functions generated from a rust function. @@ -59,7 +60,7 @@ let extract_fun_decl_register_names (ctx : extraction_ctx) (* Add the decreases proof for Lean only *) match !Config.backend with | Coq | FStar -> ctx - | HOL4 -> raise (Failure "Unexpected") + | HOL4 -> craise def.meta "Unexpected" | Lean -> ctx_add_decreases_proof def ctx else ctx in @@ -89,7 +90,7 @@ let extract_global_decl_register_names (ctx : extraction_ctx) TODO: we don't need something very generic anymore (some definitions used to be polymorphic). *) -let extract_adt_g_value +let extract_adt_g_value (meta : Meta.meta) (extract_value : extraction_ctx -> bool -> 'v -> extraction_ctx) (fmt : F.formatter) (ctx : extraction_ctx) (is_single_pat : bool) (inside : bool) (variant_id : VariantId.id option) (field_values : 'v list) @@ -127,8 +128,8 @@ let extract_adt_g_value | TAdt (TTuple, generics) -> (* Tuple *) (* For now, we only support fully applied tuple constructors *) - assert (List.length generics.types = List.length field_values); - assert (generics.const_generics = [] && generics.trait_refs = []); + cassert (List.length generics.types = List.length field_values) meta "Only applied tuple constructors are currently supported"; + cassert (generics.const_generics = [] && generics.trait_refs = []) meta "Only applied tuple constructors are currently supported"; extract_as_tuple () | TAdt (adt_id, _) -> (* "Regular" ADT *) @@ -167,8 +168,8 @@ let extract_adt_g_value *) let cons = match variant_id with - | Some vid -> ctx_get_variant adt_id vid ctx - | None -> ctx_get_struct adt_id ctx + | Some vid -> ctx_get_variant meta adt_id vid ctx + | None -> ctx_get_struct meta adt_id ctx in let use_parentheses = inside && field_values <> [] in if use_parentheses then F.pp_print_string fmt "("; @@ -182,16 +183,17 @@ let extract_adt_g_value in if use_parentheses then F.pp_print_string fmt ")"; ctx - | _ -> raise (Failure "Inconsistent typed value") + | _ -> craise meta "Inconsistent typed value" (* Extract globals in the same way as variables *) -let extract_global (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) +let extract_global (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (id : A.GlobalDeclId.id) (generics : generic_args) : unit = + (* let trait_decl = GlobalDeclId.Map.find id ctx.trait_decl_id in there might be a way to extract the meta ? *) let use_brackets = inside && generics <> empty_generic_args in F.pp_open_hvbox fmt ctx.indent_incr; if use_brackets then F.pp_print_string fmt "("; (* Extract the global name *) - F.pp_print_string fmt (ctx_get_global id ctx); + F.pp_print_string fmt (ctx_get_global meta id ctx); (* Extract the generics *) extract_generic_args ctx fmt TypeDeclId.Set.empty generics; if use_brackets then F.pp_print_string fmt ")"; @@ -231,7 +233,7 @@ let fun_builtin_filter_types (id : FunDeclId.id) (types : 'a list) As a pattern can introduce new variables, we return an extraction context updated with new bindings. *) -let rec extract_typed_pattern (ctx : extraction_ctx) (fmt : F.formatter) +let rec extract_typed_pattern (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (is_let : bool) (inside : bool) ?(with_type = false) (v : typed_pattern) : extraction_ctx = if with_type then F.pp_print_string fmt "("; @@ -239,11 +241,11 @@ let rec extract_typed_pattern (ctx : extraction_ctx) (fmt : F.formatter) let ctx = match v.value with | PatConstant cv -> - extract_literal fmt inside cv; + extract_literal meta fmt inside cv; ctx | PatVar (v, _) -> - let vname = ctx_compute_var_basename ctx v.basename v.ty in - let ctx, vname = ctx_add_var vname v.id ctx in + let vname = ctx_compute_var_basename meta ctx v.basename v.ty in + let ctx, vname = ctx_add_var meta vname v.id ctx in F.pp_print_string fmt vname; ctx | PatDummy -> @@ -251,22 +253,22 @@ let rec extract_typed_pattern (ctx : extraction_ctx) (fmt : F.formatter) ctx | PatAdt av -> let extract_value ctx inside v = - extract_typed_pattern ctx fmt is_let inside v + extract_typed_pattern meta ctx fmt is_let inside v in - extract_adt_g_value extract_value fmt ctx is_let inside av.variant_id + extract_adt_g_value meta extract_value fmt ctx is_let inside av.variant_id av.field_values v.ty in if with_type then ( F.pp_print_space fmt (); F.pp_print_string fmt ":"; F.pp_print_space fmt (); - extract_ty ctx fmt TypeDeclId.Set.empty false v.ty; + extract_ty meta ctx fmt TypeDeclId.Set.empty false v.ty; F.pp_print_string fmt ")"); ctx (** Return true if we need to wrap a succession of let-bindings in a [do ...] block (because some of them are monadic) *) -let lets_require_wrap_in_do (lets : (bool * typed_pattern * texpression) list) : +let lets_require_wrap_in_do (meta : Meta.meta) (lets : (bool * typed_pattern * texpression) list) : bool = match !backend with | Lean -> @@ -275,7 +277,7 @@ let lets_require_wrap_in_do (lets : (bool * typed_pattern * texpression) list) : | HOL4 -> (* HOL4 is similar to HOL4, but we add a sanity check *) let wrap_in_do = List.exists (fun (m, _, _) -> m) lets in - if wrap_in_do then assert (List.for_all (fun (m, _, _) -> m) lets); + if wrap_in_do then cassert (List.for_all (fun (m, _, _) -> m) lets) meta "TODO: error message"; wrap_in_do | FStar | Coq -> false @@ -289,37 +291,37 @@ let lets_require_wrap_in_do (lets : (bool * typed_pattern * texpression) list) : - application argument: [f (exp)] - match/if scrutinee: [if exp then _ else _]/[match exp | _ -> _] *) -let rec extract_texpression (ctx : extraction_ctx) (fmt : F.formatter) +let rec extract_texpression (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (e : texpression) : unit = match e.e with | Var var_id -> - let var_name = ctx_get_var var_id ctx in + let var_name = ctx_get_var meta var_id ctx in F.pp_print_string fmt var_name | CVar var_id -> - let var_name = ctx_get_const_generic_var var_id ctx in + let var_name = ctx_get_const_generic_var meta var_id ctx in F.pp_print_string fmt var_name - | Const cv -> extract_literal fmt inside cv + | Const cv -> extract_literal meta fmt inside cv | App _ -> let app, args = destruct_apps e in - extract_App ctx fmt inside app args + extract_App meta ctx fmt inside app args | Lambda _ -> let xl, e = destruct_lambdas e in - extract_Lambda ctx fmt inside xl e + extract_Lambda (meta : Meta.meta) ctx fmt inside xl e | Qualif _ -> (* We use the app case *) - extract_App ctx fmt inside e [] - | Let (_, _, _, _) -> extract_lets ctx fmt inside e - | Switch (scrut, body) -> extract_Switch ctx fmt inside scrut body - | Meta (_, e) -> extract_texpression ctx fmt inside e - | StructUpdate supd -> extract_StructUpdate ctx fmt inside e.ty supd + extract_App meta ctx fmt inside e [] + | Let (_, _, _, _) -> extract_lets meta ctx fmt inside e + | Switch (scrut, body) -> extract_Switch meta ctx fmt inside scrut body + | Meta (_, e) -> extract_texpression meta ctx fmt inside e + | StructUpdate supd -> extract_StructUpdate meta ctx fmt inside e.ty supd | Loop _ -> (* The loop nodes should have been eliminated in {!PureMicroPasses} *) - raise (Failure "Unreachable") + craise meta "Unreachable" (* Extract an application *or* a top-level qualif (function extraction has * to handle top-level qualifiers, so it seemed more natural to merge the * two cases) *) -and extract_App (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) +and extract_App (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (app : texpression) (args : texpression list) : unit = (* We don't do the same thing if the app is a top-level identifier (function, * ADT constructor...) or a "regular" expression *) @@ -328,18 +330,18 @@ and extract_App (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (* Top-level qualifier *) match qualif.id with | FunOrOp fun_id -> - extract_function_call ctx fmt inside fun_id qualif.generics args + extract_function_call meta ctx fmt inside fun_id qualif.generics args | Global global_id -> assert (args = []); - extract_global ctx fmt inside global_id qualif.generics + extract_global meta ctx fmt inside global_id qualif.generics | AdtCons adt_cons_id -> - extract_adt_cons ctx fmt inside adt_cons_id qualif.generics args + extract_adt_cons meta ctx fmt inside adt_cons_id qualif.generics args | Proj proj -> extract_field_projector ctx fmt inside app proj qualif.generics args | TraitConst (trait_ref, const_name) -> - extract_trait_ref ctx fmt TypeDeclId.Set.empty true trait_ref; + extract_trait_ref meta ctx fmt TypeDeclId.Set.empty true trait_ref; let name = - ctx_get_trait_const trait_ref.trait_decl_ref.trait_decl_id + ctx_get_trait_const meta trait_ref.trait_decl_ref.trait_decl_id const_name ctx in let add_brackets (s : string) = @@ -354,12 +356,12 @@ and extract_App (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) F.pp_open_hovbox fmt ctx.indent_incr; (* Print the app expression *) let app_inside = (inside && args = []) || args <> [] in - extract_texpression ctx fmt app_inside app; + extract_texpression meta ctx fmt app_inside app; (* Print the arguments *) List.iter (fun ve -> F.pp_print_space fmt (); - extract_texpression ctx fmt true ve) + extract_texpression meta ctx fmt true ve) args; (* Close the box for the application *) F.pp_close_box fmt (); @@ -367,7 +369,7 @@ and extract_App (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) if inside then F.pp_print_string fmt ")" (** Subcase of the app case: function call *) -and extract_function_call (ctx : extraction_ctx) (fmt : F.formatter) +and extract_function_call (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (fid : fun_or_op_id) (generics : generic_args) (args : texpression list) : unit = match (fid, args) with @@ -376,11 +378,11 @@ and extract_function_call (ctx : extraction_ctx) (fmt : F.formatter) * Note that the way we generate the translation, we shouldn't get the * case where we have no argument (all functions are fully instantiated, * and no AST transformation introduces partial calls). *) - extract_unop (extract_texpression ctx fmt) fmt inside unop arg + extract_unop meta (extract_texpression meta ctx fmt) fmt inside unop arg | Binop (binop, int_ty), [ arg0; arg1 ] -> (* Number of arguments: similar to unop *) - extract_binop - (extract_texpression ctx fmt) + extract_binop meta + (extract_texpression meta ctx fmt) fmt inside binop int_ty arg0 arg1 | Fun fun_id, _ -> if inside then F.pp_print_string fmt "("; @@ -447,8 +449,8 @@ and extract_function_call (ctx : extraction_ctx) (fmt : F.formatter) if not method_id.is_provided then ( (* Required method *) - assert (lp_id = None); - extract_trait_ref ctx fmt TypeDeclId.Set.empty true trait_ref; + cassert (lp_id = None) trait_decl.meta "TODO: Error message"; + extract_trait_ref trait_decl.meta ctx fmt TypeDeclId.Set.empty true trait_ref; let fun_name = ctx_get_trait_method trait_ref.trait_decl_ref.trait_decl_id method_name ctx @@ -461,7 +463,7 @@ and extract_function_call (ctx : extraction_ctx) (fmt : F.formatter) (* Provided method: we see it as a regular function call, and use the function name *) let fun_id = FromLlbc (FunId (FRegular method_id.id), lp_id) in - let fun_name = ctx_get_function fun_id ctx in + let fun_name = ctx_get_function trait_decl.meta fun_id ctx in F.pp_print_string fmt fun_name; (* Note that we do not need to print the generics for the trait @@ -470,13 +472,13 @@ and extract_function_call (ctx : extraction_ctx) (fmt : F.formatter) Print the trait ref (to instantate the self clause) *) F.pp_print_space fmt (); - extract_trait_ref ctx fmt TypeDeclId.Set.empty true trait_ref + extract_trait_ref trait_decl.meta ctx fmt TypeDeclId.Set.empty true trait_ref | _ -> - let fun_name = ctx_get_function fun_id ctx in + let fun_name = ctx_get_function meta fun_id ctx in F.pp_print_string fmt fun_name); (* Sanity check: HOL4 doesn't support const generics *) - assert (generics.const_generics = [] || !backend <> HOL4); + cassert (generics.const_generics = [] || !backend <> HOL4) meta "TODO: error message"; (* Print the generics. We might need to filter some of the type arguments, if the type @@ -491,12 +493,12 @@ and extract_function_call (ctx : extraction_ctx) (fmt : F.formatter) in (match types with | Ok types -> - extract_generic_args ctx fmt TypeDeclId.Set.empty + extract_generic_args meta ctx fmt TypeDeclId.Set.empty { generics with types } | Error (types, err) -> - extract_generic_args ctx fmt TypeDeclId.Set.empty + extract_generic_args meta ctx fmt TypeDeclId.Set.empty { generics with types }; - if !Config.fail_hard then raise (Failure err) + if !Config.fail_hard then craise meta err else F.pp_print_string fmt "(\"ERROR: ill-formed builtin: invalid number of filtering \ @@ -505,38 +507,38 @@ and extract_function_call (ctx : extraction_ctx) (fmt : F.formatter) List.iter (fun ve -> F.pp_print_space fmt (); - extract_texpression ctx fmt true ve) + extract_texpression meta ctx fmt true ve) args; (* Close the box for the function call *) F.pp_close_box fmt (); (* Return *) if inside then F.pp_print_string fmt ")" | (Unop _ | Binop _), _ -> - raise - (Failure + craise + meta ("Unreachable:\n" ^ "Function: " ^ show_fun_or_op_id fid ^ ",\nNumber of arguments: " ^ string_of_int (List.length args) ^ ",\nArguments: " - ^ String.concat " " (List.map show_texpression args))) + ^ String.concat " " (List.map show_texpression args)) (** Subcase of the app case: ADT constructor *) -and extract_adt_cons (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) +and extract_adt_cons (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (adt_cons : adt_cons_id) (generics : generic_args) (args : texpression list) : unit = let e_ty = TAdt (adt_cons.adt_id, generics) in let is_single_pat = false in let _ = - extract_adt_g_value + extract_adt_g_value meta (fun ctx inside e -> - extract_texpression ctx fmt inside e; + extract_texpression meta ctx fmt inside e; ctx) fmt ctx is_single_pat inside adt_cons.variant_id args e_ty in () (** Subcase of the app case: ADT field projector. *) -and extract_field_projector (ctx : extraction_ctx) (fmt : F.formatter) +and extract_field_projector (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (original_app : texpression) (proj : projection) (_generics : generic_args) (args : texpression list) : unit = (* We isolate the first argument (if there is), in order to pretty print the @@ -562,7 +564,7 @@ and extract_field_projector (ctx : extraction_ctx) (fmt : F.formatter) match num_fields with Some len -> len = 1 | None -> false in if is_tuple_struct && has_one_field then - extract_texpression ctx fmt inside arg + extract_texpression meta ctx fmt inside arg else (* Exactly one argument: pretty-print *) let field_name = @@ -613,12 +615,12 @@ and extract_field_projector (ctx : extraction_ctx) (fmt : F.formatter) if field_id + 1 = Option.get num_fields then twos_prefix else twos_prefix ^ ".1" else "#" ^ string_of_int field_id - else ctx_get_field proj.adt_id proj.field_id ctx + else ctx_get_field meta proj.adt_id proj.field_id ctx in (* Open a box *) F.pp_open_hovbox fmt ctx.indent_incr; (* Extract the expression *) - extract_texpression ctx fmt true arg; + extract_texpression meta ctx fmt true arg; (* We allow to break where the "." appears (except Lean, it's a syntax error) *) if !backend <> Lean then F.pp_print_break fmt 0 0; F.pp_print_string fmt "."; @@ -631,26 +633,26 @@ and extract_field_projector (ctx : extraction_ctx) (fmt : F.formatter) | arg :: args -> (* Call extract_App again, but in such a way that the first argument is * isolated *) - extract_App ctx fmt inside (mk_app original_app arg) args + extract_App meta ctx fmt inside (mk_app meta original_app arg) args | [] -> (* No argument: shouldn't happen *) - raise (Failure "Unreachable") + craise meta "Unreachable" -and extract_Lambda (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) +and extract_Lambda (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (xl : typed_pattern list) (e : texpression) : unit = (* Open a box for the abs expression *) F.pp_open_hovbox fmt ctx.indent_incr; (* Open parentheses *) if inside then F.pp_print_string fmt "("; (* Print the lambda - note that there should always be at least one variable *) - assert (xl <> []); + cassert (xl <> []) meta "TODO: error message"; F.pp_print_string fmt "fun"; let with_type = !backend = Coq in let ctx = List.fold_left (fun ctx x -> F.pp_print_space fmt (); - extract_typed_pattern ctx fmt true true ~with_type x) + extract_typed_pattern meta ctx fmt true true ~with_type x) ctx xl in F.pp_print_space fmt (); @@ -658,13 +660,13 @@ and extract_Lambda (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) else F.pp_print_string fmt "->"; F.pp_print_space fmt (); (* Print the body *) - extract_texpression ctx fmt false e; + extract_texpression meta ctx fmt false e; (* Close parentheses *) if inside then F.pp_print_string fmt ")"; (* Close the box for the abs expression *) F.pp_close_box fmt () -and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) +and extract_lets (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (e : texpression) : unit = (* Destruct the lets. @@ -690,7 +692,7 @@ and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) *) let lets, next_e = match !backend with - | HOL4 -> destruct_lets_no_interleave e + | HOL4 -> destruct_lets_no_interleave meta e | FStar | Coq | Lean -> destruct_lets e in (* Extract the let-bindings *) @@ -711,16 +713,16 @@ and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) * TODO: cleanup * *) if monadic && (!backend = Coq || !backend = HOL4) then ( - let ctx = extract_typed_pattern ctx fmt true true lv in + let ctx = extract_typed_pattern meta ctx fmt true true lv in F.pp_print_space fmt (); let arrow = match !backend with | Coq | HOL4 -> "<-" - | FStar | Lean -> raise (Failure "impossible") + | FStar | Lean -> craise meta "impossible" in F.pp_print_string fmt arrow; F.pp_print_space fmt (); - extract_texpression ctx fmt false re; + extract_texpression meta ctx fmt false re; F.pp_print_string fmt ";"; ctx) else ( @@ -737,7 +739,7 @@ and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) else ( F.pp_print_string fmt "let"; F.pp_print_space fmt ()); - let ctx = extract_typed_pattern ctx fmt true true lv in + let ctx = extract_typed_pattern meta ctx fmt true true lv in F.pp_print_space fmt (); let eq = match !backend with @@ -748,7 +750,7 @@ and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) in F.pp_print_string fmt eq; F.pp_print_space fmt (); - extract_texpression ctx fmt false re; + extract_texpression meta ctx fmt false re; (* End the let-binding *) (match !backend with | Lean -> @@ -776,7 +778,7 @@ and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) if inside && !backend <> Lean then F.pp_print_string fmt "("; (* If Lean and HOL4, we rely on monadic blocks, so we insert a do and open a new box immediately *) - let wrap_in_do_od = lets_require_wrap_in_do lets in + let wrap_in_do_od = lets_require_wrap_in_do meta lets in if wrap_in_do_od then ( F.pp_print_string fmt "do"; F.pp_print_space fmt ()); @@ -788,7 +790,7 @@ and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (* Open a box for the next expression *) F.pp_open_hovbox fmt ctx.indent_incr; (* Print the next expression *) - extract_texpression ctx fmt false next_e; + extract_texpression meta ctx fmt false next_e; (* Close the box for the next expression *) F.pp_close_box fmt (); @@ -802,7 +804,7 @@ and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (* Close the box for the whole expression *) F.pp_close_box fmt () -and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) +and extract_Switch (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) (scrut : texpression) (body : switch_body) : unit = (* Remark: we don't use the [inside] parameter because we extract matches in a conservative manner: we always make sure they are parenthesized/delimited @@ -821,8 +823,8 @@ and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) F.pp_print_string fmt "if"; if !backend = Lean && ctx.use_dep_ite then F.pp_print_string fmt " h:"; F.pp_print_space fmt (); - let scrut_inside = PureUtils.texpression_requires_parentheses scrut in - extract_texpression ctx fmt scrut_inside scrut; + let scrut_inside = PureUtils.texpression_requires_parentheses meta scrut in + extract_texpression meta ctx fmt scrut_inside scrut; (* Close the box for the [if e] *) F.pp_close_box fmt (); @@ -835,7 +837,7 @@ and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) F.pp_open_hovbox fmt 0; let then_or_else = if is_then then "then" else "else" in F.pp_print_string fmt then_or_else; - let parenth = PureUtils.texpression_requires_parentheses e_branch in + let parenth = PureUtils.texpression_requires_parentheses meta e_branch in (* Open the parenthesized expression *) let print_space_after_parenth = if parenth then ( @@ -856,7 +858,7 @@ and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) (* Open a box for the branch *) F.pp_open_hovbox fmt ctx.indent_incr; (* Print the branch expression *) - extract_texpression ctx fmt false e_branch; + extract_texpression meta ctx fmt false e_branch; (* Close the box for the branch *) F.pp_close_box fmt (); (* Close the parenthesized expression *) @@ -887,8 +889,8 @@ and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) in F.pp_print_string fmt match_begin; F.pp_print_space fmt (); - let scrut_inside = PureUtils.texpression_requires_parentheses scrut in - extract_texpression ctx fmt scrut_inside scrut; + let scrut_inside = PureUtils.texpression_requires_parentheses meta scrut in + extract_texpression meta ctx fmt scrut_inside scrut; F.pp_print_space fmt (); let match_scrut_end = match !backend with FStar | Coq | Lean -> "with" | HOL4 -> "of" @@ -907,7 +909,7 @@ and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) (* Print the pattern *) F.pp_print_string fmt "|"; F.pp_print_space fmt (); - let ctx = extract_typed_pattern ctx fmt false false br.pat in + let ctx = extract_typed_pattern meta ctx fmt false false br.pat in F.pp_print_space fmt (); let arrow = match !backend with FStar -> "->" | Coq | Lean | HOL4 -> "=>" @@ -919,7 +921,7 @@ and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) (* Open a box for the branch *) F.pp_open_hovbox fmt ctx.indent_incr; (* Print the branch itself *) - extract_texpression ctx fmt false br.branch; + extract_texpression meta ctx fmt false br.branch; (* Close the box for the branch *) F.pp_close_box fmt (); (* Close the box for the pattern+branch *) @@ -938,11 +940,11 @@ and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) (* Close the box for the whole expression *) F.pp_close_box fmt () -and extract_StructUpdate (ctx : extraction_ctx) (fmt : F.formatter) +and extract_StructUpdate (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (e_ty : ty) (supd : struct_update) : unit = (* We can't update a subset of the fields in Coq (i.e., we can do [{| x:= 3; y := 4 |}], but there is no syntax for [{| s with x := 3 |}]) *) - assert (!backend <> Coq || supd.init = None); + cassert (!backend <> Coq || supd.init = None) meta "TODO: error message"; (* In the case of HOL4, records with no fields are not supported and are thus extracted to unit. We need to check that by looking up the definition *) let extract_as_unit = @@ -1007,7 +1009,7 @@ and extract_StructUpdate (ctx : extraction_ctx) (fmt : F.formatter) if need_paren then F.pp_print_string fmt "("; F.pp_open_hvbox fmt ctx.indent_incr; if supd.init <> None then ( - let var_name = ctx_get_var (Option.get supd.init) ctx in + let var_name = ctx_get_var meta (Option.get supd.init) ctx in F.pp_print_string fmt var_name; F.pp_print_space fmt (); F.pp_print_string fmt "with"; @@ -1026,12 +1028,12 @@ and extract_StructUpdate (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_space fmt ()) (fun (fid, fe) -> F.pp_open_hvbox fmt ctx.indent_incr; - let f = ctx_get_field supd.struct_id fid ctx in + let f = ctx_get_field meta supd.struct_id fid ctx in F.pp_print_string fmt f; F.pp_print_string fmt (" " ^ assign); F.pp_print_space fmt (); F.pp_open_hvbox fmt ctx.indent_incr; - extract_texpression ctx fmt true fe; + extract_texpression meta ctx fmt true fe; F.pp_close_box fmt (); F.pp_close_box fmt ()) supd.updates; @@ -1050,16 +1052,16 @@ and extract_StructUpdate (ctx : extraction_ctx) (fmt : F.formatter) (* Open the box for `Array.replicate T N [` *) F.pp_open_hovbox fmt ctx.indent_incr; (* Print the array constructor *) - let cs = ctx_get_struct (TAssumed TArray) ctx in + let cs = ctx_get_struct meta (TAssumed TArray) ctx in F.pp_print_string fmt cs; (* Print the parameters *) - let _, generics = ty_as_adt e_ty in + let _, generics = ty_as_adt meta e_ty in let ty = Collections.List.to_cons_nil generics.types in F.pp_print_space fmt (); - extract_ty ctx fmt TypeDeclId.Set.empty true ty; + extract_ty meta ctx fmt TypeDeclId.Set.empty true ty; let cg = Collections.List.to_cons_nil generics.const_generics in F.pp_print_space fmt (); - extract_const_generic ctx fmt true cg; + extract_const_generic meta ctx fmt true cg; F.pp_print_space fmt (); F.pp_print_string fmt "["; (* Close the box for `Array.mk T N [` *) @@ -1074,7 +1076,7 @@ and extract_StructUpdate (ctx : extraction_ctx) (fmt : F.formatter) (fun () -> F.pp_print_string fmt delimiter; F.pp_print_space fmt ()) - (fun (_, fe) -> extract_texpression ctx fmt false fe) + (fun (_, fe) -> extract_texpression meta ctx fmt false fe) supd.updates; (* Close the boxes *) F.pp_close_box fmt (); @@ -1082,7 +1084,7 @@ and extract_StructUpdate (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_string fmt "]"; if need_paren then F.pp_print_string fmt ")"; F.pp_close_box fmt () - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" (** A small utility to print the parameters of a function signature. @@ -1116,7 +1118,7 @@ let extract_fun_parameters (space : bool ref) (ctx : extraction_ctx) match def.kind with | TraitItemProvided (decl_id, _) -> let trait_decl = T.TraitDeclId.Map.find decl_id ctx.trans_trait_decls in - let ctx, _ = ctx_add_trait_self_clause ctx in + let ctx, _ = ctx_add_trait_self_clause def.meta ctx in let ctx = { ctx with is_provided_method = true } in (ctx, Some trait_decl) | _ -> (ctx, None) @@ -1124,14 +1126,14 @@ let extract_fun_parameters (space : bool ref) (ctx : extraction_ctx) (* Add the type parameters - note that we need those bindings only for the * body translation (they are not top-level) *) let ctx, type_params, cg_params, trait_clauses = - ctx_add_generic_params def.llbc_name def.signature.llbc_generics + ctx_add_generic_params def.meta def.llbc_name def.signature.llbc_generics def.signature.generics ctx in (* Print the generics *) (* Open a box for the generics *) F.pp_open_hovbox fmt 0; (let space = Some space in - extract_generic_params ctx fmt TypeDeclId.Set.empty ~space ~trait_decl + extract_generic_params def.meta ctx fmt TypeDeclId.Set.empty ~space ~trait_decl def.signature.generics type_params cg_params trait_clauses); (* Close the box for the generics *) F.pp_close_box fmt (); @@ -1146,11 +1148,11 @@ let extract_fun_parameters (space : bool ref) (ctx : extraction_ctx) (* Open a box for the input parameter *) F.pp_open_hovbox fmt 0; F.pp_print_string fmt "("; - let ctx = extract_typed_pattern ctx fmt true false lv in + let ctx = extract_typed_pattern def.meta ctx fmt true false lv in F.pp_print_space fmt (); F.pp_print_string fmt ":"; F.pp_print_space fmt (); - extract_ty ctx fmt TypeDeclId.Set.empty false lv.ty; + extract_ty def.meta ctx fmt TypeDeclId.Set.empty false lv.ty; F.pp_print_string fmt ")"; (* Close the box for the input parameters *) F.pp_close_box fmt (); @@ -1169,7 +1171,7 @@ let extract_fun_input_parameters_types (ctx : extraction_ctx) (fmt : F.formatter) (def : fun_decl) : unit = let extract_param (ty : ty) : unit = let inside = false in - extract_ty ctx fmt TypeDeclId.Set.empty inside ty; + extract_ty def.meta ctx fmt TypeDeclId.Set.empty inside ty; F.pp_print_space fmt (); extract_arrow fmt (); F.pp_print_space fmt () @@ -1179,14 +1181,14 @@ let extract_fun_input_parameters_types (ctx : extraction_ctx) let extract_fun_inputs_output_parameters_types (ctx : extraction_ctx) (fmt : F.formatter) (def : fun_decl) : unit = extract_fun_input_parameters_types ctx fmt def; - extract_ty ctx fmt TypeDeclId.Set.empty false def.signature.output + extract_ty def.meta ctx fmt TypeDeclId.Set.empty false def.signature.output -let assert_backend_supports_decreases_clauses () = +let assert_backend_supports_decreases_clauses (meta : Meta.meta) = match !backend with | FStar | Lean -> () | _ -> - raise - (Failure "decreases clauses only supported for the Lean & F* backends") + craise + meta "decreases clauses only supported for the Lean & F* backends" (** Extract a decreases clause function template body. @@ -1206,10 +1208,10 @@ let assert_backend_supports_decreases_clauses () = *) let extract_template_fstar_decreases_clause (ctx : extraction_ctx) (fmt : F.formatter) (def : fun_decl) : unit = - assert (!backend = FStar); + cassert (!backend = FStar) def.meta "TODO: error message"; (* Retrieve the function name *) - let def_name = ctx_get_termination_measure def.def_id def.loop_id ctx in + let def_name = ctx_get_termination_measure def.meta def.def_id def.loop_id ctx in (* Add a break before *) F.pp_print_break fmt 0 0; (* Print a comment to link the extracted type to its original rust definition *) @@ -1271,12 +1273,12 @@ let extract_template_fstar_decreases_clause (ctx : extraction_ctx) *) let extract_template_lean_termination_and_decreasing (ctx : extraction_ctx) (fmt : F.formatter) (def : fun_decl) : unit = - assert (!backend = Lean); + cassert (!backend = Lean) def.meta "TODO: error message"; (* * Extract a template for the termination measure *) (* Retrieve the function name *) - let def_name = ctx_get_termination_measure def.def_id def.loop_id ctx in + let def_name = ctx_get_termination_measure def.meta def.def_id def.loop_id ctx in let def_body = Option.get def.body in (* Add a break before *) F.pp_print_break fmt 0 0; @@ -1311,7 +1313,7 @@ let extract_template_lean_termination_and_decreasing (ctx : extraction_ctx) let vars = List.map (fun (v : var) -> v.id) def_body.inputs in if List.length vars = 1 then - F.pp_print_string fmt (ctx_get_var (List.hd vars) ctx_body) + F.pp_print_string fmt (ctx_get_var def.meta (List.hd vars) ctx_body) else ( F.pp_open_hovbox fmt 0; F.pp_print_string fmt "("; @@ -1319,7 +1321,7 @@ let extract_template_lean_termination_and_decreasing (ctx : extraction_ctx) (fun () -> F.pp_print_string fmt ","; F.pp_print_space fmt ()) - (fun v -> F.pp_print_string fmt (ctx_get_var v ctx_body)) + (fun v -> F.pp_print_string fmt (ctx_get_var def.meta v ctx_body)) vars; F.pp_print_string fmt ")"; F.pp_close_box fmt ()); @@ -1333,7 +1335,7 @@ let extract_template_lean_termination_and_decreasing (ctx : extraction_ctx) (* * Extract a template for the decreases proof *) - let def_name = ctx_get_decreases_proof def.def_id def.loop_id ctx in + let def_name = ctx_get_decreases_proof def.meta def.def_id def.loop_id ctx in (* syntax <def_name> term ... term : tactic *) F.pp_print_break fmt 0 0; extract_comment_with_span ctx fmt @@ -1356,7 +1358,7 @@ let extract_template_lean_termination_and_decreasing (ctx : extraction_ctx) (fun v -> F.pp_print_space fmt (); F.pp_print_string fmt "$"; - F.pp_print_string fmt (ctx_get_var v ctx_body)) + F.pp_print_string fmt (ctx_get_var def.meta v ctx_body)) vars; F.pp_print_string fmt ") =>"; F.pp_close_box fmt (); @@ -1394,9 +1396,9 @@ let extract_fun_comment (ctx : extraction_ctx) (fmt : F.formatter) *) let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) (kind : decl_kind) (has_decreases_clause : bool) (def : fun_decl) : unit = - assert (not def.is_global_decl_body); + cassert (not def.is_global_decl_body) def.meta "TODO: error message"; (* Retrieve the function name *) - let def_name = ctx_get_local_function def.def_id def.loop_id ctx in + let def_name = ctx_get_local_function def.meta def.def_id def.loop_id ctx in (* Add a break before *) if !backend <> HOL4 || not (decl_is_first_from_group kind) then F.pp_print_break fmt 0 0; @@ -1466,18 +1468,18 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) if is_opaque then extract_fun_input_parameters_types ctx fmt def; (* [Tot] *) if has_decreases_clause then ( - assert_backend_supports_decreases_clauses (); + assert_backend_supports_decreases_clauses def.meta; if !backend = FStar then ( F.pp_print_string fmt "Tot"; F.pp_print_space fmt ())); - extract_ty ctx fmt TypeDeclId.Set.empty has_decreases_clause + extract_ty def.meta ctx fmt TypeDeclId.Set.empty has_decreases_clause def.signature.output; (* Close the box for the return type *) F.pp_close_box fmt (); (* Print the decrease clause - rk.: a function with a decreases clause * is necessarily a transparent function *) if has_decreases_clause && !backend = FStar then ( - assert_backend_supports_decreases_clauses (); + assert_backend_supports_decreases_clauses def.meta; F.pp_print_space fmt (); (* Open a box for the decreases clause *) F.pp_open_hovbox fmt ctx.indent_incr; @@ -1487,7 +1489,7 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) (* Open a box for the decreases term *) F.pp_open_hovbox fmt ctx.indent_incr; (* The name of the decrease clause *) - let decr_name = ctx_get_termination_measure def.def_id def.loop_id ctx in + let decr_name = ctx_get_termination_measure def.meta def.def_id def.loop_id ctx in F.pp_print_string fmt decr_name; (* Print the generic parameters - TODO: we do this many times, we should have a helper to factor it out *) @@ -1517,7 +1519,7 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) List.fold_left (fun ctx (lv : typed_pattern) -> F.pp_print_space fmt (); - let ctx = extract_typed_pattern ctx fmt true false lv in + let ctx = extract_typed_pattern def.meta ctx fmt true false lv in ctx) ctx inputs_lvs in @@ -1543,7 +1545,7 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) (* Open a box for the body *) F.pp_open_hvbox fmt 0; (* Extract the body *) - let _ = extract_texpression ctx_body fmt false (Option.get def.body).body in + let _ = extract_texpression def.meta ctx_body fmt false (Option.get def.body).body in (* Close the box for the body *) F.pp_close_box fmt ()); (* Close the inner box for the definition *) @@ -1559,7 +1561,7 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) (* termination_by *) let terminates_name = - ctx_get_termination_measure def.def_id def.loop_id ctx + ctx_get_termination_measure def.meta def.def_id def.loop_id ctx in F.pp_print_break fmt 0 0; (* Open a box for the whole [termination_by CALL => DECREASES] *) @@ -1572,7 +1574,7 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) List.iter (fun v -> F.pp_print_space fmt (); - F.pp_print_string fmt (ctx_get_var v ctx_body)) + F.pp_print_string fmt (ctx_get_var def.meta v ctx_body)) all_vars; F.pp_print_space fmt (); F.pp_print_string fmt "=>"; @@ -1592,7 +1594,7 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) List.iter (fun v -> F.pp_print_space fmt (); - F.pp_print_string fmt (ctx_get_var v ctx_body)) + F.pp_print_string fmt (ctx_get_var def.meta v ctx_body)) vars; (* Close the box for [DECREASES] *) F.pp_close_box fmt (); @@ -1602,7 +1604,7 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_break fmt 0 0; (* Open a box for the [decreasing by ...] *) F.pp_open_hvbox fmt ctx.indent_incr; - let decreases_name = ctx_get_decreases_proof def.def_id def.loop_id ctx in + let decreases_name = ctx_get_decreases_proof def.meta def.def_id def.loop_id ctx in F.pp_print_string fmt "decreasing_by"; F.pp_print_space fmt (); F.pp_open_hvbox fmt ctx.indent_incr; @@ -1610,7 +1612,7 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) List.iter (fun v -> F.pp_print_space fmt (); - F.pp_print_string fmt (ctx_get_var v ctx_body)) + F.pp_print_string fmt (ctx_get_var def.meta v ctx_body)) vars; F.pp_close_box fmt (); (* Close the box for the [decreasing by ...] *) @@ -1640,12 +1642,12 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) let extract_fun_decl_hol4_opaque (ctx : extraction_ctx) (fmt : F.formatter) (def : fun_decl) : unit = (* Retrieve the definition name *) - let def_name = ctx_get_local_function def.def_id def.loop_id ctx in - assert (def.signature.generics.const_generics = []); + let def_name = ctx_get_local_function def.meta def.def_id def.loop_id ctx in + cassert (def.signature.generics.const_generics = []) def.meta "TODO: error message"; (* Add the type/const gen parameters - note that we need those bindings only for the generation of the type (they are not top-level) *) let ctx, _, _, _ = - ctx_add_generic_params def.llbc_name def.signature.llbc_generics + ctx_add_generic_params def.meta def.llbc_name def.signature.llbc_generics def.signature.generics ctx in (* Add breaks to insert new lines between definitions *) @@ -1662,7 +1664,7 @@ let extract_fun_decl_hol4_opaque (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_string fmt "“:"; (* Generate the type *) extract_fun_input_parameters_types ctx fmt def; - extract_ty ctx fmt TypeDeclId.Set.empty false def.signature.output; + extract_ty def.meta ctx fmt TypeDeclId.Set.empty false def.signature.output; (* Close the box for the type *) F.pp_print_string fmt "”"; F.pp_close_box fmt (); @@ -1687,7 +1689,7 @@ let extract_fun_decl_hol4_opaque (ctx : extraction_ctx) (fmt : F.formatter) *) let extract_fun_decl (ctx : extraction_ctx) (fmt : F.formatter) (kind : decl_kind) (has_decreases_clause : bool) (def : fun_decl) : unit = - assert (not def.is_global_decl_body); + cassert (not def.is_global_decl_body) def.meta "TODO: error message"; (* We treat HOL4 opaque functions in a specific manner *) if !backend = HOL4 && Option.is_none def.body then extract_fun_decl_hol4_opaque ctx fmt def @@ -1700,7 +1702,7 @@ let extract_fun_decl (ctx : extraction_ctx) (fmt : F.formatter) extracted to two declarations, and we can actually factor out the generation of those declarations. See {!extract_global_decl} for more explanations. *) -let extract_global_decl_body_gen (ctx : extraction_ctx) (fmt : F.formatter) +let extract_global_decl_body_gen (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (kind : decl_kind) (name : string) (generics : generic_params) (type_params : string list) (cg_params : string list) (trait_clauses : string list) (ty : ty) @@ -1746,7 +1748,7 @@ let extract_global_decl_body_gen (ctx : extraction_ctx) (fmt : F.formatter) (* Open "TYPE" box (depth=3) *) F.pp_open_hovbox fmt ctx.indent_incr; (* Print "TYPE" *) - extract_ty ctx fmt TypeDeclId.Set.empty false ty; + extract_ty meta ctx fmt TypeDeclId.Set.empty false ty; (* Close "TYPE" box (depth=3) *) F.pp_close_box fmt (); @@ -1792,7 +1794,7 @@ let extract_global_decl_body_gen (ctx : extraction_ctx) (fmt : F.formatter) Remark (SH): having to treat this specific case separately is very annoying, but I could not find a better way. *) -let extract_global_decl_hol4_opaque (ctx : extraction_ctx) (fmt : F.formatter) +let extract_global_decl_hol4_opaque (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (name : string) (generics : generic_params) (ty : ty) : unit = (* TODO: non-empty generics *) assert (generics = empty_generic_params); @@ -1805,7 +1807,7 @@ let extract_global_decl_hol4_opaque (ctx : extraction_ctx) (fmt : F.formatter) F.pp_close_box fmt (); (* Print the type *) F.pp_open_hovbox fmt 0; - extract_ty ctx fmt TypeDeclId.Set.empty false ty; + extract_ty meta ctx fmt TypeDeclId.Set.empty false ty; (* Close the definition *) F.pp_print_string fmt ")"; F.pp_close_box fmt (); @@ -1836,8 +1838,8 @@ let extract_global_decl_hol4_opaque (ctx : extraction_ctx) (fmt : F.formatter) *) let extract_global_decl (ctx : extraction_ctx) (fmt : F.formatter) (global : global_decl) (body : fun_decl) (interface : bool) : unit = - assert body.is_global_decl_body; - assert (body.signature.inputs = []); + cassert body.is_global_decl_body body.meta "TODO: Error message"; + cassert (body.signature.inputs = []) body.meta "TODO: Error message"; (* Add a break then the name of the corresponding LLBC declaration *) F.pp_print_break fmt 0 0; @@ -1851,14 +1853,14 @@ let extract_global_decl (ctx : extraction_ctx) (fmt : F.formatter) name global.meta.span; F.pp_print_space fmt (); - let decl_name = ctx_get_global global.def_id ctx in + let decl_name = ctx_get_global meta global.def_id ctx in let body_name = - ctx_get_function (FromLlbc (Pure.FunId (FRegular global.body_id), None)) ctx + ctx_get_function meta (FromLlbc (Pure.FunId (FRegular global.body_id), None)) ctx in let decl_ty, body_ty = let ty = body.signature.output in if body.signature.fwd_info.effect_info.can_fail then - (unwrap_result_ty ty, ty) + (unwrap_result_ty meta ty, ty) else (ty, mk_result_ty ty) in (* Add the type parameters *) @@ -1871,20 +1873,20 @@ let extract_global_decl (ctx : extraction_ctx) (fmt : F.formatter) (* No body: only generate a [val x_c : u32] declaration *) let kind = if interface then Declared else Assumed in if !backend = HOL4 then - extract_global_decl_hol4_opaque ctx fmt decl_name global.generics + extract_global_decl_hol4_opaque meta ctx fmt decl_name global.generics decl_ty else - extract_global_decl_body_gen ctx fmt kind decl_name global.generics + extract_global_decl_body_gen meta ctx fmt kind decl_name global.generics type_params cg_params trait_clauses decl_ty None | Some body -> (* There is a body *) (* Generate: [let x_body : result u32 = Return 3] *) - extract_global_decl_body_gen ctx fmt SingleNonRec body_name + extract_global_decl_body_gen meta ctx fmt SingleNonRec body_name global.generics type_params cg_params trait_clauses body_ty - (Some (fun fmt -> extract_texpression ctx fmt false body.body)); + (Some (fun fmt -> extract_texpression meta ctx fmt false body.body)); F.pp_print_break fmt 0 0; (* Generate: [let x_c : u32 = eval_global x_body] *) - extract_global_decl_body_gen ctx fmt SingleNonRec decl_name + extract_global_decl_body_gen meta ctx fmt SingleNonRec decl_name global.generics type_params cg_params trait_clauses decl_ty (Some (fun fmt -> @@ -1953,7 +1955,7 @@ let extract_trait_decl_register_parent_clause_names (ctx : extraction_ctx) (* Register the names *) List.fold_left (fun ctx (cid, cname) -> - ctx_add (TraitParentClauseId (trait_decl.def_id, cid)) cname ctx) + ctx_add trait_decl.meta (TraitParentClauseId (trait_decl.def_id, cid)) cname ctx) ctx clause_names (** Similar to {!extract_trait_decl_register_names} *) @@ -1986,7 +1988,7 @@ let extract_trait_decl_register_constant_names (ctx : extraction_ctx) (* Register the names *) List.fold_left (fun ctx (item_name, name) -> - ctx_add (TraitItemId (trait_decl.def_id, item_name)) name ctx) + ctx_add trait_decl.meta (TraitItemId (trait_decl.def_id, item_name)) name ctx) ctx constant_names (** Similar to {!extract_trait_decl_register_names} *) @@ -2045,11 +2047,11 @@ let extract_trait_decl_type_names (ctx : extraction_ctx) List.fold_left (fun ctx (item_name, (type_name, clauses)) -> let ctx = - ctx_add (TraitItemId (trait_decl.def_id, item_name)) type_name ctx + ctx_add trait_decl.meta (TraitItemId (trait_decl.def_id, item_name)) type_name ctx in List.fold_left (fun ctx (clause_id, clause_name) -> - ctx_add + ctx_add trait_decl.meta (TraitItemClauseId (trait_decl.def_id, item_name, clause_id)) clause_name ctx) ctx clauses) @@ -2101,7 +2103,7 @@ let extract_trait_decl_method_names (ctx : extraction_ctx) (* Register the names *) List.fold_left (fun ctx (item_name, fun_name) -> - ctx_add (TraitMethodId (trait_decl.def_id, item_name)) fun_name ctx) + ctx_add trait_decl.meta (TraitMethodId (trait_decl.def_id, item_name)) fun_name ctx) ctx method_names (** Similar to {!extract_type_decl_register_names} *) @@ -2121,8 +2123,8 @@ let extract_trait_decl_register_names (ctx : extraction_ctx) ctx_compute_trait_decl_constructor ctx trait_decl ) | Some info -> (info.extract_name, info.constructor) in - let ctx = ctx_add (TraitDeclId trait_decl.def_id) trait_name ctx in - ctx_add (TraitDeclConstructorId trait_decl.def_id) trait_constructor ctx + let ctx = ctx_add trait_decl.meta (TraitDeclId trait_decl.def_id) trait_name ctx in + ctx_add trait_decl.meta (TraitDeclConstructorId trait_decl.def_id) trait_constructor ctx in (* Parent clauses *) let ctx = @@ -2176,7 +2178,7 @@ let extract_trait_impl_register_names (ctx : extraction_ctx) in (* For now we do not support overriding provided methods *) - assert (trait_impl.provided_methods = []); + cassert (trait_impl.provided_methods = []) trait_impl.meta "Overriding provided methods is not supported yet"; (* Everything is taken care of by {!extract_trait_decl_register_names} *but* the name of the implementation itself *) (* Compute the name *) @@ -2185,7 +2187,7 @@ let extract_trait_impl_register_names (ctx : extraction_ctx) | None -> ctx_compute_trait_impl_name ctx trait_decl trait_impl | Some name -> name in - ctx_add (TraitImplId trait_impl.def_id) name ctx + ctx_add trait_decl.meta (TraitImplId trait_impl.def_id) name ctx (** Small helper. @@ -2250,7 +2252,7 @@ let extract_trait_decl_method_items (ctx : extraction_ctx) (fmt : F.formatter) - we only generate trait clauses for the clauses we find in the pure generics *) let ctx, type_params, cg_params, trait_clauses = - ctx_add_generic_params f.llbc_name f.signature.llbc_generics generics ctx + ctx_add_generic_params f.meta f.llbc_name f.signature.llbc_generics generics ctx (* TODO: confirm it's the right meta*) in let backend_uses_forall = match !backend with Coq | Lean -> true | FStar | HOL4 -> false @@ -2259,9 +2261,9 @@ let extract_trait_decl_method_items (ctx : extraction_ctx) (fmt : F.formatter) let use_forall = generics_not_empty && backend_uses_forall in let use_arrows = generics_not_empty && not backend_uses_forall in let use_forall_use_sep = false in - extract_generic_params ctx fmt TypeDeclId.Set.empty ~use_forall + extract_generic_params f.meta ctx fmt TypeDeclId.Set.empty ~use_forall ~use_forall_use_sep ~use_arrows generics type_params cg_params - trait_clauses; + trait_clauses; (* TODO: confirm it's the right meta*) if use_forall then F.pp_print_string fmt ","; (* Extract the inputs and output *) F.pp_print_space fmt (); @@ -2301,7 +2303,7 @@ let extract_trait_decl (ctx : extraction_ctx) (fmt : F.formatter) (* Open the box for the name + generics *) F.pp_open_hovbox fmt ctx.indent_incr; let qualif = - Option.get (type_decl_kind_to_qualif SingleNonRec (Some Struct)) + Option.get (type_decl_kind_to_qualif decl.meta SingleNonRec (Some Struct)) in (* When checking if the trait declaration is empty: we ignore the provided methods, because for now they are extracted separately *) @@ -2317,9 +2319,9 @@ let extract_trait_decl (ctx : extraction_ctx) (fmt : F.formatter) (* Add the type and const generic params - note that we need those bindings only for the * body translation (they are not top-level) *) let ctx, type_params, cg_params, trait_clauses = - ctx_add_generic_params decl.llbc_name decl.llbc_generics generics ctx + ctx_add_generic_params decl.meta decl.llbc_name decl.llbc_generics generics ctx in - extract_generic_params ctx fmt TypeDeclId.Set.empty generics type_params + extract_generic_params decl.meta ctx fmt TypeDeclId.Set.empty generics type_params cg_params trait_clauses; F.pp_print_space fmt (); @@ -2356,7 +2358,7 @@ let extract_trait_decl (ctx : extraction_ctx) (fmt : F.formatter) let ty () = let inside = false in F.pp_print_space fmt (); - extract_ty ctx fmt TypeDeclId.Set.empty inside ty + extract_ty decl.meta ctx fmt TypeDeclId.Set.empty inside ty in extract_trait_decl_item ctx fmt item_name ty) decl.consts; @@ -2368,7 +2370,7 @@ let extract_trait_decl (ctx : extraction_ctx) (fmt : F.formatter) let item_name = ctx_get_trait_type decl.def_id name ctx in let ty () = F.pp_print_space fmt (); - F.pp_print_string fmt (type_keyword ()) + F.pp_print_string fmt (type_keyword decl.meta) in extract_trait_decl_item ctx fmt item_name ty; (* Extract the clauses *) @@ -2379,7 +2381,7 @@ let extract_trait_decl (ctx : extraction_ctx) (fmt : F.formatter) in let ty () = F.pp_print_space fmt (); - extract_trait_clause_type ctx fmt TypeDeclId.Set.empty clause + extract_trait_clause_type decl.meta ctx fmt TypeDeclId.Set.empty clause in extract_trait_decl_item ctx fmt item_name ty) clauses) @@ -2394,7 +2396,7 @@ let extract_trait_decl (ctx : extraction_ctx) (fmt : F.formatter) in let ty () = F.pp_print_space fmt (); - extract_trait_clause_type ctx fmt TypeDeclId.Set.empty clause + extract_trait_clause_type decl.meta ctx fmt TypeDeclId.Set.empty clause in extract_trait_decl_item ctx fmt item_name ty) decl.parent_clauses; @@ -2531,16 +2533,16 @@ let extract_trait_impl_method_items (ctx : extraction_ctx) (fmt : F.formatter) - we only generate trait clauses for the clauses we find in the pure generics *) let ctx, f_tys, f_cgs, f_tcs = - ctx_add_generic_params f.llbc_name f.signature.llbc_generics f_generics + ctx_add_generic_params f.meta f.llbc_name f.signature.llbc_generics f_generics ctx in let use_forall = f_generics <> empty_generic_params in - extract_generic_params ctx fmt TypeDeclId.Set.empty ~use_forall f_generics + extract_generic_params f.meta ctx fmt TypeDeclId.Set.empty ~use_forall f_generics f_tys f_cgs f_tcs; if use_forall then F.pp_print_string fmt ","; (* Extract the function call *) F.pp_print_space fmt (); - let fun_name = ctx_get_local_function f.def_id None ctx in + let fun_name = ctx_get_local_function f.meta f.def_id None ctx in F.pp_print_string fmt fun_name; let all_generics = let _, i_cgs, i_tcs = impl_generics in @@ -2556,7 +2558,9 @@ let extract_trait_impl_method_items (ctx : extraction_ctx) (fmt : F.formatter) in extract_trait_impl_item ctx fmt fun_name ty -(** Extract a trait implementation *) +(** Extract a trait implementation + * TODO: check if impl.meta everywhere is the right meta +*) let extract_trait_impl (ctx : extraction_ctx) (fmt : F.formatter) (impl : trait_impl) : unit = log#ldebug (lazy ("extract_trait_impl: " ^ name_to_string ctx impl.llbc_name)); @@ -2602,17 +2606,17 @@ let extract_trait_impl (ctx : extraction_ctx) (fmt : F.formatter) (* Add the type and const generic params - note that we need those bindings only for the * body translation (they are not top-level) *) let ctx, type_params, cg_params, trait_clauses = - ctx_add_generic_params impl.llbc_name impl.llbc_generics impl.generics ctx + ctx_add_generic_params impl.meta impl.llbc_name impl.llbc_generics impl.generics ctx in let all_generics = (type_params, cg_params, trait_clauses) in - extract_generic_params ctx fmt TypeDeclId.Set.empty impl.generics type_params + extract_generic_params impl.meta ctx fmt TypeDeclId.Set.empty impl.generics type_params cg_params trait_clauses; (* Print the type *) F.pp_print_space fmt (); F.pp_print_string fmt ":"; F.pp_print_space fmt (); - extract_trait_decl_ref ctx fmt TypeDeclId.Set.empty false impl.impl_trait; + extract_trait_decl_ref impl.meta ctx fmt TypeDeclId.Set.empty false impl.impl_trait; (* When checking if the trait impl is empty: we ignore the provided methods, because for now they are extracted separately *) @@ -2668,7 +2672,7 @@ let extract_trait_impl (ctx : extraction_ctx) (fmt : F.formatter) in let ty () = F.pp_print_space fmt (); - F.pp_print_string fmt (ctx_get_global id ctx); + F.pp_print_string fmt (ctx_get_global impl.meta id ctx); print_params () in @@ -2682,7 +2686,7 @@ let extract_trait_impl (ctx : extraction_ctx) (fmt : F.formatter) let item_name = ctx_get_trait_type trait_decl_id name ctx in let ty () = F.pp_print_space fmt (); - extract_ty ctx fmt TypeDeclId.Set.empty false ty + extract_ty impl.meta ctx fmt TypeDeclId.Set.empty false ty in extract_trait_impl_item ctx fmt item_name ty; (* Extract the clauses *) @@ -2693,7 +2697,7 @@ let extract_trait_impl (ctx : extraction_ctx) (fmt : F.formatter) in let ty () = F.pp_print_space fmt (); - extract_trait_ref ctx fmt TypeDeclId.Set.empty false trait_ref + extract_trait_ref impl.meta ctx fmt TypeDeclId.Set.empty false trait_ref in extract_trait_impl_item ctx fmt item_name ty) trait_refs) @@ -2707,7 +2711,7 @@ let extract_trait_impl (ctx : extraction_ctx) (fmt : F.formatter) in let ty () = F.pp_print_space fmt (); - extract_trait_ref ctx fmt TypeDeclId.Set.empty false trait_ref + extract_trait_ref impl.meta ctx fmt TypeDeclId.Set.empty false trait_ref in extract_trait_impl_item ctx fmt item_name ty) impl.parent_trait_refs; @@ -2770,7 +2774,7 @@ let extract_unit_test_if_unit_fun (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_string fmt "assert_norm"; F.pp_print_space fmt (); F.pp_print_string fmt "("; - let fun_name = ctx_get_local_function def.def_id def.loop_id ctx in + let fun_name = ctx_get_local_function def.meta def.def_id def.loop_id ctx in F.pp_print_string fmt fun_name; if sg.inputs <> [] then ( F.pp_print_space fmt (); @@ -2778,13 +2782,13 @@ let extract_unit_test_if_unit_fun (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_space fmt (); F.pp_print_string fmt "="; F.pp_print_space fmt (); - let success = ctx_get_variant (TAssumed TResult) result_return_id ctx in + let success = ctx_get_variant def.meta (TAssumed TResult) result_return_id ctx in F.pp_print_string fmt (success ^ " ())") | Coq -> F.pp_print_string fmt "Check"; F.pp_print_space fmt (); F.pp_print_string fmt "("; - let fun_name = ctx_get_local_function def.def_id def.loop_id ctx in + let fun_name = ctx_get_local_function def.meta def.def_id def.loop_id ctx in F.pp_print_string fmt fun_name; if sg.inputs <> [] then ( F.pp_print_space fmt (); @@ -2795,7 +2799,7 @@ let extract_unit_test_if_unit_fun (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_string fmt "#assert"; F.pp_print_space fmt (); F.pp_print_string fmt "("; - let fun_name = ctx_get_local_function def.def_id def.loop_id ctx in + let fun_name = ctx_get_local_function def.meta def.def_id def.loop_id ctx in F.pp_print_string fmt fun_name; if sg.inputs <> [] then ( F.pp_print_space fmt (); @@ -2803,12 +2807,12 @@ let extract_unit_test_if_unit_fun (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_space fmt (); F.pp_print_string fmt "=="; F.pp_print_space fmt (); - let success = ctx_get_variant (TAssumed TResult) result_return_id ctx in + let success = ctx_get_variant def.meta (TAssumed TResult) result_return_id ctx in F.pp_print_string fmt (success ^ " ())") | HOL4 -> F.pp_print_string fmt "val _ = assert_return ("; F.pp_print_string fmt "“"; - let fun_name = ctx_get_local_function def.def_id def.loop_id ctx in + let fun_name = ctx_get_local_function def.meta def.def_id def.loop_id ctx in F.pp_print_string fmt fun_name; if sg.inputs <> [] then ( F.pp_print_space fmt (); diff --git a/compiler/ExtractBase.ml b/compiler/ExtractBase.ml index 297a1d22..f6b891cc 100644 --- a/compiler/ExtractBase.ml +++ b/compiler/ExtractBase.ml @@ -7,6 +7,7 @@ open Config module F = Format open ExtractBuiltin open TranslateCore +open Errors (** The local logger *) let log = Logging.extract_log @@ -263,7 +264,7 @@ let report_name_collision (id_to_string : id -> string) (id1 : id) (id2 : id) in log#serror err; (* If we fail hard on errors, raise an exception *) - if !Config.fail_hard then raise (Failure err) + craise_opt_meta None err let names_map_get_id_from_name (name : string) (nm : names_map) : id option = StringMap.find_opt name nm.name_to_id @@ -297,7 +298,7 @@ let names_map_add (id_to_string : id -> string) (id : id) (name : string) in log#serror err; (* If we fail hard on errors, raise an exception *) - if !Config.fail_hard then raise (Failure err)); + craise_opt_meta None err); (* Insert *) names_map_add_unchecked id name nm @@ -424,7 +425,7 @@ let names_maps_add (id_to_string : id -> string) (id : id) (name : string) (** The [id_to_string] function to print nice debugging messages if there are collisions *) -let names_maps_get (id_to_string : id -> string) (id : id) (nm : names_maps) : +let names_maps_get (meta : Meta.meta) (id_to_string : id -> string) (id : id) (nm : names_maps) : string = (* We do not use the same name map if we allow/disallow collisions *) let map_to_string (m : string IdMap.t) : string = @@ -445,7 +446,7 @@ let names_maps_get (id_to_string : id -> string) (id : id) (nm : names_maps) : ^ map_to_string m in log#serror err; - if !Config.fail_hard then raise (Failure err) + if !Config.fail_hard then craise meta err else "(%%%ERROR: unknown identifier\": " ^ id_to_string id ^ "\"%%%)") else let m = nm.names_map.id_to_name in @@ -457,7 +458,7 @@ let names_maps_get (id_to_string : id -> string) (id : id) (nm : names_maps) : ^ map_to_string m in log#serror err; - if !Config.fail_hard then raise (Failure err) + if !Config.fail_hard then craise meta err else "(ERROR: \"" ^ id_to_string id ^ "\")" type names_map_init = { @@ -528,6 +529,7 @@ let scalar_name (ty : literal_type) : string = functions, etc. *) type extraction_ctx = { + (* mutable _meta : Meta.meta; *) crate : A.crate; trans_ctx : trans_ctx; names_maps : names_maps; @@ -589,17 +591,17 @@ let llbc_fun_id_to_string (ctx : extraction_ctx) = let fun_id_to_string (ctx : extraction_ctx) = PrintPure.regular_fun_id_to_string (extraction_ctx_to_fmt_env ctx) -let adt_variant_to_string (ctx : extraction_ctx) = - PrintPure.adt_variant_to_string (extraction_ctx_to_fmt_env ctx) +let adt_variant_to_string (meta : Meta.meta) (ctx : extraction_ctx) = + PrintPure.adt_variant_to_string meta (extraction_ctx_to_fmt_env ctx) -let adt_field_to_string (ctx : extraction_ctx) = - PrintPure.adt_field_to_string (extraction_ctx_to_fmt_env ctx) +let adt_field_to_string (meta : Meta.meta) (ctx : extraction_ctx) = + PrintPure.adt_field_to_string meta (extraction_ctx_to_fmt_env ctx) (** Debugging function, used when communicating name collisions to the user, and also to print ids for internal debugging (in case of lookup miss for instance). *) -let id_to_string (id : id) (ctx : extraction_ctx) : string = +let id_to_string (meta : Meta.meta) (id : id) (ctx : extraction_ctx) : string = let trait_decl_id_to_string (id : A.TraitDeclId.id) : string = let trait_name = trait_decl_id_to_string ctx id in "trait_decl: " ^ trait_name ^ " (id: " ^ A.TraitDeclId.to_string id ^ ")" @@ -627,11 +629,11 @@ let id_to_string (id : id) (ctx : extraction_ctx) : string = | StructId id -> "struct constructor of: " ^ type_id_to_string ctx id | VariantId (id, variant_id) -> let type_name = type_id_to_string ctx id in - let variant_name = adt_variant_to_string ctx id (Some variant_id) in + let variant_name = adt_variant_to_string meta ctx id (Some variant_id) in "type name: " ^ type_name ^ ", variant name: " ^ variant_name | FieldId (id, field_id) -> let type_name = type_id_to_string ctx id in - let field_name = adt_field_to_string ctx id field_id in + let field_name = adt_field_to_string meta ctx id field_id in "type name: " ^ type_name ^ ", field name: " ^ field_name | UnknownId -> "keyword" | TypeVarId id -> "type_var_id: " ^ TypeVarId.to_string id @@ -657,51 +659,55 @@ let id_to_string (id : id) (ctx : extraction_ctx) : string = trait_decl_id_to_string trait_decl_id ^ ", method name: " ^ fun_name | TraitSelfClauseId -> "trait_self_clause" -let ctx_add (id : id) (name : string) (ctx : extraction_ctx) : extraction_ctx = - let id_to_string (id : id) : string = id_to_string id ctx in +let ctx_add (meta : Meta.meta) (id : id) (name : string) (ctx : extraction_ctx) : extraction_ctx = + let id_to_string (id : id) : string = id_to_string meta id ctx in let names_maps = names_maps_add id_to_string id name ctx.names_maps in { ctx with names_maps } -let ctx_get (id : id) (ctx : extraction_ctx) : string = - let id_to_string (id : id) : string = id_to_string id ctx in - names_maps_get id_to_string id ctx.names_maps +let ctx_get (meta : Meta.meta) (id : id) (ctx : extraction_ctx) : string = + let id_to_string (id : id) : string = id_to_string meta id ctx in + names_maps_get meta id_to_string id ctx.names_maps (* TODO check if we can remove the meta arg, same for following functions*) -let ctx_get_global (id : A.GlobalDeclId.id) (ctx : extraction_ctx) : string = - ctx_get (GlobalId id) ctx +let ctx_get_global (meta : Meta.meta) (id : A.GlobalDeclId.id) (ctx : extraction_ctx) : string = + ctx_get meta (GlobalId id) ctx -let ctx_get_function (id : fun_id) (ctx : extraction_ctx) : string = - ctx_get (FunId id) ctx +let ctx_get_function (meta : Meta.meta) (id : fun_id) (ctx : extraction_ctx) : string = + ctx_get meta (FunId id) ctx -let ctx_get_local_function (id : A.FunDeclId.id) (lp : LoopId.id option) +let ctx_get_local_function (meta : Meta.meta) (id : A.FunDeclId.id) (lp : LoopId.id option) (ctx : extraction_ctx) : string = - ctx_get_function (FromLlbc (FunId (FRegular id), lp)) ctx + ctx_get_function meta (FromLlbc (FunId (FRegular id), lp)) ctx -let ctx_get_type (id : type_id) (ctx : extraction_ctx) : string = - assert (id <> TTuple); - ctx_get (TypeId id) ctx +let ctx_get_type (meta : Meta.meta) (id : type_id) (ctx : extraction_ctx) : string = + cassert (id <> TTuple) meta "T"; + ctx_get meta (TypeId id) ctx -let ctx_get_local_type (id : TypeDeclId.id) (ctx : extraction_ctx) : string = - ctx_get_type (TAdtId id) ctx +let ctx_get_local_type (meta : Meta.meta) (id : TypeDeclId.id) (ctx : extraction_ctx) : string = + ctx_get_type meta (TAdtId id) ctx -let ctx_get_assumed_type (id : assumed_ty) (ctx : extraction_ctx) : string = - ctx_get_type (TAssumed id) ctx +let ctx_get_assumed_type (meta : Meta.meta) (id : assumed_ty) (ctx : extraction_ctx) : string = + ctx_get_type meta (TAssumed id) ctx let ctx_get_trait_constructor (id : trait_decl_id) (ctx : extraction_ctx) : string = - ctx_get (TraitDeclConstructorId id) ctx + let meta = (TraitDeclId.Map.find id ctx.trans_trait_decls).meta in + ctx_get meta (TraitDeclConstructorId id) ctx -let ctx_get_trait_self_clause (ctx : extraction_ctx) : string = - ctx_get TraitSelfClauseId ctx +let ctx_get_trait_self_clause (meta : Meta.meta) (ctx : extraction_ctx) : string = + ctx_get meta TraitSelfClauseId ctx let ctx_get_trait_decl (id : trait_decl_id) (ctx : extraction_ctx) : string = - ctx_get (TraitDeclId id) ctx + let meta = (TraitDeclId.Map.find id ctx.trans_trait_decls).meta in + ctx_get meta (TraitDeclId id) ctx let ctx_get_trait_impl (id : trait_impl_id) (ctx : extraction_ctx) : string = - ctx_get (TraitImplId id) ctx + let meta = (TraitImplId.Map.find id ctx.trans_trait_impls).meta in + ctx_get meta (TraitImplId id) ctx let ctx_get_trait_item (id : trait_decl_id) (item_name : string) (ctx : extraction_ctx) : string = - ctx_get (TraitItemId (id, item_name)) ctx + let meta = (TraitDeclId.Map.find id ctx.trans_trait_decls).meta in + ctx_get meta (TraitItemId (id, item_name)) ctx let ctx_get_trait_const (id : trait_decl_id) (item_name : string) (ctx : extraction_ctx) : string = @@ -713,48 +719,52 @@ let ctx_get_trait_type (id : trait_decl_id) (item_name : string) let ctx_get_trait_method (id : trait_decl_id) (item_name : string) (ctx : extraction_ctx) : string = - ctx_get (TraitMethodId (id, item_name)) ctx + let meta = (TraitDeclId.Map.find id ctx.trans_trait_decls).meta in + ctx_get meta (TraitMethodId (id, item_name)) ctx let ctx_get_trait_parent_clause (id : trait_decl_id) (clause : trait_clause_id) (ctx : extraction_ctx) : string = - ctx_get (TraitParentClauseId (id, clause)) ctx + let meta = (TraitDeclId.Map.find id ctx.trans_trait_decls).meta in + ctx_get meta (TraitParentClauseId (id, clause)) ctx let ctx_get_trait_item_clause (id : trait_decl_id) (item : string) (clause : trait_clause_id) (ctx : extraction_ctx) : string = - ctx_get (TraitItemClauseId (id, item, clause)) ctx + let meta = (TraitDeclId.Map.find id ctx.trans_trait_decls).meta in + ctx_get meta (TraitItemClauseId (id, item, clause)) ctx -let ctx_get_var (id : VarId.id) (ctx : extraction_ctx) : string = - ctx_get (VarId id) ctx +let ctx_get_var (meta : Meta.meta) (id : VarId.id) (ctx : extraction_ctx) : string = + ctx_get meta (VarId id) ctx -let ctx_get_type_var (id : TypeVarId.id) (ctx : extraction_ctx) : string = - ctx_get (TypeVarId id) ctx +let ctx_get_type_var (meta : Meta.meta) (id : TypeVarId.id) (ctx : extraction_ctx) : string = + ctx_get meta (TypeVarId id) ctx -let ctx_get_const_generic_var (id : ConstGenericVarId.id) (ctx : extraction_ctx) +let ctx_get_const_generic_var (meta : Meta.meta) (id : ConstGenericVarId.id) (ctx : extraction_ctx) : string = - ctx_get (ConstGenericVarId id) ctx + ctx_get meta (ConstGenericVarId id) ctx -let ctx_get_local_trait_clause (id : TraitClauseId.id) (ctx : extraction_ctx) : +let ctx_get_local_trait_clause (meta : Meta.meta) (id : TraitClauseId.id) (ctx : extraction_ctx) : string = - ctx_get (LocalTraitClauseId id) ctx + ctx_get meta (LocalTraitClauseId id) ctx -let ctx_get_field (type_id : type_id) (field_id : FieldId.id) +let ctx_get_field (meta : Meta.meta) (type_id : type_id) (field_id : FieldId.id) (ctx : extraction_ctx) : string = - ctx_get (FieldId (type_id, field_id)) ctx + (* let meta = (TypeDeclId.Map.find type_id ctx.trans_types).meta in TODO : check how to get meta *) + ctx_get meta (FieldId (type_id, field_id)) ctx -let ctx_get_struct (def_id : type_id) (ctx : extraction_ctx) : string = - ctx_get (StructId def_id) ctx +let ctx_get_struct (meta : Meta.meta) (def_id : type_id) (ctx : extraction_ctx) : string = + ctx_get meta (StructId def_id) ctx -let ctx_get_variant (def_id : type_id) (variant_id : VariantId.id) +let ctx_get_variant (meta : Meta.meta) (def_id : type_id) (variant_id : VariantId.id) (ctx : extraction_ctx) : string = - ctx_get (VariantId (def_id, variant_id)) ctx + ctx_get meta (VariantId (def_id, variant_id)) ctx -let ctx_get_decreases_proof (def_id : A.FunDeclId.id) +let ctx_get_decreases_proof (meta : Meta.meta) (def_id : A.FunDeclId.id) (loop_id : LoopId.id option) (ctx : extraction_ctx) : string = - ctx_get (DecreasesProofId (FRegular def_id, loop_id)) ctx + ctx_get meta (DecreasesProofId (FRegular def_id, loop_id)) ctx -let ctx_get_termination_measure (def_id : A.FunDeclId.id) +let ctx_get_termination_measure (meta : Meta.meta) (def_id : A.FunDeclId.id) (loop_id : LoopId.id option) (ctx : extraction_ctx) : string = - ctx_get (TerminationMeasureId (FRegular def_id, loop_id)) ctx + ctx_get meta (TerminationMeasureId (FRegular def_id, loop_id)) ctx (** Small helper to compute the name of a unary operation *) let unop_name (unop : unop) : string = @@ -1161,7 +1171,7 @@ let initialize_names_maps () : names_maps = Remark: can return [None] for some backends like HOL4. *) -let type_decl_kind_to_qualif (kind : decl_kind) +let type_decl_kind_to_qualif (meta : Meta.meta) (kind : decl_kind) (type_kind : type_decl_kind option) : string option = match !backend with | FStar -> ( @@ -1189,11 +1199,11 @@ let type_decl_kind_to_qualif (kind : decl_kind) (* This is for traits *) Some "Record" | _ -> - raise - (Failure + craise + meta ("Unexpected: (" ^ show_decl_kind kind ^ ", " ^ Print.option_to_string show_type_decl_kind type_kind - ^ ")"))) + ^ ")")) | Lean -> ( match kind with | SingleNonRec -> ( @@ -1247,17 +1257,17 @@ let fun_decl_kind_to_qualif (kind : decl_kind) : string option = TODO: move inside the formatter? *) -let type_keyword () = +let type_keyword (meta : Meta.meta) = match !backend with | FStar -> "Type0" | Coq | Lean -> "Type" - | HOL4 -> raise (Failure "Unexpected") + | HOL4 -> craise meta "Unexpected" (** Helper *) -let name_last_elem_as_ident (n : llbc_name) : string = +let name_last_elem_as_ident (meta : Meta.meta) (n : llbc_name) : string = match Collections.List.last n with | PeIdent (s, _) -> s - | PeImpl _ -> raise (Failure "Unexpected") + | PeImpl _ -> craise meta "Unexpected" (** Helper @@ -1266,35 +1276,28 @@ let name_last_elem_as_ident (n : llbc_name) : string = we remove it. We ignore disambiguators (there may be collisions, but we check if there are). *) -let ctx_prepare_name (ctx : extraction_ctx) (name : llbc_name) : llbc_name = +let ctx_prepare_name (meta : Meta.meta) (ctx : extraction_ctx) (name : llbc_name) : llbc_name = (* Rmk.: initially we only filtered the disambiguators equal to 0 *) match name with | (PeIdent (crate, _) as id) :: name -> if crate = ctx.crate.name then name else id :: name | _ -> - raise - (Failure + craise + meta ("Unexpected name shape: " ^ TranslateCore.name_to_string ctx.trans_ctx name)) (** Helper *) -let ctx_compute_simple_name (ctx : extraction_ctx) (name : llbc_name) : - string list = - (* Rmk.: initially we only filtered the disambiguators equal to 0 *) - let name = ctx_prepare_name ctx name in - name_to_simple_name ctx.trans_ctx name - -(** Helper *) let ctx_compute_simple_type_name = ctx_compute_simple_name (** Helper *) -let ctx_compute_type_name_no_suffix (ctx : extraction_ctx) (name : llbc_name) : +let ctx_compute_type_name_no_suffix (meta : Meta.meta) (ctx : extraction_ctx) (name : llbc_name) : string = - flatten_name (ctx_compute_simple_type_name ctx name) + flatten_name (ctx_compute_simple_type_name meta ctx name) (** Provided a basename, compute a type name. *) -let ctx_compute_type_name (ctx : extraction_ctx) (name : llbc_name) = - let name = ctx_compute_type_name_no_suffix ctx name in +let ctx_compute_type_name (meta : Meta.meta) (ctx : extraction_ctx) (name : llbc_name) = + let name = ctx_compute_type_name_no_suffix meta ctx name in match !backend with | FStar -> StringUtils.lowercase_first_letter (name ^ "_t") | Coq | HOL4 -> name ^ "_t" @@ -1311,7 +1314,7 @@ let ctx_compute_type_name (ctx : extraction_ctx) (name : llbc_name) = access then causes trouble because not all provers accept syntax like [x.3] where [x] is a tuple. *) -let ctx_compute_field_name (ctx : extraction_ctx) (def_name : llbc_name) +let ctx_compute_field_name (meta : Meta.meta) (ctx : extraction_ctx) (def_name : llbc_name) (field_id : FieldId.id) (field_name : string option) : string = let field_name_s = match field_name with @@ -1326,7 +1329,7 @@ let ctx_compute_field_name (ctx : extraction_ctx) (def_name : llbc_name) else field_name_s else let def_name = - ctx_compute_type_name_no_suffix ctx def_name ^ "_" ^ field_name_s + ctx_compute_type_name_no_suffix meta ctx def_name ^ "_" ^ field_name_s in match !backend with | Lean | HOL4 -> def_name @@ -1336,14 +1339,14 @@ let ctx_compute_field_name (ctx : extraction_ctx) (def_name : llbc_name) - type name - variant name *) -let ctx_compute_variant_name (ctx : extraction_ctx) (def_name : llbc_name) +let ctx_compute_variant_name (meta : Meta.meta) (ctx : extraction_ctx) (def_name : llbc_name) (variant : string) : string = match !backend with | FStar | Coq | HOL4 -> let variant = to_camel_case variant in if !variant_concatenate_type_name then StringUtils.capitalize_first_letter - (ctx_compute_type_name_no_suffix ctx def_name ^ "_" ^ variant) + (ctx_compute_type_name_no_suffix meta ctx def_name ^ "_" ^ variant) else variant | Lean -> variant @@ -1358,14 +1361,14 @@ let ctx_compute_variant_name (ctx : extraction_ctx) (def_name : llbc_name) Inputs: - type name *) -let ctx_compute_struct_constructor (ctx : extraction_ctx) (basename : llbc_name) +let ctx_compute_struct_constructor (meta : Meta.meta) (ctx : extraction_ctx) (basename : llbc_name) : string = - let tname = ctx_compute_type_name ctx basename in + let tname = ctx_compute_type_name meta ctx basename in ExtractBuiltin.mk_struct_constructor tname -let ctx_compute_fun_name_no_suffix (ctx : extraction_ctx) (fname : llbc_name) : +let ctx_compute_fun_name_no_suffix (meta : Meta.meta) (ctx : extraction_ctx) (fname : llbc_name) : string = - let fname = ctx_compute_simple_name ctx fname in + let fname = ctx_compute_simple_name meta ctx fname in (* TODO: don't convert to snake case for Coq, HOL4, F* *) let fname = flatten_name fname in match !backend with @@ -1373,10 +1376,10 @@ let ctx_compute_fun_name_no_suffix (ctx : extraction_ctx) (fname : llbc_name) : | Lean -> fname (** Provided a basename, compute the name of a global declaration. *) -let ctx_compute_global_name (ctx : extraction_ctx) (name : llbc_name) : string = +let ctx_compute_global_name (meta : Meta.meta) (ctx : extraction_ctx) (name : llbc_name) : string = match !Config.backend with | Coq | FStar | HOL4 -> - let parts = List.map to_snake_case (ctx_compute_simple_name ctx name) in + let parts = List.map to_snake_case (ctx_compute_simple_name meta ctx name) in String.concat "_" parts | Lean -> flatten_name (ctx_compute_simple_name ctx name) @@ -1395,7 +1398,7 @@ let default_fun_loop_suffix (num_loops : int) (loop_id : LoopId.id option) : (** A helper function: generates a function suffix. TODO: move all those helpers. *) -let default_fun_suffix (num_loops : int) (loop_id : LoopId.id option) : string = +let default_fun_suffix (meta : Meta.meta) (num_loops : int) (loop_id : LoopId.id option) : string = (* We only generate a suffix for the functions we generate from the loops *) default_fun_loop_suffix num_loops loop_id @@ -1409,17 +1412,17 @@ let default_fun_suffix (num_loops : int) (loop_id : LoopId.id option) : string = - loop id (if pertinent) TODO: use the fun id for the assumed functions. *) -let ctx_compute_fun_name (ctx : extraction_ctx) (fname : llbc_name) +let ctx_compute_fun_name (meta : Meta.meta) (ctx : extraction_ctx) (fname : llbc_name) (num_loops : int) (loop_id : LoopId.id option) : string = - let fname = ctx_compute_fun_name_no_suffix ctx fname in + let fname = ctx_compute_fun_name_no_suffix meta ctx fname in (* Compute the suffix *) - let suffix = default_fun_suffix num_loops loop_id in + let suffix = default_fun_suffix meta num_loops loop_id in (* Concatenate *) fname ^ suffix let ctx_compute_trait_decl_name (ctx : extraction_ctx) (trait_decl : trait_decl) : string = - ctx_compute_type_name ctx trait_decl.llbc_name + ctx_compute_type_name trait_decl.meta ctx trait_decl.llbc_name let ctx_compute_trait_impl_name (ctx : extraction_ctx) (trait_decl : trait_decl) (trait_impl : trait_impl) : string = @@ -1569,17 +1572,17 @@ let ctx_compute_trait_type_clause_name (ctx : extraction_ctx) the same purpose as in [llbc_name]. - loop identifier, if this is for a loop *) -let ctx_compute_termination_measure_name (ctx : extraction_ctx) +let ctx_compute_termination_measure_name (meta : Meta.meta) (ctx : extraction_ctx) (_fid : A.FunDeclId.id) (fname : llbc_name) (num_loops : int) (loop_id : LoopId.id option) : string = - let fname = ctx_compute_fun_name_no_suffix ctx fname in + let fname = ctx_compute_fun_name_no_suffix meta ctx fname in let lp_suffix = default_fun_loop_suffix num_loops loop_id in (* Compute the suffix *) let suffix = match !Config.backend with | FStar -> "_decreases" | Lean -> "_terminates" - | Coq | HOL4 -> raise (Failure "Unexpected") + | Coq | HOL4 -> craise meta "Unexpected" in (* Concatenate *) fname ^ lp_suffix ^ suffix @@ -1598,16 +1601,16 @@ let ctx_compute_termination_measure_name (ctx : extraction_ctx) the same purpose as in [llbc_name]. - loop identifier, if this is for a loop *) -let ctx_compute_decreases_proof_name (ctx : extraction_ctx) +let ctx_compute_decreases_proof_name (meta : Meta.meta) (ctx : extraction_ctx) (_fid : A.FunDeclId.id) (fname : llbc_name) (num_loops : int) (loop_id : LoopId.id option) : string = - let fname = ctx_compute_fun_name_no_suffix ctx fname in + let fname = ctx_compute_fun_name_no_suffix meta ctx fname in let lp_suffix = default_fun_loop_suffix num_loops loop_id in (* Compute the suffix *) let suffix = match !Config.backend with | Lean -> "_decreases" - | FStar | Coq | HOL4 -> raise (Failure "Unexpected") + | FStar | Coq | HOL4 -> craise meta "Unexpected" in (* Concatenate *) fname ^ lp_suffix ^ suffix @@ -1625,7 +1628,7 @@ let ctx_compute_decreases_proof_name (ctx : extraction_ctx) if necessary to prevent name clashes: the burden of name clashes checks is thus on the caller's side. *) -let ctx_compute_var_basename (ctx : extraction_ctx) (basename : string option) +let ctx_compute_var_basename (meta : Meta.meta) (ctx : extraction_ctx) (basename : string option) (ty : ty) : string = (* Small helper to derive var names from ADT type names. @@ -1638,7 +1641,7 @@ let ctx_compute_var_basename (ctx : extraction_ctx) (basename : string option) let cl = to_snake_case name in let cl = String.split_on_char '_' cl in let cl = List.filter (fun s -> String.length s > 0) cl in - assert (List.length cl > 0); + cassert (List.length cl > 0) meta "T"; let cl = List.map (fun s -> s.[0]) cl in StringUtils.string_of_chars cl in @@ -1738,82 +1741,82 @@ let name_append_index (basename : string) (i : int) : string = basename ^ string_of_int i (** Generate a unique type variable name and add it to the context *) -let ctx_add_type_var (basename : string) (id : TypeVarId.id) +let ctx_add_type_var (meta : Meta.meta) (basename : string) (id : TypeVarId.id) (ctx : extraction_ctx) : extraction_ctx * string = let name = ctx_compute_type_var_basename ctx basename in let name = basename_to_unique ctx.names_maps.names_map.names_set name_append_index name in - let ctx = ctx_add (TypeVarId id) name ctx in + let ctx = ctx_add meta (TypeVarId id) name ctx in (ctx, name) (** Generate a unique const generic variable name and add it to the context *) -let ctx_add_const_generic_var (basename : string) (id : ConstGenericVarId.id) +let ctx_add_const_generic_var (meta : Meta.meta) (basename : string) (id : ConstGenericVarId.id) (ctx : extraction_ctx) : extraction_ctx * string = let name = ctx_compute_const_generic_var_basename ctx basename in let name = basename_to_unique ctx.names_maps.names_map.names_set name_append_index name in - let ctx = ctx_add (ConstGenericVarId id) name ctx in + let ctx = ctx_add meta (ConstGenericVarId id) name ctx in (ctx, name) (** See {!ctx_add_type_var} *) -let ctx_add_type_vars (vars : (string * TypeVarId.id) list) +let ctx_add_type_vars (meta : Meta.meta) (vars : (string * TypeVarId.id) list) (ctx : extraction_ctx) : extraction_ctx * string list = List.fold_left_map - (fun ctx (name, id) -> ctx_add_type_var name id ctx) + (fun ctx (name, id) -> ctx_add_type_var meta name id ctx) ctx vars (** Generate a unique variable name and add it to the context *) -let ctx_add_var (basename : string) (id : VarId.id) (ctx : extraction_ctx) : +let ctx_add_var (meta : Meta.meta) (basename : string) (id : VarId.id) (ctx : extraction_ctx) : extraction_ctx * string = let name = basename_to_unique ctx.names_maps.names_map.names_set name_append_index basename in - let ctx = ctx_add (VarId id) name ctx in + let ctx = ctx_add meta (VarId id) name ctx in (ctx, name) (** Generate a unique variable name for the trait self clause and add it to the context *) -let ctx_add_trait_self_clause (ctx : extraction_ctx) : extraction_ctx * string = +let ctx_add_trait_self_clause (meta : Meta.meta) (ctx : extraction_ctx) : extraction_ctx * string = let basename = trait_self_clause_basename in let name = basename_to_unique ctx.names_maps.names_map.names_set name_append_index basename in - let ctx = ctx_add TraitSelfClauseId name ctx in + let ctx = ctx_add meta TraitSelfClauseId name ctx in (ctx, name) (** Generate a unique trait clause name and add it to the context *) -let ctx_add_local_trait_clause (basename : string) (id : TraitClauseId.id) +let ctx_add_local_trait_clause (meta : Meta.meta) (basename : string) (id : TraitClauseId.id) (ctx : extraction_ctx) : extraction_ctx * string = let name = basename_to_unique ctx.names_maps.names_map.names_set name_append_index basename in - let ctx = ctx_add (LocalTraitClauseId id) name ctx in + let ctx = ctx_add meta (LocalTraitClauseId id) name ctx in (ctx, name) (** See {!ctx_add_var} *) -let ctx_add_vars (vars : var list) (ctx : extraction_ctx) : +let ctx_add_vars (meta : Meta.meta) (vars : var list) (ctx : extraction_ctx) : extraction_ctx * string list = List.fold_left_map (fun ctx (v : var) -> - let name = ctx_compute_var_basename ctx v.basename v.ty in - ctx_add_var name v.id ctx) + let name = ctx_compute_var_basename meta ctx v.basename v.ty in + ctx_add_var meta name v.id ctx) ctx vars -let ctx_add_type_params (vars : type_var list) (ctx : extraction_ctx) : +let ctx_add_type_params (meta : Meta.meta) (vars : type_var list) (ctx : extraction_ctx) : extraction_ctx * string list = List.fold_left_map - (fun ctx (var : type_var) -> ctx_add_type_var var.name var.index ctx) + (fun ctx (var : type_var) -> ctx_add_type_var meta var.name var.index ctx) ctx vars -let ctx_add_const_generic_params (vars : const_generic_var list) +let ctx_add_const_generic_params (meta : Meta.meta) (vars : const_generic_var list) (ctx : extraction_ctx) : extraction_ctx * string list = List.fold_left_map (fun ctx (var : const_generic_var) -> - ctx_add_const_generic_var var.name var.index ctx) + ctx_add_const_generic_var meta var.name var.index ctx) ctx vars (** Returns the lists of names for: @@ -1825,7 +1828,7 @@ let ctx_add_const_generic_params (vars : const_generic_var list) pretty names for the trait clauses. See {!ctx_compute_trait_clause_name} for additional information. *) -let ctx_add_local_trait_clauses (current_def_name : Types.name) +let ctx_add_local_trait_clauses (meta : Meta.meta) (current_def_name : Types.name) (llbc_generics : Types.generic_params) (clauses : trait_clause list) (ctx : extraction_ctx) : extraction_ctx * string list = List.fold_left_map @@ -1834,7 +1837,7 @@ let ctx_add_local_trait_clauses (current_def_name : Types.name) ctx_compute_trait_clause_basename ctx current_def_name llbc_generics c.clause_id in - ctx_add_local_trait_clause basename c.clause_id ctx) + ctx_add_local_trait_clause meta basename c.clause_id ctx) ctx clauses (** Returns the lists of names for: @@ -1846,33 +1849,33 @@ let ctx_add_local_trait_clauses (current_def_name : Types.name) pretty names for the trait clauses. See {!ctx_compute_trait_clause_name} for additional information. *) -let ctx_add_generic_params (current_def_name : Types.name) +let ctx_add_generic_params (meta : Meta.meta) (current_def_name : Types.name) (llbc_generics : Types.generic_params) (generics : generic_params) (ctx : extraction_ctx) : extraction_ctx * string list * string list * string list = let { types; const_generics; trait_clauses } = generics in - let ctx, tys = ctx_add_type_params types ctx in - let ctx, cgs = ctx_add_const_generic_params const_generics ctx in + let ctx, tys = ctx_add_type_params meta types ctx in + let ctx, cgs = ctx_add_const_generic_params meta const_generics ctx in let ctx, tcs = - ctx_add_local_trait_clauses current_def_name llbc_generics trait_clauses ctx + ctx_add_local_trait_clauses meta current_def_name llbc_generics trait_clauses ctx in (ctx, tys, cgs, tcs) let ctx_add_decreases_proof (def : fun_decl) (ctx : extraction_ctx) : extraction_ctx = let name = - ctx_compute_decreases_proof_name ctx def.def_id def.llbc_name def.num_loops + ctx_compute_decreases_proof_name def.meta ctx def.def_id def.llbc_name def.num_loops def.loop_id in - ctx_add (DecreasesProofId (FRegular def.def_id, def.loop_id)) name ctx + ctx_add def.meta (DecreasesProofId (FRegular def.def_id, def.loop_id)) name ctx let ctx_add_termination_measure (def : fun_decl) (ctx : extraction_ctx) : extraction_ctx = let name = - ctx_compute_termination_measure_name ctx def.def_id def.llbc_name + ctx_compute_termination_measure_name def.meta ctx def.def_id def.llbc_name def.num_loops def.loop_id in - ctx_add (TerminationMeasureId (FRegular def.def_id, def.loop_id)) name ctx + ctx_add def.meta (TerminationMeasureId (FRegular def.def_id, def.loop_id)) name ctx let ctx_add_global_decl_and_body (def : A.global_decl) (ctx : extraction_ctx) : extraction_ctx = @@ -1885,7 +1888,7 @@ let ctx_add_global_decl_and_body (def : A.global_decl) (ctx : extraction_ctx) : match match_name_find_opt ctx.trans_ctx def.name builtin_globals_map with | Some name -> (* Yes: register the custom binding *) - ctx_add decl name ctx + ctx_add def.meta decl name ctx | None -> (* Not the case: "standard" registration *) let name = ctx_compute_global_name ctx def.name in @@ -1903,20 +1906,20 @@ let ctx_add_global_decl_and_body (def : A.global_decl) (ctx : extraction_ctx) : let ctx_compute_fun_name (def : fun_decl) (ctx : extraction_ctx) : string = (* Add the function name *) - ctx_compute_fun_name ctx def.llbc_name def.num_loops def.loop_id + ctx_compute_fun_name def.meta ctx def.llbc_name def.num_loops def.loop_id (* TODO: move to Extract *) let ctx_add_fun_decl (def : fun_decl) (ctx : extraction_ctx) : extraction_ctx = (* Sanity check: the function should not be a global body - those are handled * separately *) - assert (not def.is_global_decl_body); + cassert (not def.is_global_decl_body) def.meta "The function should not be a global body - those are handled separately"; (* Lookup the LLBC def to compute the region group information *) let def_id = def.def_id in (* Add the function name *) let def_name = ctx_compute_fun_name def ctx in let fun_id = (Pure.FunId (FRegular def_id), def.loop_id) in - ctx_add (FunId (FromLlbc fun_id)) def_name ctx + ctx_add def.meta (FunId (FromLlbc fun_id)) def_name ctx let ctx_compute_type_decl_name (ctx : extraction_ctx) (def : type_decl) : string = - ctx_compute_type_name ctx def.llbc_name + ctx_compute_type_name def.meta ctx def.llbc_name diff --git a/compiler/ExtractName.ml b/compiler/ExtractName.ml index 80ed2ca3..9df5b03e 100644 --- a/compiler/ExtractName.ml +++ b/compiler/ExtractName.ml @@ -1,6 +1,7 @@ (** Utilities for extracting names *) open Charon.NameMatcher +open Errors let log = Logging.extract_log let match_with_trait_decl_refs = true @@ -31,7 +32,7 @@ end For impl blocks, we simply use the name of the type (without its arguments) if all the arguments are variables. *) -let pattern_to_extract_name (name : pattern) : string list = +let pattern_to_extract_name ?(meta = None) (name : pattern) : string list = let c = { tgt = TkName } in let all_vars = let check (g : generic_arg) : bool = @@ -71,7 +72,7 @@ let pattern_to_extract_name (name : pattern) : string list = let id = Collections.List.last id in match id with | PIdent (_, _) -> super#visit_PImpl () (EComp [ id ]) - | PImpl _ -> raise (Failure "Unreachable")) + | PImpl _ -> craise_opt_meta meta "Unreachable") | _ -> super#visit_PImpl () ty method! visit_EPrimAdt _ adt g = diff --git a/compiler/ExtractTypes.ml b/compiler/ExtractTypes.ml index bbd5fae4..51ed7f5a 100644 --- a/compiler/ExtractTypes.ml +++ b/compiler/ExtractTypes.ml @@ -4,6 +4,7 @@ open Pure open PureUtils open TranslateCore open Config +open Errors include ExtractBase (** Format a constant value. @@ -14,7 +15,7 @@ include ExtractBase if it is made of an application (ex.: [U32 3]) - the constant value *) -let extract_literal (fmt : F.formatter) (inside : bool) (cv : literal) : unit = +let extract_literal (meta : Meta.meta) (fmt : F.formatter) (inside : bool) (cv : literal) : unit = match cv with | VScalar sv -> ( match !backend with @@ -27,7 +28,7 @@ let extract_literal (fmt : F.formatter) (inside : bool) (cv : literal) : unit = | HOL4 -> F.pp_print_string fmt ("int_to_" ^ int_name sv.int_ty); F.pp_print_space fmt () - | _ -> raise (Failure "Unreachable")); + | _ -> craise meta "Unreachable"); (* We need to add parentheses if the value is negative *) if sv.value >= Z.of_int 0 then F.pp_print_string fmt (Z.to_string sv.value) @@ -40,7 +41,7 @@ let extract_literal (fmt : F.formatter) (inside : bool) (cv : literal) : unit = let iname = String.lowercase_ascii (int_name sv.int_ty) in F.pp_print_string fmt ("#" ^ iname) | HOL4 -> () - | _ -> raise (Failure "Unreachable")); + | _ -> craise meta "Unreachable"); if print_brackets then F.pp_print_string fmt ")") | VBool b -> let b = @@ -80,7 +81,7 @@ let extract_literal (fmt : F.formatter) (inside : bool) (cv : literal) : unit = - unop - argument *) -let extract_unop (extract_expr : bool -> texpression -> unit) +let extract_unop (meta : Meta.meta) (extract_expr : bool -> texpression -> unit) (fmt : F.formatter) (inside : bool) (unop : unop) (arg : texpression) : unit = match unop with @@ -127,7 +128,7 @@ let extract_unop (extract_expr : bool -> texpression -> unit) match !backend with | Coq | FStar -> "scalar_cast" | Lean -> "Scalar.cast" - | HOL4 -> raise (Failure "Unreachable") + | HOL4 -> craise meta "Unreachable" in let src = if !backend <> Lean then Some (integer_type_to_string src) @@ -140,20 +141,20 @@ let extract_unop (extract_expr : bool -> texpression -> unit) match !backend with | Coq | FStar -> "scalar_cast_bool" | Lean -> "Scalar.cast_bool" - | HOL4 -> raise (Failure "Unreachable") + | HOL4 -> craise meta "Unreachable" in let tgt = integer_type_to_string tgt in (cast_str, None, Some tgt) | TInteger _, TBool -> (* This is not allowed by rustc: the way of doing it in Rust is: [x != 0] *) - raise (Failure "Unexpected cast: integer to bool") + craise meta "Unexpected cast: integer to bool" | TBool, TBool -> (* There shouldn't be any cast here. Note that if one writes [b as bool] in Rust (where [b] is a boolean), it gets compiled to [b] (i.e., no cast is introduced). *) - raise (Failure "Unexpected cast: bool to bool") - | _ -> raise (Failure "Unreachable") + craise meta "Unexpected cast: bool to bool" + | _ -> craise meta "Unreachable" in (* Print the name of the function *) F.pp_print_string fmt cast_str; @@ -186,7 +187,7 @@ let extract_unop (extract_expr : bool -> texpression -> unit) - argument 0 - argument 1 *) -let extract_binop (extract_expr : bool -> texpression -> unit) +let extract_binop (meta : Meta.meta) (extract_expr : bool -> texpression -> unit) (fmt : F.formatter) (inside : bool) (binop : E.binop) (int_ty : integer_type) (arg0 : texpression) (arg1 : texpression) : unit = if inside then F.pp_print_string fmt "("; @@ -231,7 +232,7 @@ let extract_binop (extract_expr : bool -> texpression -> unit) constant we need to provide the second implicit type argument *) if binop_is_shift && !backend = FStar && is_const arg1 then ( F.pp_print_space fmt (); - let ty = ty_as_integer arg1.ty in + let ty = ty_as_integer meta arg1.ty in F.pp_print_string fmt ("#" ^ StringUtils.capitalize_first_letter (int_name ty))); F.pp_print_space fmt (); @@ -272,7 +273,7 @@ let start_fun_decl_group (ctx : extraction_ctx) (fmt : F.formatter) if is_single_opaque_fun_decl_group dg then () else let compute_fun_def_name (def : Pure.fun_decl) : string = - ctx_get_local_function def.def_id def.loop_id ctx ^ "_def" + ctx_get_local_function def.meta def.def_id def.loop_id ctx ^ "_def" in let names = List.map compute_fun_def_name dg in (* Add a break before *) @@ -391,15 +392,15 @@ let extract_arrow (fmt : F.formatter) () : unit = if !Config.backend = Lean then F.pp_print_string fmt "→" else F.pp_print_string fmt "->" -let extract_const_generic (ctx : extraction_ctx) (fmt : F.formatter) +let extract_const_generic (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (cg : const_generic) : unit = match cg with | CgGlobal id -> - let s = ctx_get_global id ctx in + let s = ctx_get_global meta id ctx in F.pp_print_string fmt s - | CgValue v -> extract_literal fmt inside v + | CgValue v -> extract_literal meta fmt inside v | CgVar id -> - let s = ctx_get_const_generic_var id ctx in + let s = ctx_get_const_generic_var meta id ctx in F.pp_print_string fmt s let extract_literal_type (_ctx : extraction_ctx) (fmt : F.formatter) @@ -429,9 +430,9 @@ let extract_literal_type (_ctx : extraction_ctx) (fmt : F.formatter) End ]} *) -let rec extract_ty (ctx : extraction_ctx) (fmt : F.formatter) +let rec extract_ty (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (no_params_tys : TypeDeclId.Set.t) (inside : bool) (ty : ty) : unit = - let extract_rec = extract_ty ctx fmt no_params_tys in + let extract_rec = extract_ty meta ctx fmt no_params_tys in match ty with | TAdt (type_id, generics) -> ( let has_params = generics <> empty_generic_args in @@ -469,7 +470,7 @@ let rec extract_ty (ctx : extraction_ctx) (fmt : F.formatter) if print_paren then F.pp_print_string fmt "("; (* TODO: for now, only the opaque *functions* are extracted in the opaque module. The opaque *types* are assumed. *) - F.pp_print_string fmt (ctx_get_type type_id ctx); + F.pp_print_string fmt (ctx_get_type meta type_id ctx); (* We might need to filter the type arguments, if the type is builtin (for instance, we filter the global allocator type argument for `Vec`). *) @@ -490,7 +491,7 @@ let rec extract_ty (ctx : extraction_ctx) (fmt : F.formatter) { generics with types }) | _ -> generics in - extract_generic_args ctx fmt no_params_tys generics; + extract_generic_args meta ctx fmt no_params_tys generics; if print_paren then F.pp_print_string fmt ")" | HOL4 -> let { types; const_generics; trait_refs } = generics in @@ -500,7 +501,7 @@ let rec extract_ty (ctx : extraction_ctx) (fmt : F.formatter) match type_id with | TAdtId id -> not (TypeDeclId.Set.mem id no_params_tys) | TAssumed _ -> true - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" in if types <> [] && print_tys then ( let print_paren = List.length types > 1 in @@ -512,13 +513,13 @@ let rec extract_ty (ctx : extraction_ctx) (fmt : F.formatter) (extract_rec true) types; if print_paren then F.pp_print_string fmt ")"; F.pp_print_space fmt ()); - F.pp_print_string fmt (ctx_get_type type_id ctx); + F.pp_print_string fmt (ctx_get_type meta type_id ctx); if trait_refs <> [] then ( F.pp_print_space fmt (); Collections.List.iter_link (F.pp_print_space fmt) - (extract_trait_ref ctx fmt no_params_tys true) + (extract_trait_ref meta ctx fmt no_params_tys true) trait_refs))) - | TVar vid -> F.pp_print_string fmt (ctx_get_type_var vid ctx) + | TVar vid -> F.pp_print_string fmt (ctx_get_type_var meta vid ctx) | TLiteral lty -> extract_literal_type ctx fmt lty | TArrow (arg_ty, ret_ty) -> if inside then F.pp_print_string fmt "("; @@ -529,7 +530,7 @@ let rec extract_ty (ctx : extraction_ctx) (fmt : F.formatter) extract_rec false ret_ty; if inside then F.pp_print_string fmt ")" | TTraitType (trait_ref, type_name) -> ( - if !parameterize_trait_types then raise (Failure "Unimplemented") + if !parameterize_trait_types then craise meta "Unimplemented" else let type_name = ctx_get_trait_type trait_ref.trait_decl_ref.trait_decl_id type_name @@ -548,16 +549,16 @@ let rec extract_ty (ctx : extraction_ctx) (fmt : F.formatter) match trait_ref.trait_id with | Self -> assert (trait_ref.generics = empty_generic_args); - extract_trait_instance_id_with_dot ctx fmt no_params_tys false + extract_trait_instance_id_with_dot meta ctx fmt no_params_tys false trait_ref.trait_id; F.pp_print_string fmt type_name | _ -> (* HOL4 doesn't have 1st class types *) assert (!backend <> HOL4); - extract_trait_ref ctx fmt no_params_tys false trait_ref; + extract_trait_ref meta ctx fmt no_params_tys false trait_ref; F.pp_print_string fmt ("." ^ add_brackets type_name)) -and extract_trait_ref (ctx : extraction_ctx) (fmt : F.formatter) +and extract_trait_ref (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (no_params_tys : TypeDeclId.Set.t) (inside : bool) (tr : trait_ref) : unit = let use_brackets = tr.generics <> empty_generic_args && inside in if use_brackets then F.pp_print_string fmt "("; @@ -578,11 +579,11 @@ and extract_trait_ref (ctx : extraction_ctx) (fmt : F.formatter) { tr.generics with types }) | _ -> tr.generics in - extract_trait_instance_id ctx fmt no_params_tys inside tr.trait_id; - extract_generic_args ctx fmt no_params_tys generics; + extract_trait_instance_id meta ctx fmt no_params_tys inside tr.trait_id; + extract_generic_args meta ctx fmt no_params_tys generics; if use_brackets then F.pp_print_string fmt ")" -and extract_trait_decl_ref (ctx : extraction_ctx) (fmt : F.formatter) +and extract_trait_decl_ref (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (no_params_tys : TypeDeclId.Set.t) (inside : bool) (tr : trait_decl_ref) : unit = let use_brackets = tr.decl_generics <> empty_generic_args && inside in @@ -592,28 +593,28 @@ and extract_trait_decl_ref (ctx : extraction_ctx) (fmt : F.formatter) (* There is something subtle here: the trait obligations for the implemented trait are put inside the parent clauses, so we must ignore them here *) let generics = { tr.decl_generics with trait_refs = [] } in - extract_generic_args ctx fmt no_params_tys generics; + extract_generic_args meta ctx fmt no_params_tys generics; if use_brackets then F.pp_print_string fmt ")" -and extract_generic_args (ctx : extraction_ctx) (fmt : F.formatter) +and extract_generic_args (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (no_params_tys : TypeDeclId.Set.t) (generics : generic_args) : unit = let { types; const_generics; trait_refs } = generics in if !backend <> HOL4 then ( if types <> [] then ( F.pp_print_space fmt (); Collections.List.iter_link (F.pp_print_space fmt) - (extract_ty ctx fmt no_params_tys true) + (extract_ty meta ctx fmt no_params_tys true) types); if const_generics <> [] then ( assert (!backend <> HOL4); F.pp_print_space fmt (); Collections.List.iter_link (F.pp_print_space fmt) - (extract_const_generic ctx fmt true) + (extract_const_generic meta ctx fmt true) const_generics)); if trait_refs <> [] then ( F.pp_print_space fmt (); Collections.List.iter_link (F.pp_print_space fmt) - (extract_trait_ref ctx fmt no_params_tys true) + (extract_trait_ref meta ctx fmt no_params_tys true) trait_refs) (** We sometimes need to ignore references to `Self` when generating the @@ -622,7 +623,7 @@ and extract_generic_args (ctx : extraction_ctx) (fmt : F.formatter) id (e.g., `<Self as Foo>::foo` - note that in the extracted code, the projections are often written with a dot '.'). *) -and extract_trait_instance_id_with_dot (ctx : extraction_ctx) +and extract_trait_instance_id_with_dot (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (no_params_tys : TypeDeclId.Set.t) (inside : bool) (id : trait_instance_id) : unit = match id with @@ -641,7 +642,7 @@ and extract_trait_instance_id_with_dot (ctx : extraction_ctx) *) if ctx.is_provided_method then (* Provided method: use the trait self clause *) - let self_clause = ctx_get_trait_self_clause ctx in + let self_clause = ctx_get_trait_self_clause meta ctx in F.pp_print_string fmt (self_clause ^ ".") else (* Declaration: nothing to print, we will directly refer to @@ -649,10 +650,10 @@ and extract_trait_instance_id_with_dot (ctx : extraction_ctx) () | _ -> (* Other cases *) - extract_trait_instance_id ctx fmt no_params_tys inside id; + extract_trait_instance_id meta ctx fmt no_params_tys inside id; F.pp_print_string fmt "." -and extract_trait_instance_id (ctx : extraction_ctx) (fmt : F.formatter) +and extract_trait_instance_id (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (no_params_tys : TypeDeclId.Set.t) (inside : bool) (id : trait_instance_id) : unit = let add_brackets (s : string) = if !backend = Coq then "(" ^ s ^ ")" else s in @@ -661,29 +662,29 @@ and extract_trait_instance_id (ctx : extraction_ctx) (fmt : F.formatter) (* This has a specific treatment depending on the item we're extracting (associated type, etc.). We should have caught this elsewhere. *) if !Config.fail_hard then - raise (Failure "Unexpected occurrence of `Self`") + craise meta "Unexpected occurrence of `Self`" else F.pp_print_string fmt "ERROR(\"Unexpected Self\")" | TraitImpl id -> let name = ctx_get_trait_impl id ctx in F.pp_print_string fmt name | Clause id -> - let name = ctx_get_local_trait_clause id ctx in + let name = ctx_get_local_trait_clause meta id ctx in F.pp_print_string fmt name | ParentClause (inst_id, decl_id, clause_id) -> (* Use the trait decl id to lookup the name *) let name = ctx_get_trait_parent_clause decl_id clause_id ctx in - extract_trait_instance_id_with_dot ctx fmt no_params_tys true inst_id; + extract_trait_instance_id_with_dot meta ctx fmt no_params_tys true inst_id; F.pp_print_string fmt (add_brackets name) | ItemClause (inst_id, decl_id, item_name, clause_id) -> (* Use the trait decl id to lookup the name *) let name = ctx_get_trait_item_clause decl_id item_name clause_id ctx in - extract_trait_instance_id_with_dot ctx fmt no_params_tys true inst_id; + extract_trait_instance_id_with_dot meta ctx fmt no_params_tys true inst_id; F.pp_print_string fmt (add_brackets name) | TraitRef trait_ref -> - extract_trait_ref ctx fmt no_params_tys inside trait_ref + extract_trait_ref meta ctx fmt no_params_tys inside trait_ref | UnknownTrait _ -> (* This is an error case *) - raise (Failure "Unexpected") + craise meta "Unexpected" (** Compute the names for all the top-level identifiers used in a type definition (type name, variant names, field names, etc. but not type @@ -713,10 +714,10 @@ let extract_type_decl_register_names (ctx : extraction_ctx) (def : type_decl) : (* Compute and register the type def name *) let def_name = match info with - | None -> ctx_compute_type_name ctx def.llbc_name + | None -> ctx_compute_type_name def.meta ctx def.llbc_name | Some info -> info.extract_name in - let ctx = ctx_add (TypeId (TAdtId def.def_id)) def_name ctx in + let ctx = ctx_add def.meta (TypeId (TAdtId def.def_id)) def_name ctx in (* Compute and register: * - the variant names, if this is an enumeration * - the field names, if this is a structure @@ -738,12 +739,12 @@ let extract_type_decl_register_names (ctx : extraction_ctx) (def : type_decl) : FieldId.mapi (fun fid (field : field) -> ( fid, - ctx_compute_field_name ctx def.llbc_name fid + ctx_compute_field_name def.meta ctx def.llbc_name fid field.field_name )) fields in let cons_name = - ctx_compute_struct_constructor ctx def.llbc_name + ctx_compute_struct_constructor def.meta ctx def.llbc_name in (field_names, cons_name) | Some { body_info = Some (Struct (cons_name, field_names)); _ } -> @@ -760,20 +761,20 @@ let extract_type_decl_register_names (ctx : extraction_ctx) (def : type_decl) : in (field_names, cons_name) | Some info -> - raise - (Failure + craise + def.meta ("Invalid builtin information: " - ^ show_builtin_type_info info)) + ^ show_builtin_type_info info) in (* Add the fields *) let ctx = List.fold_left (fun ctx (fid, name) -> - ctx_add (FieldId (TAdtId def.def_id, fid)) name ctx) + ctx_add def.meta (FieldId (TAdtId def.def_id, fid)) name ctx) ctx field_names in (* Add the constructor name *) - ctx_add (StructId (TAdtId def.def_id)) cons_name ctx + ctx_add def.meta (StructId (TAdtId def.def_id)) cons_name ctx | Enum variants -> let variant_names = match info with @@ -781,14 +782,14 @@ let extract_type_decl_register_names (ctx : extraction_ctx) (def : type_decl) : VariantId.mapi (fun variant_id (variant : variant) -> let name = - ctx_compute_variant_name ctx def.llbc_name + ctx_compute_variant_name def.meta ctx def.llbc_name variant.variant_name in (* Add the type name prefix for Lean *) let name = if !Config.backend = Lean then let type_name = - ctx_compute_type_name ctx def.llbc_name + ctx_compute_type_name def.meta ctx def.llbc_name in type_name ^ "." ^ name else name @@ -808,11 +809,11 @@ let extract_type_decl_register_names (ctx : extraction_ctx) (def : type_decl) : (fun variant_id (variant : variant) -> (variant_id, StringMap.find variant.variant_name variant_map)) variants - | _ -> raise (Failure "Invalid builtin information") + | _ -> craise def.meta "Invalid builtin information" in List.fold_left (fun ctx (vid, vname) -> - ctx_add (VariantId (TAdtId def.def_id, vid)) vname ctx) + ctx_add def.meta (VariantId (TAdtId def.def_id, vid)) vname ctx) ctx variant_names | Opaque -> (* Nothing to do *) @@ -822,7 +823,7 @@ let extract_type_decl_register_names (ctx : extraction_ctx) (def : type_decl) : ctx (** Print the variants *) -let extract_type_decl_variant (ctx : extraction_ctx) (fmt : F.formatter) +let extract_type_decl_variant (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (type_decl_group : TypeDeclId.Set.t) (type_name : string) (type_params : string list) (cg_params : string list) (cons_name : string) (fields : field list) : unit = @@ -851,9 +852,9 @@ let extract_type_decl_variant (ctx : extraction_ctx) (fmt : F.formatter) | Some field_name -> let var_id = VarId.of_int (FieldId.to_int fid) in let field_name = - ctx_compute_var_basename ctx (Some field_name) f.field_ty + ctx_compute_var_basename meta ctx (Some field_name) f.field_ty in - let ctx, field_name = ctx_add_var field_name var_id ctx in + let ctx, field_name = ctx_add_var meta field_name var_id ctx in F.pp_print_string fmt (field_name ^ " :"); F.pp_print_space fmt (); ctx) @@ -861,7 +862,7 @@ let extract_type_decl_variant (ctx : extraction_ctx) (fmt : F.formatter) in (* Print the field type *) let inside = !backend = HOL4 in - extract_ty ctx fmt type_decl_group inside f.field_ty; + extract_ty meta ctx fmt type_decl_group inside f.field_ty; (* Print the arrow [->] *) if !backend <> HOL4 then ( F.pp_print_space fmt (); @@ -932,9 +933,9 @@ let extract_type_decl_enum_body (ctx : extraction_ctx) (fmt : F.formatter) let print_variant _variant_id (v : variant) = (* We don't lookup the name, because it may have a prefix for the type id (in the case of Lean) *) - let cons_name = ctx_compute_variant_name ctx def.llbc_name v.variant_name in + let cons_name = ctx_compute_variant_name def.meta ctx def.llbc_name v.variant_name in let fields = v.fields in - extract_type_decl_variant ctx fmt type_decl_group def_name type_params + extract_type_decl_variant def.meta ctx fmt type_decl_group def_name type_params cg_params cons_name fields in (* Print the variants *) @@ -942,7 +943,7 @@ let extract_type_decl_enum_body (ctx : extraction_ctx) (fmt : F.formatter) List.iter (fun (vid, v) -> print_variant vid v) variants (** Extract a struct as a tuple *) -let extract_type_decl_tuple_struct_body (ctx : extraction_ctx) +let extract_type_decl_tuple_struct_body (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (fields : field list) : unit = (* If the type is empty, we need to have a special treatment *) if fields = [] then ( @@ -956,7 +957,7 @@ let extract_type_decl_tuple_struct_body (ctx : extraction_ctx) F.pp_print_string fmt sep) (fun (f : field) -> F.pp_print_space fmt (); - extract_ty ctx fmt TypeDeclId.Set.empty true f.field_ty) + extract_ty meta ctx fmt TypeDeclId.Set.empty true f.field_ty) fields let extract_type_decl_struct_body (ctx : extraction_ctx) (fmt : F.formatter) @@ -1032,7 +1033,7 @@ let extract_type_decl_struct_body (ctx : extraction_ctx) (fmt : F.formatter) (* If Coq: print the constructor name *) (* TODO: remove superfluous test not is_rec below *) if !backend = Coq && not is_rec then ( - F.pp_print_string fmt (ctx_get_struct (TAdtId def.def_id) ctx); + F.pp_print_string fmt (ctx_get_struct def.meta (TAdtId def.def_id) ctx); F.pp_print_string fmt " "); (match !backend with | Lean -> () @@ -1046,14 +1047,14 @@ let extract_type_decl_struct_body (ctx : extraction_ctx) (fmt : F.formatter) | Lean -> F.pp_open_vbox fmt 0); (* Print the fields *) let print_field (field_id : FieldId.id) (f : field) : unit = - let field_name = ctx_get_field (TAdtId def.def_id) field_id ctx in + let field_name = ctx_get_field def.meta (TAdtId def.def_id) field_id ctx in (* Open a box for the field *) F.pp_open_box fmt ctx.indent_incr; F.pp_print_string fmt field_name; F.pp_print_space fmt (); F.pp_print_string fmt ":"; F.pp_print_space fmt (); - extract_ty ctx fmt type_decl_group false f.field_ty; + extract_ty def.meta ctx fmt type_decl_group false f.field_ty; if !backend <> Lean then F.pp_print_string fmt ";"; (* Close the box for the field *) F.pp_close_box fmt () @@ -1081,10 +1082,10 @@ let extract_type_decl_struct_body (ctx : extraction_ctx) (fmt : F.formatter) i.e., instead of generating `inductive Foo := | MkFoo ...` like in Coq we generate `inductive Foo := | mk ... *) let cons_name = - if !backend = Lean then "mk" else ctx_get_struct (TAdtId def.def_id) ctx + if !backend = Lean then "mk" else ctx_get_struct def.meta (TAdtId def.def_id) ctx in - let def_name = ctx_get_local_type def.def_id ctx in - extract_type_decl_variant ctx fmt type_decl_group def_name type_params + let def_name = ctx_get_local_type def.meta def.def_id ctx in + extract_type_decl_variant def.meta ctx fmt type_decl_group def_name type_params cg_params cons_name fields) in () @@ -1129,11 +1130,11 @@ let extract_comment_with_span (ctx : extraction_ctx) (fmt : F.formatter) in extract_comment fmt (sl @ [ span ] @ name) -let extract_trait_clause_type (ctx : extraction_ctx) (fmt : F.formatter) +let extract_trait_clause_type meta (ctx : extraction_ctx) (fmt : F.formatter) (no_params_tys : TypeDeclId.Set.t) (clause : trait_clause) : unit = let trait_name = ctx_get_trait_decl clause.trait_id ctx in F.pp_print_string fmt trait_name; - extract_generic_args ctx fmt no_params_tys clause.generics + extract_generic_args meta ctx fmt no_params_tys clause.generics (** Insert a space, if necessary *) let insert_req_space (fmt : F.formatter) (space : bool ref) : unit = @@ -1148,7 +1149,7 @@ let extract_trait_self_clause (insert_req_space : unit -> unit) (params : string list) : unit = insert_req_space (); F.pp_print_string fmt "("; - let self_clause = ctx_get_trait_self_clause ctx in + let self_clause = ctx_get_trait_self_clause trait_decl.meta ctx in F.pp_print_string fmt self_clause; F.pp_print_space fmt (); F.pp_print_string fmt ":"; @@ -1166,7 +1167,7 @@ let extract_trait_self_clause (insert_req_space : unit -> unit) - [trait_decl]: if [Some], it means we are extracting the generics for a provided method and need to insert a trait self clause (see {!TraitSelfClauseId}). *) -let extract_generic_params (ctx : extraction_ctx) (fmt : F.formatter) +let extract_generic_params (meta : Meta.meta) (ctx : extraction_ctx) (fmt : F.formatter) (no_params_tys : TypeDeclId.Set.t) ?(use_forall = false) ?(use_forall_use_sep = true) ?(use_arrows = false) ?(as_implicits : bool = false) ?(space : bool ref option = None) @@ -1219,7 +1220,7 @@ let extract_generic_params (ctx : extraction_ctx) (fmt : F.formatter) type_params; F.pp_print_string fmt ":"; F.pp_print_space fmt (); - F.pp_print_string fmt (type_keyword ()); + F.pp_print_string fmt (type_keyword meta); (* ) *) right_bracket as_implicits; if use_arrows then ( @@ -1231,7 +1232,7 @@ let extract_generic_params (ctx : extraction_ctx) (fmt : F.formatter) insert_req_space (); (* ( *) left_bracket as_implicits; - let n = ctx_get_const_generic_var var.index ctx in + let n = ctx_get_const_generic_var meta var.index ctx in print_implicit_symbol as_implicits; F.pp_print_string fmt n; F.pp_print_space fmt (); @@ -1250,13 +1251,13 @@ let extract_generic_params (ctx : extraction_ctx) (fmt : F.formatter) insert_req_space (); (* ( *) left_bracket as_implicits; - let n = ctx_get_local_trait_clause clause.clause_id ctx in + let n = ctx_get_local_trait_clause meta clause.clause_id ctx in print_implicit_symbol as_implicits; F.pp_print_string fmt n; F.pp_print_space fmt (); F.pp_print_string fmt ":"; F.pp_print_space fmt (); - extract_trait_clause_type ctx fmt no_params_tys clause; + extract_trait_clause_type meta ctx fmt no_params_tys clause; (* ) *) right_bracket as_implicits; if use_arrows then ( @@ -1300,10 +1301,10 @@ let extract_generic_params (ctx : extraction_ctx) (fmt : F.formatter) dtype_params; map (fun (cg : const_generic_var) -> - ctx_get_const_generic_var cg.index ctx) + ctx_get_const_generic_var trait_decl.meta cg.index ctx) dcgs; map - (fun c -> ctx_get_local_trait_clause c.clause_id ctx) + (fun c -> ctx_get_local_trait_clause trait_decl.meta c.clause_id ctx) dtrait_clauses; ] in @@ -1350,11 +1351,11 @@ let extract_type_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) let is_opaque_coq = !backend = Coq && is_opaque in let use_forall = is_opaque_coq && def.generics <> empty_generic_params in (* Retrieve the definition name *) - let def_name = ctx_get_local_type def.def_id ctx in + let def_name = ctx_get_local_type def.meta def.def_id ctx in (* Add the type and const generic params - note that we need those bindings only for the * body translation (they are not top-level) *) let ctx_body, type_params, cg_params, trait_clauses = - ctx_add_generic_params def.llbc_name def.llbc_generics def.generics ctx + ctx_add_generic_params def.meta def.llbc_name def.llbc_generics def.generics ctx in (* Add a break before *) if !backend <> HOL4 || not (decl_is_first_from_group kind) then @@ -1387,7 +1388,7 @@ let extract_type_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_space fmt ()) else (); (* > "type TYPE_NAME" *) - let qualif = type_decl_kind_to_qualif kind type_kind in + let qualif = type_decl_kind_to_qualif def.meta kind type_kind in (match qualif with | Some qualif -> F.pp_print_string fmt (qualif ^ " " ^ def_name) | None -> F.pp_print_string fmt def_name); @@ -1395,7 +1396,7 @@ let extract_type_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) support trait clauses *) assert ((cg_params = [] && trait_clauses = []) || !backend <> HOL4); (* Print the generic parameters *) - extract_generic_params ctx_body fmt type_decl_group ~use_forall def.generics + extract_generic_params def.meta ctx_body fmt type_decl_group ~use_forall def.generics type_params cg_params trait_clauses; (* Print the "=" if we extract the body*) if extract_body then ( @@ -1422,21 +1423,21 @@ let extract_type_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_space fmt (); F.pp_print_string fmt ":"); F.pp_print_space fmt (); - F.pp_print_string fmt (type_keyword ())); + F.pp_print_string fmt (type_keyword def.meta)); (* Close the box for "type TYPE_NAME (TYPE_PARAMS) =" *) F.pp_close_box fmt (); (if extract_body then match def.kind with | Struct fields -> if is_tuple_struct then - extract_type_decl_tuple_struct_body ctx_body fmt fields + extract_type_decl_tuple_struct_body def.meta ctx_body fmt fields else extract_type_decl_struct_body ctx_body fmt type_decl_group kind def type_params cg_params fields | Enum variants -> extract_type_decl_enum_body ctx_body fmt type_decl_group def def_name type_params cg_params variants - | Opaque -> raise (Failure "Unreachable")); + | Opaque -> craise def.meta "Unreachable"); (* Add the definition end delimiter *) if !backend = HOL4 && decl_is_not_last_from_group kind then ( F.pp_print_space fmt (); @@ -1460,7 +1461,7 @@ let extract_type_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) let extract_type_decl_hol4_opaque (ctx : extraction_ctx) (fmt : F.formatter) (def : type_decl) : unit = (* Retrieve the definition name *) - let def_name = ctx_get_local_type def.def_id ctx in + let def_name = ctx_get_local_type def.meta def.def_id ctx in (* Generic parameters are unsupported *) assert (def.generics.const_generics = []); (* Trait clauses on type definitions are unsupported *) @@ -1485,7 +1486,7 @@ let extract_type_decl_hol4_opaque (ctx : extraction_ctx) (fmt : F.formatter) let extract_type_decl_hol4_empty_record (ctx : extraction_ctx) (fmt : F.formatter) (def : type_decl) : unit = (* Retrieve the definition name *) - let def_name = ctx_get_local_type def.def_id ctx in + let def_name = ctx_get_local_type def.meta def.def_id ctx in (* Sanity check *) assert (def.generics = empty_generic_params); (* Generate the declaration *) @@ -1578,14 +1579,14 @@ let extract_type_decl_coq_arguments (ctx : extraction_ctx) (fmt : F.formatter) | Struct fields -> let adt_id = TAdtId decl.def_id in (* Generate the instruction for the record constructor *) - let cons_name = ctx_get_struct adt_id ctx in + let cons_name = ctx_get_struct decl.meta adt_id ctx in extract_coq_arguments_instruction ctx fmt cons_name num_params; (* Generate the instruction for the record projectors, if there are *) let is_rec = decl_is_from_rec_group kind in if not is_rec then FieldId.iteri (fun fid _ -> - let cons_name = ctx_get_field adt_id fid ctx in + let cons_name = ctx_get_field decl.meta adt_id fid ctx in extract_coq_arguments_instruction ctx fmt cons_name num_params) fields; (* Add breaks to insert new lines between definitions *) @@ -1594,7 +1595,7 @@ let extract_type_decl_coq_arguments (ctx : extraction_ctx) (fmt : F.formatter) (* Generate the instructions *) VariantId.iteri (fun vid (_ : variant) -> - let cons_name = ctx_get_variant (TAdtId decl.def_id) vid ctx in + let cons_name = ctx_get_variant decl.meta (TAdtId decl.def_id) vid ctx in extract_coq_arguments_instruction ctx fmt cons_name num_params) variants; (* Add breaks to insert new lines between definitions *) @@ -1618,13 +1619,13 @@ let extract_type_decl_record_field_projectors (ctx : extraction_ctx) if is_rec then (* Add the type params *) let ctx, type_params, cg_params, trait_clauses = - ctx_add_generic_params decl.llbc_name decl.llbc_generics decl.generics + ctx_add_generic_params decl.meta decl.llbc_name decl.llbc_generics decl.generics ctx in - let ctx, record_var = ctx_add_var "x" (VarId.of_int 0) ctx in - let ctx, field_var = ctx_add_var "x" (VarId.of_int 1) ctx in - let def_name = ctx_get_local_type decl.def_id ctx in - let cons_name = ctx_get_struct (TAdtId decl.def_id) ctx in + let ctx, record_var = ctx_add_var decl.meta "x" (VarId.of_int 0) ctx in + let ctx, field_var = ctx_add_var decl.meta "x" (VarId.of_int 1) ctx in + let def_name = ctx_get_local_type decl.meta decl.def_id ctx in + let cons_name = ctx_get_struct decl.meta (TAdtId decl.def_id) ctx in let extract_field_proj (field_id : FieldId.id) (_ : field) : unit = F.pp_print_space fmt (); (* Outer box for the projector definition *) @@ -1635,11 +1636,11 @@ let extract_type_decl_record_field_projectors (ctx : extraction_ctx) F.pp_open_hovbox fmt ctx.indent_incr; F.pp_print_string fmt "Definition"; F.pp_print_space fmt (); - let field_name = ctx_get_field (TAdtId decl.def_id) field_id ctx in + let field_name = ctx_get_field decl.meta (TAdtId decl.def_id) field_id ctx in F.pp_print_string fmt field_name; (* Print the generics *) let as_implicits = true in - extract_generic_params ctx fmt TypeDeclId.Set.empty ~as_implicits + extract_generic_params decl.meta ctx fmt TypeDeclId.Set.empty ~as_implicits decl.generics type_params cg_params trait_clauses; (* Print the record parameter *) F.pp_print_space fmt (); @@ -1715,10 +1716,10 @@ let extract_type_decl_record_field_projectors (ctx : extraction_ctx) F.pp_open_hvbox fmt 0; (* Inner box for the projector definition *) F.pp_open_hovbox fmt ctx.indent_incr; - let ctx, record_var = ctx_add_var "x" (VarId.of_int 0) ctx in + let ctx, record_var = ctx_add_var decl.meta "x" (VarId.of_int 0) ctx in F.pp_print_string fmt "Notation"; F.pp_print_space fmt (); - let field_name = ctx_get_field (TAdtId decl.def_id) field_id ctx in + let field_name = ctx_get_field decl.meta (TAdtId decl.def_id) field_id ctx in F.pp_print_string fmt ("\"" ^ record_var ^ " .(" ^ field_name ^ ")\""); F.pp_print_space fmt (); F.pp_print_string fmt ":="; @@ -1769,7 +1770,7 @@ let extract_type_decl_extra_info (ctx : extraction_ctx) (fmt : F.formatter) extract_type_decl_record_field_projectors ctx fmt kind decl) (** Extract the state type declaration. *) -let extract_state_type (fmt : F.formatter) (ctx : extraction_ctx) +let extract_state_type (meta : Meta.meta) (fmt : F.formatter) (ctx : extraction_ctx) (kind : decl_kind) : unit = (* Add a break before *) F.pp_print_break fmt 0 0; @@ -1780,14 +1781,14 @@ let extract_state_type (fmt : F.formatter) (ctx : extraction_ctx) * one line *) F.pp_open_hvbox fmt 0; (* Retrieve the name *) - let state_name = ctx_get_assumed_type TState ctx in + let state_name = ctx_get_assumed_type meta TState ctx in (* The syntax for Lean and Coq is almost identical. *) let print_axiom () = let axiom = match !backend with | Coq -> "Axiom" | Lean -> "axiom" - | FStar | HOL4 -> raise (Failure "Unexpected") + | FStar | HOL4 -> craise meta "Unexpected" in F.pp_print_string fmt axiom; F.pp_print_space fmt (); @@ -1801,7 +1802,7 @@ let extract_state_type (fmt : F.formatter) (ctx : extraction_ctx) (* The kind should be [Assumed] or [Declared] *) (match kind with | SingleNonRec | SingleRec | MutRecFirst | MutRecInner | MutRecLast -> - raise (Failure "Unexpected") + craise meta "Unexpected" | Assumed -> ( match !backend with | FStar -> diff --git a/compiler/FunsAnalysis.ml b/compiler/FunsAnalysis.ml index f6976f23..14185a3d 100644 --- a/compiler/FunsAnalysis.ml +++ b/compiler/FunsAnalysis.ml @@ -9,6 +9,7 @@ open LlbcAst open ExpressionsUtils +open Errors (** Various information about a function. @@ -36,7 +37,6 @@ let analyze_module (m : crate) (funs_map : fun_decl FunDeclId.Map.t) (globals_map : global_decl GlobalDeclId.Map.t) (use_state : bool) : modules_funs_info = let infos = ref FunDeclId.Map.empty in - let register_info (id : FunDeclId.id) (info : fun_info) : unit = assert (not (FunDeclId.Map.mem id !infos)); infos := FunDeclId.Map.add id info !infos @@ -119,7 +119,7 @@ let analyze_module (m : crate) (funs_map : fun_decl FunDeclId.Map.t) method! visit_Call env call = (match call.func with | FnOpMove _ -> - (* Ignoring this: we lookup the called function upon creating + (* Ignoring this: we lookup t he called function upon creating the closure *) () | FnOpRegular func -> ( @@ -145,7 +145,7 @@ let analyze_module (m : crate) (funs_map : fun_decl FunDeclId.Map.t) end in (* Sanity check: global bodies don't contain stateful calls *) - assert ((not f.is_global_decl_body) || not !stateful); + cassert ((not f.is_global_decl_body) || not !stateful) f.meta "Global bodies should not contain stateful calls"; let builtin_info = get_builtin_info f in let has_builtin_info = builtin_info <> None in group_has_builtin_info := !group_has_builtin_info || has_builtin_info; @@ -167,8 +167,8 @@ let analyze_module (m : crate) (funs_map : fun_decl FunDeclId.Map.t) (* We need to know if the declaration group contains a global - note that * groups containing globals contain exactly one declaration *) let is_global_decl_body = List.exists (fun f -> f.is_global_decl_body) d in - assert ((not is_global_decl_body) || List.length d = 1); - assert ((not !group_has_builtin_info) || List.length d = 1); + cassert ((not is_global_decl_body) || List.length d = 1) (List.hd d).meta "The declaration group should containing globals should contain exactly one declaration"; (*TODO recheck how to get meta*) + cassert ((not !group_has_builtin_info) || List.length d = 1) (List.hd d).meta "The declaration group should containing globals should contain exactly one declaration"; (* We ignore on purpose functions that cannot fail and consider they *can* * fail: the result of the analysis is not used yet to adjust the translation * so that the functions which syntactically can't fail don't use an error monad. diff --git a/compiler/Interpreter.ml b/compiler/Interpreter.ml index 961a64a4..a9ca415e 100644 --- a/compiler/Interpreter.ml +++ b/compiler/Interpreter.ml @@ -10,6 +10,7 @@ open Values open LlbcAst open Contexts open SynthesizeSymbolic +open Errors module SA = SymbolicAst (** The local logger *) @@ -67,7 +68,7 @@ let normalize_inst_fun_sig (ctx : eval_ctx) (sg : inst_fun_sig) : inst_fun_sig = clauses (we are not considering a function call, so we don't need to normalize because a trait clause was instantiated with a specific trait ref). *) -let symbolic_instantiate_fun_sig (ctx : eval_ctx) (sg : fun_sig) +let symbolic_instantiate_fun_sig (meta : Meta.meta) (ctx : eval_ctx) (sg : fun_sig) (regions_hierarchy : region_var_groups) (kind : item_kind) : eval_ctx * inst_fun_sig = let tr_self = @@ -83,7 +84,7 @@ let symbolic_instantiate_fun_sig (ctx : eval_ctx) (sg : fun_sig) List.map (fun (v : const_generic_var) -> CgVar v.index) const_generics in (* Annoying that we have to generate this substitution here *) - let r_subst _ = raise (Failure "Unexpected region") in + let r_subst _ = craise meta "Unexpected region" in let ty_subst = Substitute.make_type_subst_from_vars sg.generics.types types in @@ -121,7 +122,7 @@ let symbolic_instantiate_fun_sig (ctx : eval_ctx) (sg : fun_sig) trait_instance_id = match TraitClauseId.Map.find_opt clause_id tr_map with | Some tr -> tr - | None -> raise (Failure "Local trait clause not found") + | None -> craise meta "Local trait clause not found" in let mk_subst tr_map = let tr_subst = mk_tr_subst tr_map in @@ -149,10 +150,10 @@ let symbolic_instantiate_fun_sig (ctx : eval_ctx) (sg : fun_sig) in { regions; types; const_generics; trait_refs } in - let inst_sg = instantiate_fun_sig ctx generics tr_self sg regions_hierarchy in + let inst_sg = instantiate_fun_sig meta ctx generics tr_self sg regions_hierarchy in (* Compute the normalization maps *) let ctx = - AssociatedTypes.ctx_add_norm_trait_types_from_preds ctx + AssociatedTypes.ctx_add_norm_trait_types_from_preds meta ctx inst_sg.trait_type_constraints in (* Normalize the signature *) @@ -173,7 +174,7 @@ let symbolic_instantiate_fun_sig (ctx : eval_ctx) (sg : fun_sig) - the list of symbolic values introduced for the input values - the instantiated function signature *) -let initialize_symbolic_context_for_fun (meta : Meta.meta) (ctx : decls_ctx) (fdef : fun_decl) : +let initialize_symbolic_context_for_fun (ctx : decls_ctx) (fdef : fun_decl) : eval_ctx * symbolic_value list * inst_fun_sig = (* The abstractions are not initialized the same way as for function * calls: they contain *loan* projectors, because they "provide" us @@ -195,22 +196,22 @@ let initialize_symbolic_context_for_fun (meta : Meta.meta) (ctx : decls_ctx) (fd List.map (fun (g : region_var_group) -> g.id) regions_hierarchy in let ctx = - initialize_eval_ctx ctx region_groups sg.generics.types + initialize_eval_ctx fdef.meta ctx region_groups sg.generics.types sg.generics.const_generics in (* Instantiate the signature. This updates the context because we compute at the same time the normalization map for the associated types. *) let ctx, inst_sg = - symbolic_instantiate_fun_sig ctx fdef.signature regions_hierarchy fdef.kind + symbolic_instantiate_fun_sig fdef.meta ctx fdef.signature regions_hierarchy fdef.kind in (* Create fresh symbolic values for the inputs *) let input_svs = - List.map (fun ty -> mk_fresh_symbolic_value ty) inst_sg.inputs + List.map (fun ty -> mk_fresh_symbolic_value fdef.meta ty) inst_sg.inputs in (* Initialize the abstractions as empty (i.e., with no avalues) abstractions *) let call_id = fresh_fun_call_id () in - assert (call_id = FunCallId.zero); + cassert (call_id = FunCallId.zero) fdef.meta "The abstractions should be empty (i.e., with no avalues) abstractions"; let compute_abs_avalues (abs : abs) (ctx : eval_ctx) : eval_ctx * typed_avalue list = (* Project over the values - we use *loan* projectors, as explained above *) @@ -232,12 +233,12 @@ let initialize_symbolic_context_for_fun (meta : Meta.meta) (ctx : decls_ctx) (fd Collections.List.split_at (List.tl body.locals) body.arg_count in (* Push the return variable (initialized with ⊥) *) - let ctx = ctx_push_uninitialized_var meta ctx ret_var in + let ctx = ctx_push_uninitialized_var fdef.meta ctx ret_var in (* Push the input variables (initialized with symbolic values) *) let input_values = List.map mk_typed_value_from_symbolic_value input_svs in - let ctx = ctx_push_vars meta ctx (List.combine input_vars input_values) in + let ctx = ctx_push_vars fdef.meta ctx (List.combine input_vars input_values) in (* Push the remaining local variables (initialized with ⊥) *) - let ctx = ctx_push_uninitialized_vars meta ctx local_vars in + let ctx = ctx_push_uninitialized_vars fdef.meta ctx local_vars in (* Return *) (ctx, input_svs, inst_sg) @@ -271,7 +272,7 @@ let evaluate_function_symbolic_synthesize_backward_from_return (config : config) ^ "\n- inside_loop: " ^ Print.bool_to_string inside_loop ^ "\n- ctx:\n" - ^ Print.Contexts.eval_ctx_to_string ctx)); + ^ Print.Contexts.eval_ctx_to_string fdef.meta ctx)); (* We need to instantiate the function signature - to retrieve * the return type. Note that it is important to re-generate * an instantiation of the signature, so that we use fresh @@ -280,12 +281,12 @@ let evaluate_function_symbolic_synthesize_backward_from_return (config : config) FunIdMap.find (FRegular fdef.def_id) ctx.fun_ctx.regions_hierarchies in let _, ret_inst_sg = - symbolic_instantiate_fun_sig ctx fdef.signature regions_hierarchy fdef.kind + symbolic_instantiate_fun_sig fdef.meta ctx fdef.signature regions_hierarchy fdef.kind in let ret_rty = ret_inst_sg.output in (* Move the return value out of the return variable *) let pop_return_value = is_regular_return in - let cf_pop_frame = pop_frame config pop_return_value in + let cf_pop_frame = pop_frame fdef.meta config pop_return_value in (* We need to find the parents regions/abstractions of the region we * will end - this will allow us to, first, mark the other return @@ -313,7 +314,7 @@ let evaluate_function_symbolic_synthesize_backward_from_return (config : config) let compute_abs_avalues (abs : abs) (ctx : eval_ctx) : eval_ctx * typed_avalue list = let ctx, avalue = - apply_proj_borrows_on_input_value config ctx abs.regions + apply_proj_borrows_on_input_value fdef.meta config ctx abs.regions abs.ancestors_regions ret_value ret_rty in (ctx, [ avalue ]) @@ -329,7 +330,7 @@ let evaluate_function_symbolic_synthesize_backward_from_return (config : config) let region_can_end rid = RegionGroupId.Set.mem rid parent_and_current_rgs in - assert (region_can_end back_id); + cassert (region_can_end back_id) fdef.meta "The region should be able to end"; let ctx = create_push_abstractions_from_abs_region_groups (fun rg_id -> SynthRet rg_id) @@ -416,9 +417,9 @@ let evaluate_function_symbolic_synthesize_backward_from_return (config : config) | Loop (loop_id', rg_id', LoopSynthInput) -> (* We only allow to end the loop synth input abs for the region group [rg_id] *) - assert ( + cassert ( if Option.is_some loop_id then loop_id = Some loop_id' - else true); + else true) fdef.meta "Only the loop synth input abs for the region group [rg_id] are allowed to end"; (* Loop abstractions *) let rg_id' = Option.get rg_id' in if rg_id' = back_id && inside_loop then @@ -426,7 +427,7 @@ let evaluate_function_symbolic_synthesize_backward_from_return (config : config) else abs | Loop (loop_id', _, LoopCall) -> (* We can end all the loop call abstractions *) - assert (loop_id = Some loop_id'); + cassert (loop_id = Some loop_id') fdef.meta "TODO: error message"; { abs with can_end = true } | SynthInput rg_id' -> if rg_id' = back_id && end_fun_synth_input then @@ -446,7 +447,7 @@ let evaluate_function_symbolic_synthesize_backward_from_return (config : config) let target_abs_ids = List.append parent_input_abs_ids current_abs_id in let cf_end_target_abs cf = List.fold_left - (fun cf id -> end_abstraction config id cf) + (fun cf id -> end_abstraction fdef.meta config id cf) cf target_abs_ids in (* Generate the Return node *) @@ -468,7 +469,7 @@ let evaluate_function_symbolic_synthesize_backward_from_return (config : config) for the synthesis) - the symbolic AST generated by the symbolic execution *) -let evaluate_function_symbolic (meta : Meta.meta) (synthesize : bool) (ctx : decls_ctx) +let evaluate_function_symbolic (synthesize : bool) (ctx : decls_ctx) (fdef : fun_decl) : symbolic_value list * SA.expression option = (* Debug *) let name_to_string () = @@ -479,7 +480,7 @@ let evaluate_function_symbolic (meta : Meta.meta) (synthesize : bool) (ctx : dec log#ldebug (lazy ("evaluate_function_symbolic: " ^ name_to_string ())); (* Create the evaluation context *) - let ctx, input_svs, inst_sg = initialize_symbolic_context_for_fun meta ctx fdef in + let ctx, input_svs, inst_sg = initialize_symbolic_context_for_fun ctx fdef in let regions_hierarchy = FunIdMap.find (FRegular fdef.def_id) ctx.fun_ctx.regions_hierarchies @@ -512,7 +513,7 @@ let evaluate_function_symbolic (meta : Meta.meta) (synthesize : bool) (ctx : dec let fwd_e = (* Pop the frame and retrieve the returned value at the same time*) let pop_return_value = true in - let cf_pop = pop_frame config pop_return_value in + let cf_pop = pop_frame fdef.meta config pop_return_value in (* Generate the Return node *) let cf_return ret_value : m_fun = fun ctx -> Some (SA.Return (ctx, ret_value)) @@ -529,7 +530,7 @@ let evaluate_function_symbolic (meta : Meta.meta) (synthesize : bool) (ctx : dec match res with | Return -> None | LoopReturn loop_id -> Some loop_id - | _ -> raise (Failure "Unreachable") + | _ -> craise fdef.meta "Unreachable" in let is_regular_return = true in let inside_loop = Option.is_some loop_id in @@ -555,14 +556,14 @@ let evaluate_function_symbolic (meta : Meta.meta) (synthesize : bool) (ctx : dec match res with | EndEnterLoop _ -> false | EndContinue _ -> true - | _ -> raise (Failure "Unreachable") + | _ -> craise fdef.meta "Unreachable" in (* Forward translation *) let fwd_e = (* Pop the frame - there is no returned value to pop: in the translation we will simply call the loop function *) let pop_return_value = false in - let cf_pop = pop_frame config pop_return_value in + let cf_pop = pop_frame fdef.meta config pop_return_value in (* Generate the Return node *) let cf_return _ret_value : m_fun = fun _ctx -> Some (SA.ReturnWithLoop (loop_id, inside_loop)) @@ -596,13 +597,13 @@ let evaluate_function_symbolic (meta : Meta.meta) (synthesize : bool) (ctx : dec * the executions can lead to a panic *) if synthesize then Some SA.Panic else None | Unit | Break _ | Continue _ -> - raise - (Failure ("evaluate_function_symbolic failed on: " ^ name_to_string ())) + craise + fdef.meta ("evaluate_function_symbolic failed on: " ^ name_to_string ()) in (* Evaluate the function *) let symbolic = - eval_function_body config (Option.get fdef.body).body cf_finish ctx + eval_function_body fdef.meta config (Option.get fdef.body).body cf_finish ctx in (* Return *) @@ -612,7 +613,7 @@ module Test = struct (** Test a unit function (taking no arguments) by evaluating it in an empty environment. *) - let test_unit_function (meta : Meta.meta) (crate : crate) (decls_ctx : decls_ctx) + let test_unit_function (crate : crate) (decls_ctx : decls_ctx) (fid : FunDeclId.id) : unit = (* Retrieve the function declaration *) let fdef = FunDeclId.Map.find fid crate.fun_decls in @@ -627,14 +628,14 @@ module Test = struct fdef.name)); (* Sanity check - *) - assert (fdef.signature.generics = empty_generic_params); - assert (body.arg_count = 0); + cassert (fdef.signature.generics = empty_generic_params) fdef.meta "TODO: Error message"; + cassert (body.arg_count = 0) fdef.meta "TODO: Error message"; (* Create the evaluation context *) - let ctx = initialize_eval_ctx decls_ctx [] [] [] in + let ctx = initialize_eval_ctx fdef.meta decls_ctx [] [] [] in (* Insert the (uninitialized) local variables *) - let ctx = ctx_push_uninitialized_vars meta ctx body.locals in + let ctx = ctx_push_uninitialized_vars fdef.meta ctx body.locals in (* Create the continuation to check the function's result *) let config = mk_config ConcreteMode in @@ -643,18 +644,18 @@ module Test = struct | Return -> (* Ok: drop the local variables and finish *) let pop_return_value = true in - pop_frame config pop_return_value (fun _ _ -> None) ctx + pop_frame fdef.meta config pop_return_value (fun _ _ -> None) ctx | _ -> - raise - (Failure + craise + fdef.meta ("Unit test failed (concrete execution) on: " ^ Print.Types.name_to_string (Print.Contexts.decls_ctx_to_fmt_env decls_ctx) - fdef.name)) + fdef.name) in (* Evaluate the function *) - let _ = eval_function_body config body.body cf_check ctx in + let _ = eval_function_body body.meta config body.body cf_check ctx in () (** Small helper: return true if the function is a *transparent* unit function @@ -665,7 +666,7 @@ module Test = struct && def.signature.inputs = [] (** Test all the unit functions in a list of function definitions *) - let test_unit_functions (meta : Meta.meta) (crate : crate) : unit = + let test_unit_functions (crate : crate) : unit = let unit_funs = FunDeclId.Map.filter (fun _ -> fun_decl_is_transparent_unit) @@ -673,7 +674,7 @@ module Test = struct in let decls_ctx = compute_contexts crate in let test_unit_fun _ (def : fun_decl) : unit = - test_unit_function meta crate decls_ctx def.def_id + test_unit_function crate decls_ctx def.def_id in FunDeclId.Map.iter test_unit_fun unit_funs end diff --git a/compiler/InterpreterBorrows.ml b/compiler/InterpreterBorrows.ml index e37a67b7..be31d865 100644 --- a/compiler/InterpreterBorrows.ml +++ b/compiler/InterpreterBorrows.ml @@ -216,7 +216,7 @@ let end_borrow_get_borrow (meta : Meta.meta) (allowed_abs : AbstractionId.id opt set_replaced_bc (fst outer) (Abstract bc); (* Update the value - note that we are necessarily in the second * of the two cases described above *) - let asb = remove_borrow_from_asb l asb in + let asb = remove_borrow_from_asb meta l asb in ABorrow (AProjSharedBorrow asb)) else (* Nothing special to do *) super#visit_ABorrow outer bc @@ -254,8 +254,8 @@ let give_back_value (meta : Meta.meta) (config : config) (bid : BorrowId.id) (nv log#ldebug (lazy ("give_back_value:\n- bid: " ^ BorrowId.to_string bid ^ "\n- value: " - ^ typed_value_to_string ctx nv - ^ "\n- context:\n" ^ eval_ctx_to_string ctx ^ "\n")); + ^ typed_value_to_string meta ctx nv + ^ "\n- context:\n" ^ eval_ctx_to_string meta ctx ^ "\n")); (* We use a reference to check that we updated exactly one loan *) let replaced : bool ref = ref false in let set_replaced () = @@ -267,7 +267,7 @@ let give_back_value (meta : Meta.meta) (config : config) (bid : BorrowId.id) (nv (* We sometimes need to reborrow values while giving a value back due: prepare that *) let allow_reborrows = true in let fresh_reborrow, apply_registered_reborrows = - prepare_reborrows config allow_reborrows + prepare_reborrows meta config allow_reborrows in (* The visitor to give back the values *) let obj = @@ -335,7 +335,7 @@ let give_back_value (meta : Meta.meta) (config : config) (bid : BorrowId.id) (nv (* Remember the given back value as a meta-value * TODO: it is a bit annoying to have to deconstruct * the value... Think about a more elegant way. *) - let given_back_meta = as_symbolic nv.value in + let given_back_meta = as_symbolic meta nv.value in (* The loan projector *) let given_back = mk_aproj_loans_value_from_symbolic_value abs.regions sv @@ -382,7 +382,7 @@ let give_back_value (meta : Meta.meta) (config : config) (bid : BorrowId.id) (nv let given_back_meta = nv in (* Apply the projection *) let given_back = - apply_proj_borrows check_symbolic_no_ended ctx fresh_reborrow + apply_proj_borrows meta check_symbolic_no_ended ctx fresh_reborrow regions ancestors_regions nv borrowed_value_aty in (* Continue giving back in the child value *) @@ -409,7 +409,7 @@ let give_back_value (meta : Meta.meta) (config : config) (bid : BorrowId.id) (nv * we don't register the fact that we inserted the value somewhere * (i.e., we don't call {!set_replaced}) *) let given_back = - apply_proj_borrows check_symbolic_no_ended ctx fresh_reborrow + apply_proj_borrows meta check_symbolic_no_ended ctx fresh_reborrow regions ancestors_regions nv borrowed_value_aty in (* Continue giving back in the child value *) @@ -720,8 +720,8 @@ let reborrow_shared (meta : Meta.meta) (original_bid : BorrowId.id) (new_bid : B be expanded (because expanding this symbolic value would require expanding a reference whose region has already ended). *) -let convert_avalue_to_given_back_value (av : typed_avalue) : symbolic_value = - mk_fresh_symbolic_value av.ty +let convert_avalue_to_given_back_value (meta : Meta.meta) (av : typed_avalue) : symbolic_value = + mk_fresh_symbolic_value meta av.ty (** Auxiliary function: see {!end_borrow_aux}. @@ -746,11 +746,11 @@ let give_back (meta : Meta.meta) (config : config) (l : BorrowId.id) (bc : g_bor (lazy (let bc = match bc with - | Concrete bc -> borrow_content_to_string ctx bc - | Abstract bc -> aborrow_content_to_string ctx bc + | Concrete bc -> borrow_content_to_string meta ctx bc + | Abstract bc -> aborrow_content_to_string meta ctx bc in "give_back:\n- bid: " ^ BorrowId.to_string l ^ "\n- content: " ^ bc - ^ "\n- context:\n" ^ eval_ctx_to_string ctx ^ "\n")); + ^ "\n- context:\n" ^ eval_ctx_to_string meta ctx ^ "\n")); (* This is used for sanity checks *) let sanity_ek = { enter_shared_loans = true; enter_mut_borrows = true; enter_abs = true } @@ -781,7 +781,7 @@ let give_back (meta : Meta.meta) (config : config) (l : BorrowId.id) (bc : g_bor Rem.: we shouldn't do this here. We should do this in a function which takes care of ending *sub*-abstractions. *) - let sv = convert_avalue_to_given_back_value av in + let sv = convert_avalue_to_given_back_value meta av in (* Update the context *) give_back_avalue_to_same_abstraction meta config l av (mk_typed_value_from_symbolic_value sv) @@ -814,8 +814,8 @@ let check_borrow_disappeared (meta : Meta.meta) (fun_name : string) (l : BorrowI (lazy (fun_name ^ ": " ^ BorrowId.to_string l ^ ": borrow didn't disappear:\n- original context:\n" - ^ eval_ctx_to_string ctx0 ^ "\n\n- new context:\n" - ^ eval_ctx_to_string ctx)); + ^ eval_ctx_to_string meta ctx0 ^ "\n\n- new context:\n" + ^ eval_ctx_to_string meta ctx)); craise meta "Borrow not eliminated" in match lookup_loan_opt meta ek_all l ctx with @@ -825,8 +825,8 @@ let check_borrow_disappeared (meta : Meta.meta) (fun_name : string) (l : BorrowI (lazy (fun_name ^ ": " ^ BorrowId.to_string l ^ ": loan didn't disappear:\n- original context:\n" - ^ eval_ctx_to_string ctx0 ^ "\n\n- new context:\n" - ^ eval_ctx_to_string ctx)); + ^ eval_ctx_to_string meta ctx0 ^ "\n\n- new context:\n" + ^ eval_ctx_to_string meta ctx)); craise meta "Loan not eliminated" in unit_to_cm_fun check_disappeared @@ -858,12 +858,12 @@ let rec end_borrow_aux (meta : Meta.meta) (config : config) (chain : borrow_or_a (* Check that we don't loop *) let chain0 = chain in let chain = - add_borrow_or_abs_id_to_chain "end_borrow_aux: " (BorrowId l) chain + add_borrow_or_abs_id_to_chain meta "end_borrow_aux: " (BorrowId l) chain in log#ldebug (lazy ("end borrow: " ^ BorrowId.to_string l ^ ":\n- original context:\n" - ^ eval_ctx_to_string ctx)); + ^ eval_ctx_to_string meta ctx)); (* Utility function for the sanity checks: check that the borrow disappeared * from the context *) @@ -958,7 +958,7 @@ and end_abstraction_aux (meta : Meta.meta) (config : config) (chain : borrow_or_ fun cf ctx -> (* Check that we don't loop *) let chain = - add_borrow_or_abs_id_to_chain "end_abstraction_aux: " (AbsId abs_id) chain + add_borrow_or_abs_id_to_chain meta "end_abstraction_aux: " (AbsId abs_id) chain in (* Remember the original context for printing purposes *) let ctx0 = ctx in @@ -966,7 +966,7 @@ and end_abstraction_aux (meta : Meta.meta) (config : config) (chain : borrow_or_ (lazy ("end_abstraction_aux: " ^ AbstractionId.to_string abs_id - ^ "\n- original context:\n" ^ eval_ctx_to_string ctx0)); + ^ "\n- original context:\n" ^ eval_ctx_to_string meta ctx0)); (* Lookup the abstraction - note that if we end a list of abstractions, ending one abstraction may lead to the current abstraction having @@ -999,7 +999,7 @@ and end_abstraction_aux (meta : Meta.meta) (config : config) (chain : borrow_or_ ("end_abstraction_aux: " ^ AbstractionId.to_string abs_id ^ "\n- context after parent abstractions ended:\n" - ^ eval_ctx_to_string ctx))) + ^ eval_ctx_to_string meta ctx))) in (* End the loans inside the abstraction *) @@ -1010,7 +1010,7 @@ and end_abstraction_aux (meta : Meta.meta) (config : config) (chain : borrow_or_ (lazy ("end_abstraction_aux: " ^ AbstractionId.to_string abs_id - ^ "\n- context after loans ended:\n" ^ eval_ctx_to_string ctx))) + ^ "\n- context after loans ended:\n" ^ eval_ctx_to_string meta ctx))) in (* End the abstraction itself by redistributing the borrows it contains *) @@ -1039,8 +1039,8 @@ and end_abstraction_aux (meta : Meta.meta) (config : config) (chain : borrow_or_ (lazy ("end_abstraction_aux: " ^ AbstractionId.to_string abs_id - ^ "\n- original context:\n" ^ eval_ctx_to_string ctx0 - ^ "\n\n- new context:\n" ^ eval_ctx_to_string ctx))) + ^ "\n- original context:\n" ^ eval_ctx_to_string meta ctx0 + ^ "\n\n- new context:\n" ^ eval_ctx_to_string meta ctx))) in (* Sanity check: ending an abstraction must preserve the invariants *) @@ -1173,12 +1173,12 @@ and end_abstraction_borrows (meta : Meta.meta) (config : config) (chain : borrow log#ldebug (lazy ("end_abstraction_borrows: found aborrow content: " - ^ aborrow_content_to_string ctx bc)); + ^ aborrow_content_to_string meta ctx bc)); let ctx = match bc with | AMutBorrow (bid, av) -> (* First, convert the avalue to a (fresh symbolic) value *) - let sv = convert_avalue_to_given_back_value av in + let sv = convert_avalue_to_given_back_value meta av in (* Replace the mut borrow to register the fact that we ended * it and store with it the freshly generated given back value *) let ended_borrow = ABorrow (AEndedMutBorrow (sv, av)) in @@ -1228,7 +1228,7 @@ and end_abstraction_borrows (meta : Meta.meta) (config : config) (chain : borrow ("end_abstraction_borrows: found aproj borrows: " ^ aproj_to_string ctx (AProjBorrows (sv, proj_ty)))); (* Generate a fresh symbolic value *) - let nsv = mk_fresh_symbolic_value proj_ty in + let nsv = mk_fresh_symbolic_value meta proj_ty in (* Replace the proj_borrows - there should be exactly one *) let ended_borrow = AEndedProjBorrows nsv in let ctx = update_aproj_borrows meta abs.abs_id sv ended_borrow ctx in @@ -1243,7 +1243,7 @@ and end_abstraction_borrows (meta : Meta.meta) (config : config) (chain : borrow log#ldebug (lazy ("end_abstraction_borrows: found borrow content: " - ^ borrow_content_to_string ctx bc)); + ^ borrow_content_to_string meta ctx bc)); let ctx = match bc with | VSharedBorrow bid -> ( @@ -1432,16 +1432,16 @@ let end_abstraction meta config = end_abstraction_aux meta config [] let end_abstractions meta config = end_abstractions_aux meta config [] let end_borrow_no_synth meta config id ctx = - get_cf_ctx_no_synth (end_borrow meta config id) ctx + get_cf_ctx_no_synth meta (end_borrow meta config id) ctx let end_borrows_no_synth meta config ids ctx = - get_cf_ctx_no_synth (end_borrows meta config ids) ctx + get_cf_ctx_no_synth meta (end_borrows meta config ids) ctx let end_abstraction_no_synth meta config id ctx = - get_cf_ctx_no_synth (end_abstraction meta config id) ctx + get_cf_ctx_no_synth meta (end_abstraction meta config id) ctx let end_abstractions_no_synth meta config ids ctx = - get_cf_ctx_no_synth (end_abstractions meta config ids) ctx + get_cf_ctx_no_synth meta (end_abstractions meta config ids) ctx (** Helper function: see {!activate_reserved_mut_borrow}. @@ -1466,7 +1466,7 @@ let promote_shared_loan_to_mut_loan (meta : Meta.meta) (l : BorrowId.id) log#ldebug (lazy ("promote_shared_loan_to_mut_loan:\n- loan: " ^ BorrowId.to_string l - ^ "\n- context:\n" ^ eval_ctx_to_string ctx ^ "\n")); + ^ "\n- context:\n" ^ eval_ctx_to_string meta ctx ^ "\n")); (* Lookup the shared loan - note that we can't promote a shared loan * in a shared value, but we can do it in a mutably borrowed value. * This is important because we can do: [let y = &two-phase ( *x );] @@ -1563,7 +1563,7 @@ let rec promote_reserved_mut_borrow (meta : Meta.meta) (config : config) (l : Bo log#ldebug (lazy ("activate_reserved_mut_borrow: resulting value:\n" - ^ typed_value_to_string ctx sv)); + ^ typed_value_to_string meta ctx sv)); cassert (not (loans_in_value sv)) meta "TODO: error message"; cassert (not (bottom_in_value ctx.ended_regions sv)) meta "TODO: error message"; cassert (not (reserved_in_value sv)) meta "TODO: error message"; @@ -1627,7 +1627,7 @@ let destructure_abs (meta : Meta.meta) (abs_kind : abs_kind) (can_end : bool) if destructure_shared_values then list_values sv else ([], sv) in (* Push a value *) - let ignored = mk_aignored child_av.ty in + let ignored = mk_aignored meta child_av.ty in let value = ALoan (ASharedLoan (bids, sv, ignored)) in push { value; ty }; (* Explore the child *) @@ -1643,7 +1643,7 @@ let destructure_abs (meta : Meta.meta) (abs_kind : abs_kind) (can_end : bool) (* Explore the child *) list_avalues false push_fail child_av; (* Explore the whole loan *) - let ignored = mk_aignored child_av.ty in + let ignored = mk_aignored meta child_av.ty in let value = ALoan (AMutLoan (bid, ignored)) in push { value; ty } | AIgnoredMutLoan (opt_bid, child_av) -> @@ -1671,7 +1671,7 @@ let destructure_abs (meta : Meta.meta) (abs_kind : abs_kind) (can_end : bool) (* Explore the child *) list_avalues false push_fail child_av; (* Explore the borrow *) - let ignored = mk_aignored child_av.ty in + let ignored = mk_aignored meta child_av.ty in let value = ABorrow (AMutBorrow (bid, ignored)) in push { value; ty } | ASharedBorrow _ -> @@ -1742,7 +1742,7 @@ let destructure_abs (meta : Meta.meta) (abs_kind : abs_kind) (can_end : bool) in let sv = mk_value_with_fresh_sids sv in (* Create the new avalue *) - let value = ALoan (ASharedLoan (bids, sv, mk_aignored ty)) in + let value = ALoan (ASharedLoan (bids, sv, mk_aignored meta ty)) in { value; ty } in let avl = List.append [ av ] avl in @@ -1808,7 +1808,7 @@ let convert_value_to_abstractions (meta : Meta.meta) (abs_kind : abs_kind) (can_ log#ldebug (lazy ("convert_value_to_abstractions: to_avalues:\n- value: " - ^ typed_value_to_string ctx v)); + ^ typed_value_to_string meta ctx v)); let ty = v.ty in match v.value with @@ -1868,7 +1868,7 @@ let convert_value_to_abstractions (meta : Meta.meta) (abs_kind : abs_kind) (can_ cassert (not (value_has_borrows ctx bv.value)) meta "Nested borrows are not supported yet"; (* Create an avalue to push - note that we use [AIgnore] for the inner avalue *) let ty = TRef (RFVar r_id, ref_ty, kind) in - let ignored = mk_aignored ref_ty in + let ignored = mk_aignored meta ref_ty in let av = ABorrow (AMutBorrow (bid, ignored)) in let av = { value = av; ty } in (* Continue exploring, looking for loans (and forbidding borrows, @@ -1889,7 +1889,7 @@ let convert_value_to_abstractions (meta : Meta.meta) (abs_kind : abs_kind) (can_ (* For avalues, a loan has the borrow type *) cassert (ty_no_regions ty) meta "TODO: error message"; let ty = mk_ref_ty (RFVar r_id) ty RShared in - let ignored = mk_aignored ty in + let ignored = mk_aignored meta ty in (* Rem.: the shared value might contain loans *) let avl, sv = to_avalues false true true r_id sv in let av = ALoan (ASharedLoan (bids, sv, ignored)) in @@ -1907,7 +1907,7 @@ let convert_value_to_abstractions (meta : Meta.meta) (abs_kind : abs_kind) (can_ (* For avalues, a loan has the borrow type *) cassert (ty_no_regions ty) meta "TODO: error message"; let ty = mk_ref_ty (RFVar r_id) ty RMut in - let ignored = mk_aignored ty in + let ignored = mk_aignored meta ty in let av = ALoan (AMutLoan (bid, ignored)) in let av = { value = av; ty } in ([ av ], v)) @@ -2140,8 +2140,8 @@ let merge_into_abstraction_aux (meta : Meta.meta) (abs_kind : abs_kind) (can_end (abs1 : abs) : abs = log#ldebug (lazy - ("merge_into_abstraction_aux:\n- abs0:\n" ^ abs_to_string ctx abs0 - ^ "\n\n- abs1:\n" ^ abs_to_string ctx abs1)); + ("merge_into_abstraction_aux:\n- abs0:\n" ^ abs_to_string meta ctx abs0 + ^ "\n\n- abs1:\n" ^ abs_to_string meta ctx abs1)); (* Check that the abstractions are destructured *) if !Config.sanity_checks then ( @@ -2201,7 +2201,7 @@ let merge_into_abstraction_aux (meta : Meta.meta) (abs_kind : abs_kind) (can_end log#ldebug (lazy ("merge_into_abstraction_aux: push_avalue: " - ^ typed_avalue_to_string ctx av)); + ^ typed_avalue_to_string meta ctx av)); avalues := av :: !avalues in let push_opt_avalue av = diff --git a/compiler/InterpreterBorrows.mli b/compiler/InterpreterBorrows.mli index e47ba82d..95a27245 100644 --- a/compiler/InterpreterBorrows.mli +++ b/compiler/InterpreterBorrows.mli @@ -8,37 +8,37 @@ open Cps applies this change to an environment [ctx] by inserting a new borrow id in the set of borrows tracked by a shared value, referenced by the [original_bid] argument. *) -val reborrow_shared : BorrowId.id -> BorrowId.id -> eval_ctx -> eval_ctx +val reborrow_shared : Meta.meta -> BorrowId.id -> BorrowId.id -> eval_ctx -> eval_ctx (** End a borrow identified by its id, while preserving the invariants. If the borrow is inside another borrow/an abstraction or contains loans, [end_borrow] will end those borrows/abstractions/loans first. *) -val end_borrow : config -> BorrowId.id -> cm_fun +val end_borrow : Meta.meta -> config -> BorrowId.id -> cm_fun (** End a set of borrows identified by their ids, while preserving the invariants. *) -val end_borrows : config -> BorrowId.Set.t -> cm_fun +val end_borrows : Meta.meta -> config -> BorrowId.Set.t -> cm_fun (** End an abstraction while preserving the invariants. *) -val end_abstraction : config -> AbstractionId.id -> cm_fun +val end_abstraction : Meta.meta -> config -> AbstractionId.id -> cm_fun (** End a set of abstractions while preserving the invariants. *) -val end_abstractions : config -> AbstractionId.Set.t -> cm_fun +val end_abstractions : Meta.meta -> config -> AbstractionId.Set.t -> cm_fun (** End a borrow and return the resulting environment, ignoring synthesis *) -val end_borrow_no_synth : config -> BorrowId.id -> eval_ctx -> eval_ctx +val end_borrow_no_synth : Meta.meta -> config -> BorrowId.id -> eval_ctx -> eval_ctx (** End a set of borrows and return the resulting environment, ignoring synthesis *) -val end_borrows_no_synth : config -> BorrowId.Set.t -> eval_ctx -> eval_ctx +val end_borrows_no_synth : Meta.meta -> config -> BorrowId.Set.t -> eval_ctx -> eval_ctx (** End an abstraction and return the resulting environment, ignoring synthesis *) val end_abstraction_no_synth : - config -> AbstractionId.id -> eval_ctx -> eval_ctx + Meta.meta -> config -> AbstractionId.id -> eval_ctx -> eval_ctx (** End a set of abstractions and return the resulting environment, ignoring synthesis *) val end_abstractions_no_synth : - config -> AbstractionId.Set.t -> eval_ctx -> eval_ctx + Meta.meta -> config -> AbstractionId.Set.t -> eval_ctx -> eval_ctx (** Promote a reserved mut borrow to a mut borrow, while preserving the invariants. @@ -49,7 +49,7 @@ val end_abstractions_no_synth : the corresponding shared loan with a mutable loan (after having ended the other shared borrows which point to this loan). *) -val promote_reserved_mut_borrow : config -> BorrowId.id -> cm_fun +val promote_reserved_mut_borrow : Meta.meta -> config -> BorrowId.id -> cm_fun (** Transform an abstraction to an abstraction where the values are not structured. @@ -91,7 +91,7 @@ val promote_reserved_mut_borrow : config -> BorrowId.id -> cm_fun - [ctx] - [abs] *) -val destructure_abs : abs_kind -> bool -> bool -> eval_ctx -> abs -> abs +val destructure_abs : Meta.meta -> abs_kind -> bool -> bool -> eval_ctx -> abs -> abs (** Return [true] if the values in an abstraction are destructured. @@ -99,7 +99,7 @@ val destructure_abs : abs_kind -> bool -> bool -> eval_ctx -> abs -> abs The input boolean is [destructure_shared_value]. See {!destructure_abs}. *) -val abs_is_destructured : bool -> eval_ctx -> abs -> bool +val abs_is_destructured : Meta.meta -> bool -> eval_ctx -> abs -> bool (** Turn a value into a abstractions. @@ -125,7 +125,7 @@ val abs_is_destructured : bool -> eval_ctx -> abs -> bool - [v] *) val convert_value_to_abstractions : - abs_kind -> bool -> bool -> eval_ctx -> typed_value -> abs list + Meta.meta -> abs_kind -> bool -> bool -> eval_ctx -> typed_value -> abs list (** See {!merge_into_abstraction}. @@ -232,6 +232,7 @@ type merge_duplicates_funcs = { results from the merge. *) val merge_into_abstraction : + Meta.meta -> abs_kind -> bool -> merge_duplicates_funcs option -> diff --git a/compiler/InterpreterBorrowsCore.ml b/compiler/InterpreterBorrowsCore.ml index 5b84e2c0..6691fdcd 100644 --- a/compiler/InterpreterBorrowsCore.ml +++ b/compiler/InterpreterBorrowsCore.ml @@ -72,13 +72,13 @@ let borrow_or_abs_ids_chain_to_string (ids : borrow_or_abs_ids) : string = String.concat " -> " ids (** Add a borrow or abs id to a chain of ids, while checking that we don't loop *) -let add_borrow_or_abs_id_to_chain (msg : string) (id : borrow_or_abs_id) +let add_borrow_or_abs_id_to_chain (meta : Meta.meta) (msg : string) (id : borrow_or_abs_id) (ids : borrow_or_abs_ids) : borrow_or_abs_ids = if List.mem id ids then - raise - (Failure + craise + meta (msg ^ "detected a loop in the chain of ids: " - ^ borrow_or_abs_ids_chain_to_string (id :: ids))) + ^ borrow_or_abs_ids_chain_to_string (id :: ids)) else id :: ids (** Helper function. @@ -100,14 +100,14 @@ let rec compare_rtys (meta : Meta.meta) (default : bool) (combine : bool -> bool = let compare = compare_rtys meta default combine compare_regions in (* Sanity check - TODO: don't do this at every recursive call *) - cassert (ty_is_rty ty1 && ty_is_rty ty2) meta "ty1 or ty2 are not rty TODO"; + cassert (ty_is_rty ty1 && ty_is_rty ty2) meta "ty1 or ty2 are not rty TODO: Error message"; (* Normalize the associated types *) match (ty1, ty2) with | TLiteral lit1, TLiteral lit2 -> - cassert (lit1 = lit2) meta "Tlitrals are not equal TODO"; + cassert (lit1 = lit2) meta "Tlitrals are not equal TODO: Error message"; default | TAdt (id1, generics1), TAdt (id2, generics2) -> - cassert (id1 = id2) meta "ids are not equal TODO"; + cassert (id1 = id2) meta "ids are not equal TODO: Error message"; (* There are no regions in the const generics, so we ignore them, but we still check they are the same, for sanity *) cassert (generics1.const_generics = generics2.const_generics) meta "const generics are not the same"; @@ -144,7 +144,7 @@ let rec compare_rtys (meta : Meta.meta) (default : bool) (combine : bool -> bool combine params_b tys_b | TRef (r1, ty1, kind1), TRef (r2, ty2, kind2) -> (* Sanity check *) - cassert (kind1 = kind2) meta "kind1 and kind2 are not equal TODO"; + cassert (kind1 = kind2) meta "kind1 and kind2 are not equal TODO: Error message"; (* Explanation for the case where we check if projections intersect: * the projections intersect if the borrows intersect or their contents * intersect. *) @@ -152,7 +152,7 @@ let rec compare_rtys (meta : Meta.meta) (default : bool) (combine : bool -> bool let tys_b = compare ty1 ty2 in combine regions_b tys_b | TVar id1, TVar id2 -> - cassert (id1 = id2) meta "Ids are not the same TODO"; + cassert (id1 = id2) meta "Ids are not the same TODO: Error message"; default | TTraitType _, TTraitType _ -> (* The types should have been normalized. If after normalization we @@ -301,7 +301,7 @@ let lookup_loan_opt (meta : Meta.meta) (ek : exploration_kind) (l : BorrowId.id) The loan is referred to by a borrow id. Raises an exception if no loan was found. *) -let lookup_loan (meta : Meta.meta) (ek : exploration_kind) (l : BorrowId.id) (ctx : eval_ctx) : +let lookup_loan (meta : Meta.meta) (ek : exploration_kind) (l : BorrowId.id) (ctx : eval_ctx) : abs_or_var_id * g_loan_content = match lookup_loan_opt meta ek l ctx with | None -> craise meta "Unreachable" @@ -936,7 +936,7 @@ let update_intersecting_aproj_loans (meta : Meta.meta) (proj_regions : RegionId. (subst : abs -> (msymbolic_value * aproj) list -> aproj) (ctx : eval_ctx) : eval_ctx = (* *) - cassert (ty_is_rty proj_ty) meta "proj_ty is not rty TODO"; + cassert (ty_is_rty proj_ty) meta "proj_ty is not rty TODO: Error message"; (* Small helpers for sanity checks *) let updated = ref false in let update abs local_given_back : aproj = @@ -1158,7 +1158,7 @@ let no_aproj_over_symbolic_in_context (meta : Meta.meta) (sv : symbolic_value) **Remark:** we don't take the *ignored* mut/shared loans into account. *) -let get_first_non_ignored_aloan_in_abstraction (meta : Meta.meta) (abs : abs) : +let get_first_non_ignored_aloan_in_abstraction (meta : Meta.meta) (abs : abs) : borrow_ids_or_symbolic_value option = (* Explore to find a loan *) let obj = diff --git a/compiler/InterpreterExpansion.ml b/compiler/InterpreterExpansion.ml index 0a5a289e..9448f3e8 100644 --- a/compiler/InterpreterExpansion.ml +++ b/compiler/InterpreterExpansion.ml @@ -56,7 +56,7 @@ let apply_symbolic_expansion_to_target_avalues (meta : Meta.meta) (config : conf let check_symbolic_no_ended = false in (* Prepare reborrows registration *) let fresh_reborrow, apply_registered_reborrows = - prepare_reborrows config allow_reborrows + prepare_reborrows meta config allow_reborrows in (* Visitor to apply the expansion *) let obj = @@ -66,7 +66,7 @@ let apply_symbolic_expansion_to_target_avalues (meta : Meta.meta) (config : conf (** When visiting an abstraction, we remember the regions it owns to be able to properly reduce projectors when expanding symbolic values *) method! visit_abs current_abs abs = - cassert (Option.is_none current_abs) meta "T"; + cassert (Option.is_none current_abs) meta "TODO: error message"; let current_abs = Some abs in super#visit_abs current_abs abs @@ -78,7 +78,7 @@ let apply_symbolic_expansion_to_target_avalues (meta : Meta.meta) (config : conf method! visit_aproj current_abs aproj = (match aproj with | AProjLoans (sv, _) | AProjBorrows (sv, _) -> - cassert (not (same_symbolic_id sv original_sv)) meta "T" + cassert (not (same_symbolic_id sv original_sv)) meta "TODO: error message" | AEndedProjLoans _ | AEndedProjBorrows _ | AIgnoredProjBorrows -> ()); super#visit_aproj current_abs aproj @@ -98,10 +98,10 @@ let apply_symbolic_expansion_to_target_avalues (meta : Meta.meta) (config : conf (* Check if this is the symbolic value we are looking for *) if same_symbolic_id sv original_sv then ( (* There mustn't be any given back values *) - cassert (given_back = []) meta "T"; + cassert (given_back = []) meta "TODO: error message"; (* Apply the projector *) let projected_value = - apply_proj_loans_on_symbolic_expansion proj_regions + apply_proj_loans_on_symbolic_expansion meta proj_regions ancestors_regions expansion original_sv.sv_ty in (* Replace *) @@ -118,12 +118,12 @@ let apply_symbolic_expansion_to_target_avalues (meta : Meta.meta) (config : conf (* WARNING: we mustn't get there if the expansion is for a shared * reference. *) let expansion = - symbolic_expansion_non_shared_borrow_to_value original_sv + symbolic_expansion_non_shared_borrow_to_value meta original_sv expansion in (* Apply the projector *) let projected_value = - apply_proj_borrows check_symbolic_no_ended ctx fresh_reborrow + apply_proj_borrows meta check_symbolic_no_ended ctx fresh_reborrow proj_regions ancestors_regions expansion proj_ty in (* Replace *) @@ -168,7 +168,7 @@ let replace_symbolic_values (meta : Meta.meta) (at_most_once : bool) (original_s (* Count *) let replaced = ref false in let replace () = - if at_most_once then cassert (not !replaced) meta "T"; + if at_most_once then cassert (not !replaced) meta "TODO: error message"; replaced := true; nv in @@ -191,7 +191,7 @@ let apply_symbolic_expansion_non_borrow (meta : Meta.meta) (config : config) (original_sv : symbolic_value) (expansion : symbolic_expansion) (ctx : eval_ctx) : eval_ctx = (* Apply the expansion to non-abstraction values *) - let nv = symbolic_expansion_non_borrow_to_value original_sv expansion in + let nv = symbolic_expansion_non_borrow_to_value meta original_sv expansion in let at_most_once = false in let ctx = replace_symbolic_values meta at_most_once original_sv nv.value ctx in (* Apply the expansion to abstraction values *) @@ -215,7 +215,7 @@ let compute_expanded_symbolic_non_assumed_adt_value (meta : Meta.meta) (expand_e (* Lookup the definition and check if it is an enumeration with several * variants *) let def = ctx_lookup_type_decl ctx def_id in - cassert (List.length generics.regions = List.length def.generics.regions) meta "T"; + cassert (List.length generics.regions = List.length def.generics.regions) meta "TODO: error message"; (* Retrieve, for every variant, the list of its instantiated field types *) let variants_fields_types = AssociatedTypes.type_decl_get_inst_norm_variants_fields_rtypes ctx def @@ -228,7 +228,7 @@ let compute_expanded_symbolic_non_assumed_adt_value (meta : Meta.meta) (expand_e let initialize ((variant_id, field_types) : VariantId.id option * rty list) : symbolic_expansion = let field_values = - List.map (fun (ty : rty) -> mk_fresh_symbolic_value ty) field_types + List.map (fun (ty : rty) -> mk_fresh_symbolic_value meta ty) field_types in let see = SeAdt (variant_id, field_values) in see @@ -236,19 +236,19 @@ let compute_expanded_symbolic_non_assumed_adt_value (meta : Meta.meta) (expand_e (* Initialize all the expanded values of all the variants *) List.map initialize variants_fields_types -let compute_expanded_symbolic_tuple_value (field_types : rty list) : +let compute_expanded_symbolic_tuple_value (meta : Meta.meta) (field_types : rty list) : symbolic_expansion = (* Generate the field values *) let field_values = - List.map (fun sv_ty -> mk_fresh_symbolic_value sv_ty) field_types + List.map (fun sv_ty -> mk_fresh_symbolic_value meta sv_ty) field_types in let variant_id = None in let see = SeAdt (variant_id, field_values) in see -let compute_expanded_symbolic_box_value (boxed_ty : rty) : symbolic_expansion = +let compute_expanded_symbolic_box_value (meta : Meta.meta) (boxed_ty : rty) : symbolic_expansion = (* Introduce a fresh symbolic value *) - let boxed_value = mk_fresh_symbolic_value boxed_ty in + let boxed_value = mk_fresh_symbolic_value meta boxed_ty in let see = SeAdt (None, [ boxed_value ]) in see @@ -268,9 +268,9 @@ let compute_expanded_symbolic_adt_value (meta : Meta.meta) (expand_enumerations | TAdtId def_id, _, _ -> compute_expanded_symbolic_non_assumed_adt_value meta expand_enumerations def_id generics ctx - | TTuple, [], _ -> [ compute_expanded_symbolic_tuple_value generics.types ] + | TTuple, [], _ -> [ compute_expanded_symbolic_tuple_value meta generics.types ] | TAssumed TBox, [], [ boxed_ty ] -> - [ compute_expanded_symbolic_box_value boxed_ty ] + [ compute_expanded_symbolic_box_value meta boxed_ty ] | _ -> craise meta "compute_expanded_symbolic_adt_value: unexpected combination" @@ -312,7 +312,7 @@ let expand_symbolic_value_shared_borrow (meta : Meta.meta) (config : config) else None in (* The fresh symbolic value for the shared value *) - let shared_sv = mk_fresh_symbolic_value ref_ty in + let shared_sv = mk_fresh_symbolic_value meta ref_ty in (* Visitor to replace the projectors on borrows *) let obj = object (self) @@ -325,7 +325,7 @@ let expand_symbolic_value_shared_borrow (meta : Meta.meta) (config : config) else super#visit_VSymbolic env sv method! visit_EAbs proj_regions abs = - cassert (Option.is_none proj_regions) meta "T"; + cassert (Option.is_none proj_regions) meta "TODO: error message"; let proj_regions = Some abs.regions in super#visit_EAbs proj_regions abs @@ -350,7 +350,7 @@ let expand_symbolic_value_shared_borrow (meta : Meta.meta) (config : config) method! visit_aproj proj_regions aproj = (match aproj with | AProjLoans (sv, _) | AProjBorrows (sv, _) -> - cassert (not (same_symbolic_id sv original_sv)) meta "T" + cassert (not (same_symbolic_id sv original_sv)) meta "TODO: error message" | AEndedProjLoans _ | AEndedProjBorrows _ | AIgnoredProjBorrows -> ()); super#visit_aproj proj_regions aproj @@ -376,7 +376,7 @@ let expand_symbolic_value_shared_borrow (meta : Meta.meta) (config : config) let ctx = obj#visit_eval_ctx None ctx in (* Finally, replace the projectors on loans *) let bids = !borrows in - cassert (not (BorrowId.Set.is_empty bids)) meta "T"; + cassert (not (BorrowId.Set.is_empty bids)) meta "TODO: error message"; let see = SeSharedRef (bids, shared_sv) in let allow_reborrows = true in let ctx = @@ -394,20 +394,20 @@ let expand_symbolic_value_borrow (meta : Meta.meta) (config : config) (original_sv : symbolic_value) (original_sv_place : SA.mplace option) (region : region) (ref_ty : rty) (rkind : ref_kind) : cm_fun = fun cf ctx -> - cassert (region <> RErased) meta "T"; + cassert (region <> RErased) meta "TODO: error message"; (* Check that we are allowed to expand the reference *) - cassert (not (region_in_set region ctx.ended_regions)) meta "T"; + cassert (not (region_in_set region ctx.ended_regions)) meta "TODO: error message"; (* Match on the reference kind *) match rkind with | RMut -> (* Simple case: simply create a fresh symbolic value and a fresh * borrow id *) - let sv = mk_fresh_symbolic_value ref_ty in + let sv = mk_fresh_symbolic_value meta ref_ty in let bid = fresh_borrow_id () in let see = SeMutRef (bid, sv) in (* Expand the symbolic values - we simply perform a substitution (and * check that we perform exactly one substitution) *) - let nv = symbolic_expansion_non_shared_borrow_to_value original_sv see in + let nv = symbolic_expansion_non_shared_borrow_to_value meta original_sv see in let at_most_once = true in let ctx = replace_symbolic_values meta at_most_once original_sv nv.value ctx in (* Expand the symbolic avalues *) @@ -446,7 +446,7 @@ let apply_branching_symbolic_expansions_non_borrow (meta : Meta.meta) (config : (see_cf_l : (symbolic_expansion option * st_cm_fun) list) (cf_after_join : st_m_fun) : m_fun = fun ctx -> - cassert (see_cf_l <> []) meta "T"; + cassert (see_cf_l <> []) meta "TODO: error message"; (* Apply the symbolic expansion in the context and call the continuation *) let resl = List.map @@ -464,8 +464,8 @@ let apply_branching_symbolic_expansions_non_borrow (meta : Meta.meta) (config : (lazy ("apply_branching_symbolic_expansions_non_borrow: " ^ symbolic_value_to_string ctx0 sv - ^ "\n\n- original context:\n" ^ eval_ctx_to_string ctx0 - ^ "\n\n- new context:\n" ^ eval_ctx_to_string ctx ^ "\n")); + ^ "\n\n- original context:\n" ^ eval_ctx_to_string meta ctx0 + ^ "\n\n- new context:\n" ^ eval_ctx_to_string meta ctx ^ "\n")); (* Continuation *) cf_br cf_after_join ctx) see_cf_l @@ -476,7 +476,7 @@ let apply_branching_symbolic_expansions_non_borrow (meta : Meta.meta) (config : match resl with | Some _ :: _ -> Some (List.map Option.get resl) | None :: _ -> - List.iter (fun res -> cassert (res = None) meta "T") resl; + List.iter (fun res -> cassert (res = None) meta "TODO: error message") resl; None | _ -> craise meta "Unreachable" in @@ -492,7 +492,7 @@ let expand_symbolic_bool (meta : Meta.meta) (config : config) (sv : symbolic_val let original_sv = sv in let original_sv_place = sv_place in let rty = original_sv.sv_ty in - cassert (rty = TLiteral TBool) meta "T"; + cassert (rty = TLiteral TBool) meta "TODO: error message"; (* Expand the symbolic value to true or false and continue execution *) let see_true = SeLiteral (VBool true) in let see_false = SeLiteral (VBool false) in @@ -554,10 +554,10 @@ let expand_symbolic_value_no_branching (meta : Meta.meta) (config : config) (sv (lazy ("expand_symbolic_value_no_branching: " ^ symbolic_value_to_string ctx0 sv - ^ "\n\n- original context:\n" ^ eval_ctx_to_string ctx0 - ^ "\n\n- new context:\n" ^ eval_ctx_to_string ctx ^ "\n")); + ^ "\n\n- original context:\n" ^ eval_ctx_to_string meta ctx0 + ^ "\n\n- new context:\n" ^ eval_ctx_to_string meta ctx ^ "\n")); (* Sanity check: the symbolic value has disappeared *) - cassert (not (symbolic_value_id_in_ctx original_sv.sv_id ctx)) meta "T") + cassert (not (symbolic_value_id_in_ctx original_sv.sv_id ctx)) meta "TODO: error message") in (* Continue *) cc cf ctx @@ -594,7 +594,7 @@ let expand_symbolic_int (meta : Meta.meta) (config : config) (sv : symbolic_valu (tgts : (scalar_value * st_cm_fun) list) (otherwise : st_cm_fun) (cf_after_join : st_m_fun) : m_fun = (* Sanity check *) - cassert (sv.sv_ty = TLiteral (TInteger int_type)) meta "T"; + cassert (sv.sv_ty = TLiteral (TInteger int_type)) meta "TODO: error message"; (* For all the branches of the switch, we expand the symbolic value * to the value given by the branch and execute the branch statement. * For the otherwise branch, we leave the symbolic value as it is diff --git a/compiler/InterpreterExpansion.mli b/compiler/InterpreterExpansion.mli index b545f979..3540d04c 100644 --- a/compiler/InterpreterExpansion.mli +++ b/compiler/InterpreterExpansion.mli @@ -12,11 +12,11 @@ type proj_kind = LoanProj | BorrowProj This function does *not* update the synthesis. *) val apply_symbolic_expansion_non_borrow : - config -> symbolic_value -> symbolic_expansion -> eval_ctx -> eval_ctx + Meta.meta -> config -> symbolic_value -> symbolic_expansion -> eval_ctx -> eval_ctx (** Expand a symhbolic value, without branching *) val expand_symbolic_value_no_branching : - config -> symbolic_value -> SA.mplace option -> cm_fun + Meta.meta -> config -> symbolic_value -> SA.mplace option -> cm_fun (** Expand a symbolic enumeration (leads to branching if the enumeration has more than one variant). @@ -32,7 +32,7 @@ val expand_symbolic_value_no_branching : then call it). *) val expand_symbolic_adt : - config -> symbolic_value -> SA.mplace option -> st_cm_fun -> st_m_fun -> m_fun + Meta.meta -> config -> symbolic_value -> SA.mplace option -> st_cm_fun -> st_m_fun -> m_fun (** Expand a symbolic boolean. @@ -41,6 +41,7 @@ val expand_symbolic_adt : parameter (here, there are exactly two branches). *) val expand_symbolic_bool : + Meta.meta -> config -> symbolic_value -> SA.mplace option -> @@ -69,6 +70,7 @@ val expand_symbolic_bool : switch. The continuation is thus for the execution *after* the switch. *) val expand_symbolic_int : + Meta.meta -> config -> symbolic_value -> SA.mplace option -> @@ -81,4 +83,4 @@ val expand_symbolic_int : (** If this mode is activated through the [config], greedily expand the symbolic values which need to be expanded. See {!type:Contexts.config} for more information. *) -val greedy_expand_symbolic_values : config -> cm_fun +val greedy_expand_symbolic_values : Meta.meta -> config -> cm_fun diff --git a/compiler/InterpreterExpressions.ml b/compiler/InterpreterExpressions.ml index 51be904f..f82c7130 100644 --- a/compiler/InterpreterExpressions.ml +++ b/compiler/InterpreterExpressions.ml @@ -11,6 +11,7 @@ open Cps open InterpreterUtils open InterpreterExpansion open InterpreterPaths +open Errors (** The local logger *) let log = Logging.expressions_log @@ -29,14 +30,14 @@ let expand_primitively_copyable_at_place (meta : Meta.meta) (config : config) (* Small helper *) let rec expand : cm_fun = fun cf ctx -> - let v = read_place access p ctx in + let v = read_place meta access p ctx in match find_first_primitively_copyable_sv_with_borrows ctx.type_ctx.type_infos v with | None -> cf ctx | Some sv -> let cc = - expand_symbolic_value_no_branching config sv (Some (mk_mplace meta p ctx)) + expand_symbolic_value_no_branching meta config sv (Some (mk_mplace meta p ctx)) in comp cc expand cf ctx in @@ -48,14 +49,14 @@ let expand_primitively_copyable_at_place (meta : Meta.meta) (config : config) We also check that the value *doesn't contain bottoms or reserved borrows*. *) -let read_place (access : access_kind) (p : place) (cf : typed_value -> m_fun) : +let read_place (meta : Meta.meta) (access : access_kind) (p : place) (cf : typed_value -> m_fun) : m_fun = fun ctx -> - let v = read_place access p ctx in + let v = read_place meta access p ctx in (* Check that there are no bottoms in the value *) - assert (not (bottom_in_value ctx.ended_regions v)); + cassert (not (bottom_in_value ctx.ended_regions v)) meta "There should be no bottoms in the value"; (* Check that there are no reserved borrows in the value *) - assert (not (reserved_in_value v)); + cassert (not (reserved_in_value v)) meta "There should be no reserved borrows in the value"; (* Call the continuation *) cf v ctx @@ -64,9 +65,9 @@ let access_rplace_reorganize_and_read (meta : Meta.meta) (config : config) (cf : typed_value -> m_fun) : m_fun = fun ctx -> (* Make sure we can evaluate the path *) - let cc = update_ctx_along_read_place config access p in + let cc = update_ctx_along_read_place meta config access p in (* End the proper loans at the place itself *) - let cc = comp cc (end_loans_at_place config access p) in + let cc = comp cc (end_loans_at_place meta config access p) in (* Expand the copyable values which contain borrows (which are necessarily shared * borrows) *) let cc = @@ -75,7 +76,7 @@ let access_rplace_reorganize_and_read (meta : Meta.meta) (config : config) else cc in (* Read the place - note that this checks that the value doesn't contain bottoms *) - let read_place = read_place access p in + let read_place = read_place meta access p in (* Compose *) comp cc read_place cf ctx @@ -87,7 +88,7 @@ let access_rplace_reorganize (meta : Meta.meta) (config : config) (expand_prim_c ctx (** Convert an operand constant operand value to a typed value *) -let literal_to_typed_value (ty : literal_type) (cv : literal) : typed_value = +let literal_to_typed_value (meta : Meta.meta) (ty : literal_type) (cv : literal) : typed_value = (* Check the type while converting - we actually need some information * contained in the type *) log#ldebug @@ -100,11 +101,11 @@ let literal_to_typed_value (ty : literal_type) (cv : literal) : typed_value = | TChar, VChar v -> { value = VLiteral (VChar v); ty = TLiteral ty } | TInteger int_ty, VScalar v -> (* Check the type and the ranges *) - assert (int_ty = v.int_ty); - assert (check_scalar_value_in_range v); + cassert (int_ty = v.int_ty) meta "Wrong type TODO: error message"; + cassert (check_scalar_value_in_range v) meta "Wrong range TODO: error message"; { value = VLiteral (VScalar v); ty = TLiteral ty } (* Remaining cases (invalid) *) - | _, _ -> raise (Failure "Improperly typed constant value") + | _, _ -> craise meta "Improperly typed constant value" (** Copy a value, and return the resulting value. @@ -117,13 +118,13 @@ let literal_to_typed_value (ty : literal_type) (cv : literal) : typed_value = parameter to control this copy ([allow_adt_copy]). Note that here by ADT we mean the user-defined ADTs (not tuples or assumed types). *) -let rec copy_value (allow_adt_copy : bool) (config : config) (ctx : eval_ctx) +let rec copy_value (meta : Meta.meta) (allow_adt_copy : bool) (config : config) (ctx : eval_ctx) (v : typed_value) : eval_ctx * typed_value = log#ldebug (lazy ("copy_value: " - ^ typed_value_to_string ctx v - ^ "\n- context:\n" ^ eval_ctx_to_string ctx)); + ^ typed_value_to_string meta ctx v + ^ "\n- context:\n" ^ eval_ctx_to_string meta ctx)); (* Remark: at some point we rewrote this function to use iterators, but then * we reverted the changes: the result was less clear actually. In particular, * the fact that we have exhaustive matches below makes very obvious the cases @@ -134,9 +135,9 @@ let rec copy_value (allow_adt_copy : bool) (config : config) (ctx : eval_ctx) (* Sanity check *) (match v.ty with | TAdt (TAssumed TBox, _) -> - raise (Failure "Can't copy an assumed value other than Option") + craise meta "Can't copy an assumed value other than Option" | TAdt (TAdtId _, _) as ty -> - assert (allow_adt_copy || ty_is_primitively_copyable ty) + cassert (allow_adt_copy || ty_is_primitively_copyable ty) meta "TODO: error message" | TAdt (TTuple, _) -> () (* Ok *) | TAdt ( TAssumed (TSlice | TArray), @@ -146,15 +147,15 @@ let rec copy_value (allow_adt_copy : bool) (config : config) (ctx : eval_ctx) const_generics = []; trait_refs = []; } ) -> - assert (ty_is_primitively_copyable ty) - | _ -> raise (Failure "Unreachable")); + cassert (ty_is_primitively_copyable ty) meta "TODO: error message" + | _ -> craise meta "Unreachable"); let ctx, fields = List.fold_left_map - (copy_value allow_adt_copy config) + (copy_value meta allow_adt_copy config) ctx av.field_values in (ctx, { v with value = VAdt { av with field_values = fields } }) - | VBottom -> raise (Failure "Can't copy ⊥") + | VBottom -> craise meta "Can't copy ⊥" | VBorrow bc -> ( (* We can only copy shared borrows *) match bc with @@ -162,24 +163,24 @@ let rec copy_value (allow_adt_copy : bool) (config : config) (ctx : eval_ctx) (* We need to create a new borrow id for the copied borrow, and * update the context accordingly *) let bid' = fresh_borrow_id () in - let ctx = InterpreterBorrows.reborrow_shared bid bid' ctx in + let ctx = InterpreterBorrows.reborrow_shared meta bid bid' ctx in (ctx, { v with value = VBorrow (VSharedBorrow bid') }) - | VMutBorrow (_, _) -> raise (Failure "Can't copy a mutable borrow") + | VMutBorrow (_, _) -> craise meta "Can't copy a mutable borrow" | VReservedMutBorrow _ -> - raise (Failure "Can't copy a reserved mut borrow")) + craise meta "Can't copy a reserved mut borrow") | VLoan lc -> ( (* We can only copy shared loans *) match lc with - | VMutLoan _ -> raise (Failure "Can't copy a mutable loan") + | VMutLoan _ -> craise meta "Can't copy a mutable loan" | VSharedLoan (_, sv) -> (* We don't copy the shared loan: only the shared value inside *) - copy_value allow_adt_copy config ctx sv) + copy_value meta allow_adt_copy config ctx sv) | VSymbolic sp -> (* We can copy only if the type is "primitively" copyable. * Note that in the general case, copy is a trait: copying values * thus requires calling the proper function. Here, we copy values * for very simple types such as integers, shared borrows, etc. *) - assert (ty_is_primitively_copyable (Substitute.erase_regions sp.sv_ty)); + cassert (ty_is_primitively_copyable (Substitute.erase_regions sp.sv_ty)) meta "Not primitively copyable"; (* If the type is copyable, we simply return the current value. Side * remark: what is important to look at when copying symbolic values * is symbolic expansion. The important subcase is the expansion of shared @@ -248,25 +249,25 @@ let prepare_eval_operand_reorganize (meta : Meta.meta) (config : config) (op : o prepare cf ctx (** Evaluate an operand, without reorganizing the context before *) -let eval_operand_no_reorganize (config : config) (op : operand) +let eval_operand_no_reorganize (meta : Meta.meta) (config : config) (op : operand) (cf : typed_value -> m_fun) : m_fun = fun ctx -> (* Debug *) log#ldebug (lazy ("eval_operand_no_reorganize: op: " ^ operand_to_string ctx op - ^ "\n- ctx:\n" ^ eval_ctx_to_string ctx ^ "\n")); + ^ "\n- ctx:\n" ^ eval_ctx_to_string meta ctx ^ "\n")); (* Evaluate *) match op with | Constant cv -> ( match cv.value with | CLiteral lit -> - cf (literal_to_typed_value (ty_as_literal cv.ty) lit) ctx + cf (literal_to_typed_value meta (ty_as_literal cv.ty) lit) ctx | CTraitConst (trait_ref, const_name) -> ( let ctx0 = ctx in (* Simply introduce a fresh symbolic value *) let ty = cv.ty in - let v = mk_fresh_symbolic_typed_value ty in + let v = mk_fresh_symbolic_typed_value meta ty in (* Continue the evaluation *) let e = cf v ctx in (* Wrap the generated expression *) @@ -277,7 +278,7 @@ let eval_operand_no_reorganize (config : config) (op : operand) (SymbolicAst.IntroSymbolic ( ctx0, None, - value_as_symbolic v.value, + value_as_symbolic meta v.value, SymbolicAst.VaTraitConstValue (trait_ref, const_name), e ))) | CVar vid -> ( @@ -294,49 +295,49 @@ let eval_operand_no_reorganize (config : config) (op : operand) | ConcreteMode -> (* Copy the value - this is more of a sanity check *) let allow_adt_copy = false in - copy_value allow_adt_copy config ctx cv + copy_value meta allow_adt_copy config ctx cv | SymbolicMode -> (* We use the looked up value only for its type *) - let v = mk_fresh_symbolic_typed_value cv.ty in + let v = mk_fresh_symbolic_typed_value meta cv.ty in (ctx, v) in (* Continue *) let e = cf cv ctx in (* If we are synthesizing a symbolic AST, it means that we are in symbolic mode: the value of the const generic is necessarily symbolic. *) - assert (e = None || is_symbolic cv.value); + cassert (e = None || is_symbolic cv.value) meta "The value of the const generic should be symbolic"; (* We have to wrap the generated expression *) match e with | None -> None | Some e -> (* If we are synthesizing a symbolic AST, it means that we are in symbolic mode: the value of the const generic is necessarily symbolic. *) - assert (is_symbolic cv.value); + cassert (is_symbolic cv.value) meta "The value of the const generic should be symbolic"; (* *) Some (SymbolicAst.IntroSymbolic ( ctx0, None, - value_as_symbolic cv.value, + value_as_symbolic meta cv.value, SymbolicAst.VaCgValue vid, e ))) - | CFnPtr _ -> raise (Failure "TODO")) + | CFnPtr _ -> craise meta "TODO") | Copy p -> (* Access the value *) let access = Read in - let cc = read_place access p in + let cc = read_place meta access p in (* Copy the value *) let copy cf v : m_fun = fun ctx -> (* Sanity checks *) - assert (not (bottom_in_value ctx.ended_regions v)); - assert ( + cassert (not (bottom_in_value ctx.ended_regions v)) meta "TODO: error message"; + cassert ( Option.is_none (find_first_primitively_copyable_sv_with_borrows - ctx.type_ctx.type_infos v)); + ctx.type_ctx.type_infos v)) meta "TODO: error message"; (* Actually perform the copy *) let allow_adt_copy = false in - let ctx, v = copy_value allow_adt_copy config ctx v in + let ctx, v = copy_value meta allow_adt_copy config ctx v in (* Continue *) cf v ctx in @@ -345,14 +346,14 @@ let eval_operand_no_reorganize (config : config) (op : operand) | Move p -> (* Access the value *) let access = Move in - let cc = read_place access p in + let cc = read_place meta access p in (* Move the value *) let move cf v : m_fun = fun ctx -> (* Check that there are no bottoms in the value we are about to move *) - assert (not (bottom_in_value ctx.ended_regions v)); + cassert (not (bottom_in_value ctx.ended_regions v)) meta "There should be no bottoms in the value we are about to move"; let bottom : typed_value = { value = VBottom; ty = v.ty } in - let ctx = write_place access p bottom ctx in + let ctx = write_place meta access p bottom ctx in cf v ctx in (* Compose and apply *) @@ -365,11 +366,11 @@ let eval_operand (meta : Meta.meta) (config : config) (op : operand) (cf : type log#ldebug (lazy ("eval_operand: op: " ^ operand_to_string ctx op ^ "\n- ctx:\n" - ^ eval_ctx_to_string ctx ^ "\n")); + ^ eval_ctx_to_string meta ctx ^ "\n")); (* We reorganize the context, then evaluate the operand *) comp (prepare_eval_operand_reorganize meta config op) - (eval_operand_no_reorganize config op) + (eval_operand_no_reorganize meta config op) cf ctx (** Small utility. @@ -388,7 +389,7 @@ let eval_operands (meta : Meta.meta) (config : config) (ops : operand list) let prepare = prepare_eval_operands_reorganize meta config ops in (* Evaluate the operands *) let eval = - fold_left_list_apply_continuation (eval_operand_no_reorganize config) ops + fold_left_list_apply_continuation (eval_operand_no_reorganize meta config) ops in (* Compose and apply *) comp prepare eval cf ctx @@ -399,7 +400,7 @@ let eval_two_operands (meta : Meta.meta) (config : config) (op1 : operand) (op2 let use_res cf res = match res with | [ v1; v2 ] -> cf (v1, v2) - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" in comp eval_op use_res cf @@ -420,7 +421,7 @@ let eval_unary_op_concrete (meta : Meta.meta) (config : config) (unop : unop) (o | ( Cast (CastScalar (TInteger src_ty, TInteger tgt_ty)), VLiteral (VScalar sv) ) -> ( (* Cast between integers *) - assert (src_ty = sv.int_ty); + cassert (src_ty = sv.int_ty) meta "TODO: error message"; let i = sv.value in match mk_scalar tgt_ty i with | Error _ -> cf (Error EPanic) @@ -442,12 +443,12 @@ let eval_unary_op_concrete (meta : Meta.meta) (config : config) (unop : unop) (o let b = if Z.of_int 0 = sv.value then false else if Z.of_int 1 = sv.value then true - else raise (Failure "Conversion from int to bool: out of range") + else craise meta "Conversion from int to bool: out of range" in let value = VLiteral (VBool b) in let ty = TLiteral TBool in cf (Ok { ty; value }) - | _ -> raise (Failure "Invalid input for unop") + | _ -> craise meta "Invalid input for unop" in comp eval_op apply cf @@ -465,7 +466,7 @@ let eval_unary_op_symbolic (meta : Meta.meta) (config : config) (unop : unop) (o | Not, (TLiteral TBool as lty) -> lty | Neg, (TLiteral (TInteger _) as lty) -> lty | Cast (CastScalar (_, tgt_ty)), _ -> TLiteral tgt_ty - | _ -> raise (Failure "Invalid input for unop") + | _ -> craise meta "Invalid input for unop" in let res_sv = { sv_id = res_sv_id; sv_ty = res_sv_ty } in (* Call the continuation *) @@ -487,15 +488,15 @@ let eval_unary_op (meta : Meta.meta) (config : config) (unop : unop) (op : opera (** Small helper for [eval_binary_op_concrete]: computes the result of applying the binop *after* the operands have been successfully evaluated *) -let eval_binary_op_concrete_compute (binop : binop) (v1 : typed_value) +let eval_binary_op_concrete_compute (meta : Meta.meta) (binop : binop) (v1 : typed_value) (v2 : typed_value) : (typed_value, eval_error) result = (* Equality check binops (Eq, Ne) accept values from a wide variety of types. * The remaining binops only operate on scalars. *) if binop = Eq || binop = Ne then ( (* Equality operations *) - assert (v1.ty = v2.ty); + cassert (v1.ty = v2.ty) meta "TODO: error message"; (* Equality/inequality check is primitive only for a subset of types *) - assert (ty_is_primitively_copyable v1.ty); + cassert (ty_is_primitively_copyable v1.ty) meta "Not primitively copyable TODO: error message"; let b = v1 = v2 in Ok { value = VLiteral (VBool b); ty = TLiteral TBool }) else @@ -510,7 +511,7 @@ let eval_binary_op_concrete_compute (binop : binop) (v1 : typed_value) match binop with | Lt | Le | Ge | Gt -> (* The two operands must have the same type and the result is a boolean *) - assert (sv1.int_ty = sv2.int_ty); + cassert (sv1.int_ty = sv2.int_ty) meta "The two operands must have the same type and the result is a boolean"; let b = match binop with | Lt -> Z.lt sv1.value sv2.value @@ -519,14 +520,14 @@ let eval_binary_op_concrete_compute (binop : binop) (v1 : typed_value) | Gt -> Z.gt sv1.value sv2.value | Div | Rem | Add | Sub | Mul | BitXor | BitAnd | BitOr | Shl | Shr | Ne | Eq -> - raise (Failure "Unreachable") + craise meta "Unreachable" in Ok ({ value = VLiteral (VBool b); ty = TLiteral TBool } : typed_value) | Div | Rem | Add | Sub | Mul | BitXor | BitAnd | BitOr -> ( (* The two operands must have the same type and the result is an integer *) - assert (sv1.int_ty = sv2.int_ty); + cassert (sv1.int_ty = sv2.int_ty) meta "The two operands must have the same type and the result is an integer"; let res = match binop with | Div -> @@ -543,7 +544,7 @@ let eval_binary_op_concrete_compute (binop : binop) (v1 : typed_value) | BitAnd -> raise Unimplemented | BitOr -> raise Unimplemented | Lt | Le | Ge | Gt | Shl | Shr | Ne | Eq -> - raise (Failure "Unreachable") + craise meta "Unreachable" in match res with | Error _ -> Error EPanic @@ -554,8 +555,8 @@ let eval_binary_op_concrete_compute (binop : binop) (v1 : typed_value) ty = TLiteral (TInteger sv1.int_ty); }) | Shl | Shr -> raise Unimplemented - | Ne | Eq -> raise (Failure "Unreachable")) - | _ -> raise (Failure "Invalid inputs for binop") + | Ne | Eq -> craise meta "Unreachable") + | _ -> craise meta "Invalid inputs for binop" let eval_binary_op_concrete (meta : Meta.meta) (config : config) (binop : binop) (op1 : operand) (op2 : operand) (cf : (typed_value, eval_error) result -> m_fun) : m_fun = @@ -564,7 +565,7 @@ let eval_binary_op_concrete (meta : Meta.meta) (config : config) (binop : binop) (* Compute the result of the binop *) let compute cf (res : typed_value * typed_value) = let v1, v2 = res in - cf (eval_binary_op_concrete_compute binop v1 v2) + cf (eval_binary_op_concrete_compute meta binop v1 v2) in (* Compose and apply *) comp eval_ops compute cf @@ -582,9 +583,9 @@ let eval_binary_op_symbolic (meta : Meta.meta) (config : config) (binop : binop) let res_sv_ty = if binop = Eq || binop = Ne then ( (* Equality operations *) - assert (v1.ty = v2.ty); + cassert (v1.ty = v2.ty) meta "TODO: error message"; (* Equality/inequality check is primitive only for a subset of types *) - assert (ty_is_primitively_copyable v1.ty); + cassert (ty_is_primitively_copyable v1.ty) meta "Not primitively copyable TODO: error message"; TLiteral TBool) else (* Other operations: input types are integers *) @@ -592,17 +593,17 @@ let eval_binary_op_symbolic (meta : Meta.meta) (config : config) (binop : binop) | TLiteral (TInteger int_ty1), TLiteral (TInteger int_ty2) -> ( match binop with | Lt | Le | Ge | Gt -> - assert (int_ty1 = int_ty2); + cassert (int_ty1 = int_ty2) meta "TODO: error message"; TLiteral TBool | Div | Rem | Add | Sub | Mul | BitXor | BitAnd | BitOr -> - assert (int_ty1 = int_ty2); + cassert (int_ty1 = int_ty2) meta "TODO: error message"; TLiteral (TInteger int_ty1) | Shl | Shr -> (* The number of bits can be of a different integer type than the operand *) TLiteral (TInteger int_ty1) - | Ne | Eq -> raise (Failure "Unreachable")) - | _ -> raise (Failure "Invalid inputs for binop") + | Ne | Eq -> craise meta "Unreachable") + | _ -> craise meta "Invalid inputs for binop" in let res_sv = { sv_id = res_sv_id; sv_ty = res_sv_ty } in (* Call the continuattion *) @@ -631,14 +632,14 @@ let eval_rvalue_ref (meta : Meta.meta) (config : config) (p : place) (bkind : bo In practice this restricted the behaviour too much, so for now we forbid them. *) - assert (bkind <> BShallow); + cassert (bkind <> BShallow) meta "Shallow borrow are currently forbidden"; (* Access the value *) let access = match bkind with | BShared | BShallow -> Read | BTwoPhaseMut -> Write - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" in let expand_prim_copy = false in @@ -663,14 +664,14 @@ let eval_rvalue_ref (meta : Meta.meta) (config : config) (p : place) (bkind : bo { v with value = v' } in (* Update the borrowed value in the context *) - let ctx = write_place access p nv ctx in + let ctx = write_place meta access p nv ctx in (* Compute the rvalue - simply a shared borrow with a the fresh id. * Note that the reference is *mutable* if we do a two-phase borrow *) let ref_kind = match bkind with | BShared | BShallow -> RShared | BTwoPhaseMut -> RMut - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" in let rv_ty = TRef (RErased, v.ty, ref_kind) in let bc = @@ -680,7 +681,7 @@ let eval_rvalue_ref (meta : Meta.meta) (config : config) (p : place) (bkind : bo handle shallow borrows like shared borrows *) VSharedBorrow bid | BTwoPhaseMut -> VReservedMutBorrow bid - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" in let rv : typed_value = { value = VBorrow bc; ty = rv_ty } in (* Continue *) @@ -707,7 +708,7 @@ let eval_rvalue_ref (meta : Meta.meta) (config : config) (p : place) (bkind : bo (* Compute the value with which to replace the value at place p *) let nv = { v with value = VLoan (VMutLoan bid) } in (* Update the value in the context *) - let ctx = write_place access p nv ctx in + let ctx = write_place meta access p nv ctx in (* Continue *) cf rv ctx in @@ -736,16 +737,16 @@ let eval_rvalue_aggregate (meta : Meta.meta) (config : config) (aggregate_kind : | TAdtId def_id -> (* Sanity checks *) let type_decl = ctx_lookup_type_decl ctx def_id in - assert ( + cassert ( List.length type_decl.generics.regions - = List.length generics.regions); + = List.length generics.regions) meta "TODO: error message"; let expected_field_types = AssociatedTypes.ctx_adt_get_inst_norm_field_etypes ctx def_id opt_variant_id generics in - assert ( + cassert ( expected_field_types - = List.map (fun (v : typed_value) -> v.ty) values); + = List.map (fun (v : typed_value) -> v.ty) values) meta "TODO: error message"; (* Construct the value *) let av : adt_value = { variant_id = opt_variant_id; field_values = values } @@ -754,13 +755,13 @@ let eval_rvalue_aggregate (meta : Meta.meta) (config : config) (aggregate_kind : let aggregated : typed_value = { value = VAdt av; ty = aty } in (* Call the continuation *) cf aggregated ctx - | TAssumed _ -> raise (Failure "Unreachable")) + | TAssumed _ -> craise meta "Unreachable") | AggregatedArray (ety, cg) -> ( (* Sanity check: all the values have the proper type *) - assert (List.for_all (fun (v : typed_value) -> v.ty = ety) values); + cassert (List.for_all (fun (v : typed_value) -> v.ty = ety) values) meta "All the values do not have the proper type"; (* Sanity check: the number of values is consistent with the length *) let len = (literal_as_scalar (const_generic_as_literal cg)).value in - assert (len = Z.of_int (List.length values)); + cassert (len = Z.of_int (List.length values)) meta "The number of values is not consistent with the length"; let generics = TypesUtils.mk_generic_args [] [ ety ] [ cg ] [] in let ty = TAdt (TAssumed TArray, generics) in (* In order to generate a better AST, we introduce a symbolic @@ -768,15 +769,15 @@ let eval_rvalue_aggregate (meta : Meta.meta) (config : config) (aggregate_kind : array we introduce here might be duplicated in the generated code: by introducing a symbolic value we introduce a let-binding in the generated code. *) - let saggregated = mk_fresh_symbolic_typed_value ty in + let saggregated = mk_fresh_symbolic_typed_value meta ty in (* Call the continuation *) match cf saggregated ctx with | None -> None | Some e -> (* Introduce the symbolic value in the AST *) - let sv = ValuesUtils.value_as_symbolic saggregated.value in + let sv = ValuesUtils.value_as_symbolic meta saggregated.value in Some (SymbolicAst.IntroSymbolic (ctx, None, sv, VaArray values, e))) - | AggregatedClosure _ -> raise (Failure "Closures are not supported yet") + | AggregatedClosure _ -> craise meta "Closures are not supported yet" in (* Compose and apply *) comp eval_ops compute cf @@ -800,11 +801,11 @@ let eval_rvalue_not_global (meta : Meta.meta) (config : config) (rvalue : rvalue | Aggregate (aggregate_kind, ops) -> comp_wrap (eval_rvalue_aggregate meta config aggregate_kind ops) ctx | Discriminant _ -> - raise - (Failure + craise + meta "Unreachable: discriminant reads should have been eliminated from \ - the AST") - | Global _ -> raise (Failure "Unreachable") + the AST" + | Global _ -> craise meta "Unreachable" let eval_fake_read (meta : Meta.meta) (config : config) (p : place) : cm_fun = fun cf ctx -> @@ -814,7 +815,7 @@ let eval_fake_read (meta : Meta.meta) (config : config) (p : place) : cm_fun = in let cf_continue cf v : m_fun = fun ctx -> - assert (not (bottom_in_value ctx.ended_regions v)); + cassert (not (bottom_in_value ctx.ended_regions v)) meta "TODO: error message"; cf ctx in comp cf_prepare cf_continue cf ctx diff --git a/compiler/InterpreterExpressions.mli b/compiler/InterpreterExpressions.mli index b975371c..69455682 100644 --- a/compiler/InterpreterExpressions.mli +++ b/compiler/InterpreterExpressions.mli @@ -12,7 +12,7 @@ open InterpreterPaths This function doesn't reorganize the context to make sure we can read the place. If needs be, you should call {!InterpreterPaths.update_ctx_along_read_place} first. *) -val read_place : access_kind -> place -> (typed_value -> m_fun) -> m_fun +val read_place : Meta.meta -> access_kind -> place -> (typed_value -> m_fun) -> m_fun (** Auxiliary function. @@ -31,7 +31,7 @@ val read_place : access_kind -> place -> (typed_value -> m_fun) -> m_fun primitively copyable and contain borrows. *) val access_rplace_reorganize_and_read : - config -> bool -> access_kind -> place -> (typed_value -> m_fun) -> m_fun + Meta.meta -> config -> bool -> access_kind -> place -> (typed_value -> m_fun) -> m_fun (** Evaluate an operand. @@ -42,11 +42,11 @@ val access_rplace_reorganize_and_read : of the environment, before evaluating all the operands at once. Use {!eval_operands} instead. *) -val eval_operand : config -> operand -> (typed_value -> m_fun) -> m_fun +val eval_operand : Meta.meta -> config -> operand -> (typed_value -> m_fun) -> m_fun (** Evaluate several operands at once. *) val eval_operands : - config -> operand list -> (typed_value list -> m_fun) -> m_fun + Meta.meta -> config -> operand list -> (typed_value list -> m_fun) -> m_fun (** Evaluate an rvalue which is not a global (globals are handled elsewhere). @@ -56,7 +56,7 @@ val eval_operands : reads should have been eliminated from the AST. *) val eval_rvalue_not_global : - config -> rvalue -> ((typed_value, eval_error) result -> m_fun) -> m_fun + Meta.meta -> config -> rvalue -> ((typed_value, eval_error) result -> m_fun) -> m_fun (** Evaluate a fake read (update the context so that we can read a place) *) -val eval_fake_read : config -> place -> cm_fun +val eval_fake_read : Meta.meta -> config -> place -> cm_fun diff --git a/compiler/InterpreterLoops.ml b/compiler/InterpreterLoops.ml index afbe0501..98aa0e14 100644 --- a/compiler/InterpreterLoops.ml +++ b/compiler/InterpreterLoops.ml @@ -9,12 +9,13 @@ open InterpreterUtils open InterpreterLoopsCore open InterpreterLoopsMatchCtxs open InterpreterLoopsFixedPoint +open Errors (** The local logger *) let log = Logging.loops_log (** Evaluate a loop in concrete mode *) -let eval_loop_concrete (eval_loop_body : st_cm_fun) : st_cm_fun = +let eval_loop_concrete (meta : Meta.meta) (eval_loop_body : st_cm_fun) : st_cm_fun = fun cf ctx -> (* We need a loop id for the [LoopReturn]. In practice it won't be used (it is useful only for the symbolic execution *) @@ -52,10 +53,10 @@ let eval_loop_concrete (eval_loop_body : st_cm_fun) : st_cm_fun = * {!Unit} would account for the first iteration of the loop. * We prefer to write it this way for consistency and sanity, * though. *) - raise (Failure "Unreachable") + craise meta "Unreachable" | LoopReturn _ | EndEnterLoop _ | EndContinue _ -> (* We can't get there: this is only used in symbolic mode *) - raise (Failure "Unreachable") + craise meta "Unreachable" in (* Apply *) @@ -67,24 +68,24 @@ let eval_loop_symbolic (config : config) (meta : meta) fun cf ctx -> (* Debug *) log#ldebug - (lazy ("eval_loop_symbolic:\nContext:\n" ^ eval_ctx_to_string ctx ^ "\n\n")); + (lazy ("eval_loop_symbolic:\nContext:\n" ^ eval_ctx_to_string meta ctx ^ "\n\n")); (* Generate a fresh loop id *) let loop_id = fresh_loop_id () in (* Compute the fixed point at the loop entrance *) let fp_ctx, fixed_ids, rg_to_abs = - compute_loop_entry_fixed_point config loop_id eval_loop_body ctx + compute_loop_entry_fixed_point meta config loop_id eval_loop_body ctx in (* Debug *) log#ldebug (lazy - ("eval_loop_symbolic:\nInitial context:\n" ^ eval_ctx_to_string ctx - ^ "\n\nFixed point:\n" ^ eval_ctx_to_string fp_ctx)); + ("eval_loop_symbolic:\nInitial context:\n" ^ eval_ctx_to_string meta ctx + ^ "\n\nFixed point:\n" ^ eval_ctx_to_string meta fp_ctx)); (* Compute the loop input parameters *) - let fresh_sids, input_svalues = compute_fp_ctx_symbolic_values ctx fp_ctx in + let fresh_sids, input_svalues = compute_fp_ctx_symbolic_values meta ctx fp_ctx in let fp_input_svalues = List.map (fun sv -> sv.sv_id) input_svalues in (* Synthesize the end of the function - we simply match the context at the @@ -115,16 +116,16 @@ let eval_loop_symbolic (config : config) (meta : meta) (* Compute the id correspondance between the contexts *) let fp_bl_corresp = - compute_fixed_point_id_correspondance fixed_ids ctx fp_ctx + compute_fixed_point_id_correspondance meta fixed_ids ctx fp_ctx in log#ldebug (lazy ("eval_loop_symbolic: about to match the fixed-point context with the \ original context:\n\ - - src ctx (fixed-point ctx)" ^ eval_ctx_to_string fp_ctx - ^ "\n\n-tgt ctx (original context):\n" ^ eval_ctx_to_string ctx)); + - src ctx (fixed-point ctx)" ^ eval_ctx_to_string meta fp_ctx + ^ "\n\n-tgt ctx (original context):\n" ^ eval_ctx_to_string meta ctx)); let end_expr : SymbolicAst.expression option = - match_ctx_with_target config loop_id true fp_bl_corresp fp_input_svalues + match_ctx_with_target meta config loop_id true fp_bl_corresp fp_input_svalues fixed_ids fp_ctx cf ctx in log#ldebug @@ -149,15 +150,15 @@ let eval_loop_symbolic (config : config) (meta : meta) cf res ctx | Continue i -> (* We don't support nested loops for now *) - assert (i = 0); + cassert (i = 0) meta "Nested loops are not supported yet"; log#ldebug (lazy ("eval_loop_symbolic: about to match the fixed-point context \ with the context at a continue:\n\ - - src ctx (fixed-point ctx)" ^ eval_ctx_to_string fp_ctx - ^ "\n\n-tgt ctx (ctx at continue):\n" ^ eval_ctx_to_string ctx)); + - src ctx (fixed-point ctx)" ^ eval_ctx_to_string meta fp_ctx + ^ "\n\n-tgt ctx (ctx at continue):\n" ^ eval_ctx_to_string meta ctx)); let cc = - match_ctx_with_target config loop_id false fp_bl_corresp + match_ctx_with_target meta config loop_id false fp_bl_corresp fp_input_svalues fixed_ids fp_ctx in cc cf ctx @@ -165,16 +166,16 @@ let eval_loop_symbolic (config : config) (meta : meta) (* For why we can't get [Unit], see the comments inside {!eval_loop_concrete}. For [EndEnterLoop] and [EndContinue]: we don't support nested loops for now. *) - raise (Failure "Unreachable") + craise meta "Unreachable" in let loop_expr = eval_loop_body cf_loop fp_ctx in log#ldebug (lazy ("eval_loop_symbolic: result:" ^ "\n- src context:\n" - ^ eval_ctx_to_string_no_filter ctx + ^ eval_ctx_to_string_no_filter meta ctx ^ "\n- fixed point:\n" - ^ eval_ctx_to_string_no_filter fp_ctx + ^ eval_ctx_to_string_no_filter meta fp_ctx ^ "\n- fixed_sids: " ^ SymbolicValueId.Set.show fixed_ids.sids ^ "\n- fresh_sids: " @@ -199,7 +200,7 @@ let eval_loop_symbolic (config : config) (meta : meta) match av.value with | ABorrow _ -> true | ALoan _ -> false - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" in let borrows, loans = List.partition is_borrow abs.avalues in @@ -208,10 +209,10 @@ let eval_loop_symbolic (config : config) (meta : meta) (fun (av : typed_avalue) -> match av.value with | ABorrow (AMutBorrow (bid, child_av)) -> - assert (is_aignored child_av.value); + cassert (is_aignored child_av.value) meta "TODO: error message"; Some (bid, child_av.ty) | ABorrow (ASharedBorrow _) -> None - | _ -> raise (Failure "Unreachable")) + | _ -> craise meta "Unreachable") borrows in let borrows = ref (BorrowId.Map.of_list borrows) in @@ -221,10 +222,10 @@ let eval_loop_symbolic (config : config) (meta : meta) (fun (av : typed_avalue) -> match av.value with | ALoan (AMutLoan (bid, child_av)) -> - assert (is_aignored child_av.value); + cassert (is_aignored child_av.value) meta "TODO: error message"; Some bid | ALoan (ASharedLoan _) -> None - | _ -> raise (Failure "Unreachable")) + | _ -> craise meta "Unreachable") loans in @@ -240,7 +241,7 @@ let eval_loop_symbolic (config : config) (meta : meta) ty) loan_ids in - assert (BorrowId.Map.is_empty !borrows); + cassert (BorrowId.Map.is_empty !borrows) meta "TODO: error message"; given_back_tys in @@ -259,7 +260,7 @@ let eval_loop (config : config) (meta : meta) (eval_loop_body : st_cm_fun) : st_cm_fun = fun cf ctx -> match config.mode with - | ConcreteMode -> eval_loop_concrete eval_loop_body cf ctx + | ConcreteMode -> eval_loop_concrete meta eval_loop_body cf ctx | SymbolicMode -> (* Simplify the context by ending the unnecessary borrows/loans and getting rid of the useless symbolic values (which are in anonymous variables) *) @@ -283,5 +284,5 @@ let eval_loop (config : config) (meta : meta) (eval_loop_body : st_cm_fun) : introduce *fixed* abstractions, and again later to introduce *non-fixed* abstractions. *) - let cc = comp cc (prepare_ashared_loans None) in + let cc = comp cc (prepare_ashared_loans meta None) in comp cc (eval_loop_symbolic config meta eval_loop_body) cf ctx diff --git a/compiler/InterpreterLoopsCore.ml b/compiler/InterpreterLoopsCore.ml index 0bd57756..3e887741 100644 --- a/compiler/InterpreterLoopsCore.ml +++ b/compiler/InterpreterLoopsCore.ml @@ -4,6 +4,7 @@ open Types open Values open Contexts open InterpreterUtils +open Errors type updt_env_kind = | AbsInLeft of AbstractionId.id @@ -57,11 +58,11 @@ module type PrimMatcher = sig (** The input primitive values are not equal *) val match_distinct_literals : - eval_ctx -> eval_ctx -> ety -> literal -> literal -> typed_value + Meta.meta -> eval_ctx -> eval_ctx -> ety -> literal -> literal -> typed_value (** The input ADTs don't have the same variant *) val match_distinct_adts : - eval_ctx -> eval_ctx -> ety -> adt_value -> adt_value -> typed_value + Meta.meta -> eval_ctx -> eval_ctx -> ety -> adt_value -> adt_value -> typed_value (** The meta-value is the result of a match. @@ -74,6 +75,7 @@ module type PrimMatcher = sig calling the match function. *) val match_shared_borrows : + Meta.meta -> eval_ctx -> eval_ctx -> (typed_value -> typed_value -> typed_value) -> @@ -91,6 +93,7 @@ module type PrimMatcher = sig - [bv]: the result of matching [bv0] with [bv1] *) val match_mut_borrows : + Meta.meta -> eval_ctx -> eval_ctx -> ety -> @@ -121,7 +124,7 @@ module type PrimMatcher = sig (** There are no constraints on the input symbolic values *) val match_symbolic_values : - eval_ctx -> eval_ctx -> symbolic_value -> symbolic_value -> symbolic_value + Meta.meta -> eval_ctx -> eval_ctx -> symbolic_value -> symbolic_value -> symbolic_value (** Match a symbolic value with a value which is not symbolic. @@ -131,7 +134,7 @@ module type PrimMatcher = sig end loans in one of the two environments). *) val match_symbolic_with_other : - eval_ctx -> eval_ctx -> bool -> symbolic_value -> typed_value -> typed_value + Meta.meta -> eval_ctx -> eval_ctx -> bool -> symbolic_value -> typed_value -> typed_value (** Match a bottom value with a value which is not bottom. @@ -141,10 +144,11 @@ module type PrimMatcher = sig end loans in one of the two environments). *) val match_bottom_with_other : - eval_ctx -> eval_ctx -> bool -> typed_value -> typed_value + Meta.meta -> eval_ctx -> eval_ctx -> bool -> typed_value -> typed_value (** The input ADTs don't have the same variant *) val match_distinct_aadts : + Meta.meta -> eval_ctx -> eval_ctx -> rty -> @@ -162,6 +166,7 @@ module type PrimMatcher = sig [ty]: result of matching ty0 and ty1 *) val match_ashared_borrows : + Meta.meta -> eval_ctx -> eval_ctx -> rty -> @@ -182,6 +187,7 @@ module type PrimMatcher = sig [av]: result of matching av0 and av1 *) val match_amut_borrows : + Meta.meta -> eval_ctx -> eval_ctx -> rty -> @@ -208,6 +214,7 @@ module type PrimMatcher = sig [av]: result of matching av0 and av1 *) val match_ashared_loans : + Meta.meta -> eval_ctx -> eval_ctx -> rty -> @@ -234,6 +241,7 @@ module type PrimMatcher = sig [av]: result of matching av0 and av1 *) val match_amut_loans : + Meta.meta -> eval_ctx -> eval_ctx -> rty -> @@ -250,7 +258,7 @@ module type PrimMatcher = sig is typically used to raise the proper exception). *) val match_avalues : - eval_ctx -> eval_ctx -> typed_avalue -> typed_avalue -> typed_avalue + Meta.meta -> eval_ctx -> eval_ctx -> typed_avalue -> typed_avalue -> typed_avalue end module type Matcher = sig @@ -259,14 +267,14 @@ module type Matcher = sig Rem.: this function raises exceptions of type {!Aeneas.InterpreterLoopsCore.ValueMatchFailure}. *) val match_typed_values : - eval_ctx -> eval_ctx -> typed_value -> typed_value -> typed_value + Meta.meta -> eval_ctx -> eval_ctx -> typed_value -> typed_value -> typed_value (** Match two avalues. Rem.: this function raises exceptions of type {!Aeneas.InterpreterLoopsCore.ValueMatchFailure}. *) val match_typed_avalues : - eval_ctx -> eval_ctx -> typed_avalue -> typed_avalue -> typed_avalue + Meta.meta -> eval_ctx -> eval_ctx -> typed_avalue -> typed_avalue -> typed_avalue end (** See {!module:InterpreterLoopsMatchCtxs.MakeCheckEquivMatcher} and @@ -351,7 +359,7 @@ end Returns: (fixed, new abs, new dummies) *) -let ctx_split_fixed_new (fixed_ids : ids_sets) (ctx : eval_ctx) : +let ctx_split_fixed_new (meta : Meta.meta) (fixed_ids : ids_sets) (ctx : eval_ctx) : env * abs list * typed_value list = let is_fresh_did (id : DummyVarId.id) : bool = not (DummyVarId.Set.mem id fixed_ids.dids) @@ -373,7 +381,7 @@ let ctx_split_fixed_new (fixed_ids : ids_sets) (ctx : eval_ctx) : let new_absl = List.map (fun ee -> - match ee with EAbs abs -> abs | _ -> raise (Failure "Unreachable")) + match ee with EAbs abs -> abs | _ -> craise meta "Unreachable") new_absl in let new_dummyl = @@ -381,7 +389,7 @@ let ctx_split_fixed_new (fixed_ids : ids_sets) (ctx : eval_ctx) : (fun ee -> match ee with | EBinding (BDummy _, v) -> v - | _ -> raise (Failure "Unreachable")) + | _ -> craise meta "Unreachable") new_dummyl in (filt_env, new_absl, new_dummyl) diff --git a/compiler/InterpreterLoopsFixedPoint.ml b/compiler/InterpreterLoopsFixedPoint.ml index 35582456..508d0f0c 100644 --- a/compiler/InterpreterLoopsFixedPoint.ml +++ b/compiler/InterpreterLoopsFixedPoint.ml @@ -215,7 +215,7 @@ let prepare_ashared_loans (meta : Meta.meta) (loop_id : LoopId.id option) : cm_f (* Remove the shared loans *) let v = value_remove_shared_loans v in (* Substitute the symbolic values and the region *) - Substitute.typed_value_subst_ids + Substitute.typed_value_subst_ids meta (fun r -> if RegionId.Set.mem r rids then nrid else r) (fun x -> x) (fun x -> x) @@ -267,9 +267,9 @@ let prepare_ashared_loans (meta : Meta.meta) (loop_id : LoopId.id option) : cm_f borrow_substs := (lid, nlid) :: !borrow_substs; (* Rem.: the below sanity checks are not really necessary *) - cassert (AbstractionId.Set.is_empty abs.parents) meta "abs.parents is not empty TODO"; - cassert (abs.original_parents = []) meta "original_parents is not empty TODO"; - cassert (RegionId.Set.is_empty abs.ancestors_regions) meta "ancestors_regions is not empty TODO"; + cassert (AbstractionId.Set.is_empty abs.parents) meta "abs.parents is not empty TODO: Error message"; + cassert (abs.original_parents = []) meta "original_parents is not empty TODO: Error message"; + cassert (RegionId.Set.is_empty abs.ancestors_regions) meta "ancestors_regions is not empty TODO: Error message"; (* Introduce the new abstraction for the shared values *) cassert (ty_no_regions sv.ty) meta "TODO : error message "; @@ -277,19 +277,19 @@ let prepare_ashared_loans (meta : Meta.meta) (loop_id : LoopId.id option) : cm_f (* Create the shared loan child *) let child_rty = rty in - let child_av = mk_aignored child_rty in + let child_av = mk_aignored meta child_rty in (* Create the shared loan *) let loan_rty = TRef (RFVar nrid, rty, RShared) in let loan_value = ALoan (ASharedLoan (BorrowId.Set.singleton nlid, nsv, child_av)) in - let loan_value = mk_typed_avalue loan_rty loan_value in + let loan_value = mk_typed_avalue meta loan_rty loan_value in (* Create the shared borrow *) let borrow_rty = loan_rty in let borrow_value = ABorrow (ASharedBorrow lid) in - let borrow_value = mk_typed_avalue borrow_rty borrow_value in + let borrow_value = mk_typed_avalue meta borrow_rty borrow_value in (* Create the abstraction *) let avalues = [ borrow_value; loan_value ] in @@ -435,7 +435,7 @@ let prepare_ashared_loans (meta : Meta.meta) (loop_id : LoopId.id option) : cm_f let prepare_ashared_loans_no_synth (meta : Meta.meta) (loop_id : LoopId.id) (ctx : eval_ctx) : eval_ctx = - get_cf_ctx_no_synth (prepare_ashared_loans meta (Some loop_id)) ctx + get_cf_ctx_no_synth meta (prepare_ashared_loans meta (Some loop_id)) ctx let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id : LoopId.id) (eval_loop_body : st_cm_fun) (ctx0 : eval_ctx) : @@ -461,9 +461,9 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id (lazy ("compute_loop_entry_fixed_point: after prepare_ashared_loans:" ^ "\n\n- ctx0:\n" - ^ eval_ctx_to_string_no_filter ctx0 + ^ eval_ctx_to_string_no_filter meta ctx0 ^ "\n\n- ctx1:\n" - ^ eval_ctx_to_string_no_filter ctx + ^ eval_ctx_to_string_no_filter meta ctx ^ "\n\n")); let cf_exit_loop_body (res : statement_eval_res) : m_fun = @@ -510,10 +510,10 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id (* End those borrows and abstractions *) let end_borrows_abs blids aids ctx = let ctx = - InterpreterBorrows.end_borrows_no_synth config blids ctx + InterpreterBorrows.end_borrows_no_synth meta config blids ctx in let ctx = - InterpreterBorrows.end_abstractions_no_synth config aids ctx + InterpreterBorrows.end_abstractions_no_synth meta config aids ctx in ctx in @@ -544,7 +544,7 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id (* Join the context with the context at the loop entry *) let (_, _), ctx2 = - loop_join_origin_with_continue_ctxs config loop_id fixed_ids ctx1 !ctxs + loop_join_origin_with_continue_ctxs meta config loop_id fixed_ids ctx1 !ctxs in ctxs := []; ctx2 @@ -576,7 +576,7 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id let check_equivalent = true in let lookup_shared_value _ = craise meta "Unreachable" in Option.is_some - (match_ctxs check_equivalent fixed_ids lookup_shared_value + (match_ctxs meta check_equivalent fixed_ids lookup_shared_value lookup_shared_value ctx1 ctx2) in let max_num_iter = Config.loop_fixed_point_max_num_iters in @@ -597,9 +597,9 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id log#ldebug (lazy ("compute_fixed_point:" ^ "\n\n- ctx0:\n" - ^ eval_ctx_to_string_no_filter ctx + ^ eval_ctx_to_string_no_filter meta ctx ^ "\n\n- ctx1:\n" - ^ eval_ctx_to_string_no_filter ctx1 + ^ eval_ctx_to_string_no_filter meta ctx1 ^ "\n\n")); (* Check if we reached a fixed point: if not, iterate *) @@ -612,7 +612,7 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id (lazy ("compute_fixed_point: fixed point computed before matching with input \ region groups:" ^ "\n\n- fp:\n" - ^ eval_ctx_to_string_no_filter fp + ^ eval_ctx_to_string_no_filter meta fp ^ "\n\n")); (* Make sure we have exactly one loop abstraction per function region (merge @@ -699,7 +699,7 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id abs.kind = SynthInput rg_id) meta "TODO : error message "; (* End this abstraction *) let ctx = - InterpreterBorrows.end_abstraction_no_synth config abs_id ctx + InterpreterBorrows.end_abstraction_no_synth meta config abs_id ctx in (* Explore the context, and check which abstractions are not there anymore *) let ids, _ = compute_ctx_ids ctx in @@ -725,7 +725,7 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id (* We also check that all the regions need to end - this is not necessary per se, but if it doesn't happen it is bizarre and worth investigating... *) - cassert (AbstractionId.Set.equal !aids_union !fp_aids) meta "Not all regions need to end TODO"; + cassert (AbstractionId.Set.equal !aids_union !fp_aids) meta "Not all regions need to end TODO: Error message"; (* Merge the abstractions which need to be merged, and compute the map from region id to abstraction id *) @@ -777,7 +777,7 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id ^ AbstractionId.to_string !id0)); (* Note that we merge *into* [id0] *) let fp', id0' = - merge_into_abstraction loop_id abs_kind false !fp id !id0 + merge_into_abstraction meta loop_id abs_kind false !fp id !id0 in fp := fp'; id0 := id0'; @@ -793,7 +793,7 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id (* Reorder the loans and borrows in the fresh abstractions in the fixed-point *) let fp = - reorder_loans_borrows_in_fresh_abs (meta : Meta.meta) (Option.get !fixed_ids).aids !fp + reorder_loans_borrows_in_fresh_abs meta (Option.get !fixed_ids).aids !fp in (* Update the abstraction's [can_end] field and their kinds. @@ -838,7 +838,7 @@ let compute_loop_entry_fixed_point (meta : Meta.meta) (config : config) (loop_id (lazy ("compute_fixed_point: fixed point after matching with the function \ region groups:\n" - ^ eval_ctx_to_string_no_filter fp_test)); + ^ eval_ctx_to_string_no_filter meta fp_test)); compute_fixed_point fp_test 1 1 in @@ -855,21 +855,21 @@ let compute_fixed_point_id_correspondance (meta : Meta.meta) (fixed_ids : ids_se log#ldebug (lazy ("compute_fixed_point_id_correspondance:\n\n- fixed_ids:\n" - ^ show_ids_sets fixed_ids ^ "\n\n- src_ctx:\n" ^ eval_ctx_to_string src_ctx - ^ "\n\n- tgt_ctx:\n" ^ eval_ctx_to_string tgt_ctx ^ "\n\n")); + ^ show_ids_sets fixed_ids ^ "\n\n- src_ctx:\n" ^ eval_ctx_to_string meta src_ctx + ^ "\n\n- tgt_ctx:\n" ^ eval_ctx_to_string meta tgt_ctx ^ "\n\n")); - let filt_src_env, _, _ = ctx_split_fixed_new fixed_ids src_ctx in + let filt_src_env, _, _ = ctx_split_fixed_new meta fixed_ids src_ctx in let filt_src_ctx = { src_ctx with env = filt_src_env } in - let filt_tgt_env, new_absl, _ = ctx_split_fixed_new fixed_ids tgt_ctx in + let filt_tgt_env, new_absl, _ = ctx_split_fixed_new meta fixed_ids tgt_ctx in let filt_tgt_ctx = { tgt_ctx with env = filt_tgt_env } in log#ldebug (lazy ("compute_fixed_point_id_correspondance:\n\n- fixed_ids:\n" ^ show_ids_sets fixed_ids ^ "\n\n- filt_src_ctx:\n" - ^ eval_ctx_to_string filt_src_ctx + ^ eval_ctx_to_string meta filt_src_ctx ^ "\n\n- filt_tgt_ctx:\n" - ^ eval_ctx_to_string filt_tgt_ctx + ^ eval_ctx_to_string meta filt_tgt_ctx ^ "\n\n")); (* Match the source context and the filtered target context *) @@ -886,7 +886,7 @@ let compute_fixed_point_id_correspondance (meta : Meta.meta) (fixed_ids : ids_se let lookup_in_tgt id = lookup_shared_loan id tgt_ctx in let lookup_in_src id = lookup_shared_loan id src_ctx in Option.get - (match_ctxs check_equiv fixed_ids lookup_in_tgt lookup_in_src filt_tgt_ctx + (match_ctxs meta check_equiv fixed_ids lookup_in_tgt lookup_in_src filt_tgt_ctx filt_src_ctx) in @@ -1089,9 +1089,9 @@ let compute_fp_ctx_symbolic_values (meta : Meta.meta) (ctx : eval_ctx) (fp_ctx : log#ldebug (lazy ("compute_fp_ctx_symbolic_values:" ^ "\n- src context:\n" - ^ eval_ctx_to_string_no_filter ctx + ^ eval_ctx_to_string_no_filter meta ctx ^ "\n- fixed point:\n" - ^ eval_ctx_to_string_no_filter fp_ctx + ^ eval_ctx_to_string_no_filter meta fp_ctx ^ "\n- fresh_sids: " ^ SymbolicValueId.Set.show fresh_sids ^ "\n- input_svalues: " diff --git a/compiler/InterpreterLoopsFixedPoint.mli b/compiler/InterpreterLoopsFixedPoint.mli index 7c3f6199..d727e9bd 100644 --- a/compiler/InterpreterLoopsFixedPoint.mli +++ b/compiler/InterpreterLoopsFixedPoint.mli @@ -60,7 +60,7 @@ val cleanup_fresh_values_and_abs : config -> ids_sets -> Cps.cm_fun we only introduce a fresh abstraction for [l1]. *) -val prepare_ashared_loans : loop_id option -> Cps.cm_fun +val prepare_ashared_loans : Meta.meta -> loop_id option -> Cps.cm_fun (** Compute a fixed-point for the context at the entry of the loop. We also return: @@ -77,6 +77,7 @@ val prepare_ashared_loans : loop_id option -> Cps.cm_fun the values which are read or modified (some symbolic values may be ignored). *) val compute_loop_entry_fixed_point : + Meta.meta -> config -> loop_id -> Cps.st_cm_fun -> @@ -160,7 +161,7 @@ val compute_loop_entry_fixed_point : through the loan [l1] is actually the value which has to be given back to [l0]. *) val compute_fixed_point_id_correspondance : - ids_sets -> eval_ctx -> eval_ctx -> borrow_loan_corresp + Meta.meta -> ids_sets -> eval_ctx -> eval_ctx -> borrow_loan_corresp (** Compute the set of "quantified" symbolic value ids in a fixed-point context. @@ -169,4 +170,4 @@ val compute_fixed_point_id_correspondance : - the list of input symbolic values *) val compute_fp_ctx_symbolic_values : - eval_ctx -> eval_ctx -> symbolic_value_id_set * symbolic_value list + Meta.meta -> eval_ctx -> eval_ctx -> symbolic_value_id_set * symbolic_value list diff --git a/compiler/InterpreterLoopsJoinCtxs.ml b/compiler/InterpreterLoopsJoinCtxs.ml index fc2a97e5..ef4807e4 100644 --- a/compiler/InterpreterLoopsJoinCtxs.ml +++ b/compiler/InterpreterLoopsJoinCtxs.ml @@ -136,7 +136,7 @@ let collapse_ctx (meta : Meta.meta) (loop_id : LoopId.id) log#ldebug (lazy ("collapse_ctx:\n\n- fixed_ids:\n" ^ show_ids_sets old_ids - ^ "\n\n- ctx0:\n" ^ eval_ctx_to_string ctx0 ^ "\n\n")); + ^ "\n\n- ctx0:\n" ^ eval_ctx_to_string meta ctx0 ^ "\n\n")); let abs_kind : abs_kind = Loop (loop_id, None, LoopSynthInput) in let can_end = true in @@ -160,7 +160,7 @@ let collapse_ctx (meta : Meta.meta) (loop_id : LoopId.id) | EBinding (BDummy id, v) -> if is_fresh_did id then let absl = - convert_value_to_abstractions abs_kind can_end + convert_value_to_abstractions meta abs_kind can_end destructure_shared_values ctx0 v in List.map (fun abs -> EAbs abs) absl @@ -171,19 +171,19 @@ let collapse_ctx (meta : Meta.meta) (loop_id : LoopId.id) log#ldebug (lazy ("collapse_ctx: after converting values to abstractions:\n" - ^ show_ids_sets old_ids ^ "\n\n- ctx:\n" ^ eval_ctx_to_string ctx ^ "\n\n" + ^ show_ids_sets old_ids ^ "\n\n- ctx:\n" ^ eval_ctx_to_string meta ctx ^ "\n\n" )); log#ldebug (lazy ("collapse_ctx: after decomposing the shared values in the abstractions:\n" - ^ show_ids_sets old_ids ^ "\n\n- ctx:\n" ^ eval_ctx_to_string ctx ^ "\n\n" + ^ show_ids_sets old_ids ^ "\n\n- ctx:\n" ^ eval_ctx_to_string meta ctx ^ "\n\n" )); (* Explore all the *new* abstractions, and compute various maps *) let explore (abs : abs) = is_fresh_abs_id abs.abs_id in let ids_maps = - compute_abs_borrows_loans_maps (merge_funs = None) explore env + compute_abs_borrows_loans_maps meta (merge_funs = None) explore env in let { abs_ids; @@ -252,12 +252,12 @@ let collapse_ctx (meta : Meta.meta) (loop_id : LoopId.id) ^ AbstractionId.to_string abs_id1 ^ " into " ^ AbstractionId.to_string abs_id0 - ^ ":\n\n" ^ eval_ctx_to_string !ctx)); + ^ ":\n\n" ^ eval_ctx_to_string meta !ctx)); (* Update the environment - pay attention to the order: we we merge [abs_id1] *into* [abs_id0] *) let nctx, abs_id = - merge_into_abstraction abs_kind can_end merge_funs !ctx + merge_into_abstraction meta abs_kind can_end merge_funs !ctx abs_id1 abs_id0 in ctx := nctx; @@ -272,7 +272,7 @@ let collapse_ctx (meta : Meta.meta) (loop_id : LoopId.id) log#ldebug (lazy ("collapse_ctx:\n\n- fixed_ids:\n" ^ show_ids_sets old_ids - ^ "\n\n- after collapse:\n" ^ eval_ctx_to_string !ctx ^ "\n\n")); + ^ "\n\n- after collapse:\n" ^ eval_ctx_to_string meta !ctx ^ "\n\n")); (* Reorder the loans and borrows in the fresh abstractions *) let ctx = reorder_loans_borrows_in_fresh_abs meta old_ids.aids !ctx in @@ -281,7 +281,7 @@ let collapse_ctx (meta : Meta.meta) (loop_id : LoopId.id) (lazy ("collapse_ctx:\n\n- fixed_ids:\n" ^ show_ids_sets old_ids ^ "\n\n- after collapse and reorder borrows/loans:\n" - ^ eval_ctx_to_string ctx ^ "\n\n")); + ^ eval_ctx_to_string meta ctx ^ "\n\n")); (* Return the new context *) ctx @@ -360,7 +360,7 @@ let mk_collapse_ctx_merge_duplicate_funs (meta : Meta.meta) (loop_id : LoopId.id cassert (not (value_has_loans_or_borrows ctx sv1.value)) meta ""; let ty = ty0 in let child = child0 in - let sv = M.match_typed_values ctx ctx sv0 sv1 in + let sv = M.match_typed_values meta ctx ctx sv0 sv1 in let value = ALoan (ASharedLoan (ids, sv, child)) in { value; ty } in @@ -375,7 +375,7 @@ let merge_into_abstraction (meta : Meta.meta) (loop_id : LoopId.id) (abs_kind : (can_end : bool) (ctx : eval_ctx) (aid0 : AbstractionId.id) (aid1 : AbstractionId.id) : eval_ctx * AbstractionId.id = let merge_funs = mk_collapse_ctx_merge_duplicate_funs meta loop_id ctx in - merge_into_abstraction abs_kind can_end (Some merge_funs) ctx aid0 aid1 + merge_into_abstraction meta abs_kind can_end (Some merge_funs) ctx aid0 aid1 (** Collapse an environment, merging the duplicated borrows/loans. @@ -397,9 +397,9 @@ let join_ctxs (meta : Meta.meta) (loop_id : LoopId.id) (fixed_ids : ids_sets) (c (lazy ("join_ctxs:\n\n- fixed_ids:\n" ^ show_ids_sets fixed_ids ^ "\n\n- ctx0:\n" - ^ eval_ctx_to_string_no_filter ctx0 + ^ eval_ctx_to_string_no_filter meta ctx0 ^ "\n\n- ctx1:\n" - ^ eval_ctx_to_string_no_filter ctx1 + ^ eval_ctx_to_string_no_filter meta ctx1 ^ "\n\n")); let env0 = List.rev ctx0.env in @@ -413,9 +413,9 @@ let join_ctxs (meta : Meta.meta) (loop_id : LoopId.id) (fixed_ids : ids_sets) (c (lazy ("join_suffixes:\n\n- fixed_ids:\n" ^ show_ids_sets fixed_ids ^ "\n\n- ctx0:\n" - ^ eval_ctx_to_string_no_filter { ctx0 with env = List.rev env0 } + ^ eval_ctx_to_string_no_filter meta { ctx0 with env = List.rev env0 } ^ "\n\n- ctx1:\n" - ^ eval_ctx_to_string_no_filter { ctx1 with env = List.rev env1 } + ^ eval_ctx_to_string_no_filter meta { ctx1 with env = List.rev env1 } ^ "\n\n")); (* Sanity check: there are no values/abstractions which should be in the prefix *) @@ -456,9 +456,9 @@ let join_ctxs (meta : Meta.meta) (loop_id : LoopId.id) (fixed_ids : ids_sets) (c (lazy ("join_prefixes: BDummys:\n\n- fixed_ids:\n" ^ "\n" ^ show_ids_sets fixed_ids ^ "\n\n- value0:\n" - ^ env_elem_to_string ctx0 var0 + ^ env_elem_to_string meta ctx0 var0 ^ "\n\n- value1:\n" - ^ env_elem_to_string ctx1 var1 + ^ env_elem_to_string meta ctx1 var1 ^ "\n\n")); (* Two cases: the dummy value is an old value, in which case the bindings @@ -468,7 +468,7 @@ let join_ctxs (meta : Meta.meta) (loop_id : LoopId.id) (fixed_ids : ids_sets) (c (* Still in the prefix: match the values *) cassert (b0 = b1) meta "Bindings are not the same. We are not in the prefix anymore"; let b = b0 in - let v = M.match_typed_values ctx0 ctx1 v0 v1 in + let v = M.match_typed_values meta ctx0 ctx1 v0 v1 in let var = EBinding (BDummy b, v) in (* Continue *) var :: join_prefixes env0' env1') @@ -481,9 +481,9 @@ let join_ctxs (meta : Meta.meta) (loop_id : LoopId.id) (fixed_ids : ids_sets) (c (lazy ("join_prefixes: BVars:\n\n- fixed_ids:\n" ^ "\n" ^ show_ids_sets fixed_ids ^ "\n\n- value0:\n" - ^ env_elem_to_string ctx0 var0 + ^ env_elem_to_string meta ctx0 var0 ^ "\n\n- value1:\n" - ^ env_elem_to_string ctx1 var1 + ^ env_elem_to_string meta ctx1 var1 ^ "\n\n")); (* Variable bindings *must* be in the prefix and consequently their @@ -492,7 +492,7 @@ let join_ctxs (meta : Meta.meta) (loop_id : LoopId.id) (fixed_ids : ids_sets) (c ids must be the same"; (* Match the values *) let b = b0 in - let v = M.match_typed_values ctx0 ctx1 v0 v1 in + let v = M.match_typed_values meta ctx0 ctx1 v0 v1 in let var = EBinding (BVar b, v) in (* Continue *) var :: join_prefixes env0' env1' @@ -501,8 +501,8 @@ let join_ctxs (meta : Meta.meta) (loop_id : LoopId.id) (fixed_ids : ids_sets) (c log#ldebug (lazy ("join_prefixes: Abs:\n\n- fixed_ids:\n" ^ "\n" - ^ show_ids_sets fixed_ids ^ "\n\n- abs0:\n" ^ abs_to_string ctx0 abs0 - ^ "\n\n- abs1:\n" ^ abs_to_string ctx1 abs1 ^ "\n\n")); + ^ show_ids_sets fixed_ids ^ "\n\n- abs0:\n" ^ abs_to_string meta ctx0 abs0 + ^ "\n\n- abs1:\n" ^ abs_to_string meta ctx1 abs1 ^ "\n\n")); (* Same as for the dummy values: there are two cases *) if AbstractionId.Set.mem abs0.abs_id fixed_ids.aids then ( @@ -584,7 +584,7 @@ let join_ctxs (meta : Meta.meta) (loop_id : LoopId.id) (fixed_ids : ids_sets) (c with ValueMatchFailure e -> Error e (** Destructure all the new abstractions *) -let destructure_new_abs (loop_id : LoopId.id) +let destructure_new_abs (meta : Meta.meta) (loop_id : LoopId.id) (old_abs_ids : AbstractionId.Set.t) (ctx : eval_ctx) : eval_ctx = let abs_kind : abs_kind = Loop (loop_id, None, LoopSynthInput) in let can_end = true in @@ -597,7 +597,7 @@ let destructure_new_abs (loop_id : LoopId.id) (fun abs -> if is_fresh_abs_id abs.abs_id then let abs = - destructure_abs abs_kind can_end destructure_shared_values ctx abs + destructure_abs meta abs_kind can_end destructure_shared_values ctx abs in abs else abs) @@ -657,9 +657,9 @@ let loop_join_origin_with_continue_ctxs (meta : Meta.meta) (config : config) (lo let ctx = match err with | LoanInRight bid -> - InterpreterBorrows.end_borrow_no_synth config bid ctx + InterpreterBorrows.end_borrow_no_synth meta config bid ctx | LoansInRight bids -> - InterpreterBorrows.end_borrows_no_synth config bids ctx + InterpreterBorrows.end_borrows_no_synth meta config bids ctx | AbsInRight _ | AbsInLeft _ | LoanInLeft _ | LoansInLeft _ -> craise meta "Unexpected" in @@ -669,21 +669,21 @@ let loop_join_origin_with_continue_ctxs (meta : Meta.meta) (config : config) (lo log#ldebug (lazy ("loop_join_origin_with_continue_ctxs:join_one: initial ctx:\n" - ^ eval_ctx_to_string ctx)); + ^ eval_ctx_to_string meta ctx)); (* Destructure the abstractions introduced in the new context *) - let ctx = destructure_new_abs loop_id fixed_ids.aids ctx in + let ctx = destructure_new_abs meta loop_id fixed_ids.aids ctx in log#ldebug (lazy ("loop_join_origin_with_continue_ctxs:join_one: after destructure:\n" - ^ eval_ctx_to_string ctx)); + ^ eval_ctx_to_string meta ctx)); (* Collapse the context we want to add to the join *) let ctx = collapse_ctx meta loop_id None fixed_ids ctx in log#ldebug (lazy ("loop_join_origin_with_continue_ctxs:join_one: after collapse:\n" - ^ eval_ctx_to_string ctx)); + ^ eval_ctx_to_string meta ctx)); (* Refresh the fresh abstractions *) let ctx = refresh_abs fixed_ids.aids ctx in @@ -693,7 +693,7 @@ let loop_join_origin_with_continue_ctxs (meta : Meta.meta) (config : config) (lo log#ldebug (lazy ("loop_join_origin_with_continue_ctxs:join_one: after join:\n" - ^ eval_ctx_to_string ctx1)); + ^ eval_ctx_to_string meta ctx1)); (* Collapse again - the join might have introduce abstractions we want to merge with the others (note that those abstractions may actually @@ -702,7 +702,7 @@ let loop_join_origin_with_continue_ctxs (meta : Meta.meta) (config : config) (lo log#ldebug (lazy ("loop_join_origin_with_continue_ctxs:join_one: after join-collapse:\n" - ^ eval_ctx_to_string !joined_ctx)); + ^ eval_ctx_to_string meta !joined_ctx)); (* Sanity check *) if !Config.sanity_checks then Invariants.check_invariants meta !joined_ctx; diff --git a/compiler/InterpreterLoopsJoinCtxs.mli b/compiler/InterpreterLoopsJoinCtxs.mli index bb9f14ed..e79e6a25 100644 --- a/compiler/InterpreterLoopsJoinCtxs.mli +++ b/compiler/InterpreterLoopsJoinCtxs.mli @@ -16,6 +16,7 @@ open InterpreterLoopsCore - [aid1] *) val merge_into_abstraction : + Meta.meta -> loop_id -> abs_kind -> bool -> @@ -84,7 +85,7 @@ val merge_into_abstraction : - [ctx0] - [ctx1] *) -val join_ctxs : loop_id -> ids_sets -> eval_ctx -> eval_ctx -> ctx_or_update +val join_ctxs : Meta.meta -> loop_id -> ids_sets -> eval_ctx -> eval_ctx -> ctx_or_update (** Join the context at the entry of the loop with the contexts upon reentry (upon reaching the [Continue] statement - the goal is to compute a fixed @@ -103,6 +104,7 @@ val join_ctxs : loop_id -> ids_sets -> eval_ctx -> eval_ctx -> ctx_or_update - [ctxl] *) val loop_join_origin_with_continue_ctxs : + Meta.meta -> config -> loop_id -> ids_sets -> diff --git a/compiler/InterpreterLoopsMatchCtxs.ml b/compiler/InterpreterLoopsMatchCtxs.ml index 67c1155c..08d18407 100644 --- a/compiler/InterpreterLoopsMatchCtxs.ml +++ b/compiler/InterpreterLoopsMatchCtxs.ml @@ -20,7 +20,7 @@ module S = SynthesizeSymbolic (** The local logger *) let log = Logging.loops_match_ctxs_log -let compute_abs_borrows_loans_maps (no_duplicates : bool) +let compute_abs_borrows_loans_maps (meta : Meta.meta) (no_duplicates : bool) (explore : abs -> bool) (env : env) : abs_borrows_loans_maps = let abs_ids = ref [] in let abs_to_borrows = ref AbstractionId.Map.empty in @@ -94,7 +94,7 @@ let compute_abs_borrows_loans_maps (no_duplicates : bool) | AIgnoredSharedLoan child -> (* Ignore the id of the loan, if there is *) self#visit_typed_avalue abs_id child - | AEndedMutLoan _ | AEndedSharedLoan _ -> raise (Failure "Unreachable") + | AEndedMutLoan _ | AEndedSharedLoan _ -> craise meta "Unreachable" (** Make sure we don't register the ignored ids *) method! visit_aborrow_content abs_id bc = @@ -108,7 +108,7 @@ let compute_abs_borrows_loans_maps (no_duplicates : bool) (* Ignore the id of the borrow, if there is *) self#visit_typed_avalue abs_id child | AEndedMutBorrow _ | AEndedSharedBorrow -> - raise (Failure "Unreachable") + craise meta "Unreachable" method! visit_borrow_id abs_id bid = register_borrow_id abs_id bid method! visit_loan_id abs_id lid = register_loan_id abs_id lid @@ -184,9 +184,9 @@ let rec match_types (match_distinct_types : ty -> ty -> ty) | _ -> match_distinct_types ty0 ty1 module MakeMatcher (M : PrimMatcher) : Matcher = struct - let rec match_typed_values (ctx0 : eval_ctx) (ctx1 : eval_ctx) + let rec match_typed_values (meta : Meta.meta) (ctx0 : eval_ctx) (ctx1 : eval_ctx) (v0 : typed_value) (v1 : typed_value) : typed_value = - let match_rec = match_typed_values ctx0 ctx1 in + let match_rec = match_typed_values meta ctx0 ctx1 in let ty = M.match_etys ctx0 ctx1 v0.ty v1.ty in (* Using ValuesUtils.value_has_borrows on purpose here: we want to make explicit the fact that, though we have to pick @@ -197,7 +197,7 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct in match (v0.value, v1.value) with | VLiteral lv0, VLiteral lv1 -> - if lv0 = lv1 then v1 else M.match_distinct_literals ctx0 ctx1 ty lv0 lv1 + if lv0 = lv1 then v1 else M.match_distinct_literals meta ctx0 ctx1 ty lv0 lv1 | VAdt av0, VAdt av1 -> if av0.variant_id = av1.variant_id then let fields = List.combine av0.field_values av1.field_values in @@ -213,14 +213,14 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct assert (not (value_has_borrows v0.value)); assert (not (value_has_borrows v1.value)); (* Merge *) - M.match_distinct_adts ctx0 ctx1 ty av0 av1) + M.match_distinct_adts meta ctx0 ctx1 ty av0 av1) | VBottom, VBottom -> v0 | VBorrow bc0, VBorrow bc1 -> let bc = match (bc0, bc1) with | VSharedBorrow bid0, VSharedBorrow bid1 -> let bid = - M.match_shared_borrows ctx0 ctx1 match_rec ty bid0 bid1 + M.match_shared_borrows meta ctx0 ctx1 match_rec ty bid0 bid1 in VSharedBorrow bid | VMutBorrow (bid0, bv0), VMutBorrow (bid1, bv1) -> @@ -231,7 +231,7 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct (ValuesUtils.value_has_borrows ctx0.type_ctx.type_infos bv.value)); let bid, bv = - M.match_mut_borrows ctx0 ctx1 ty bid0 bv0 bid1 bv1 bv + M.match_mut_borrows meta ctx0 ctx1 ty bid0 bv0 bid1 bv1 bv in VMutBorrow (bid, bv) | VReservedMutBorrow _, _ @@ -242,7 +242,7 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct trying to match a reserved borrow, which shouldn't happen because reserved borrow should be eliminated very quickly - they are introduced just before function calls which activate them *) - raise (Failure "Unexpected") + craise meta "Unexpected" in { value = VBorrow bc; ty } | VLoan lc0, VLoan lc1 -> @@ -259,7 +259,7 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct let id = M.match_mut_loans ctx0 ctx1 ty id0 id1 in VMutLoan id | VSharedLoan _, VMutLoan _ | VMutLoan _, VSharedLoan _ -> - raise (Failure "Unreachable") + craise meta "Unreachable" in { value = VLoan lc; ty = v1.ty } | VSymbolic sv0, VSymbolic sv1 -> @@ -268,7 +268,7 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct assert (not (value_has_borrows v0.value)); assert (not (value_has_borrows v1.value)); (* Match *) - let sv = M.match_symbolic_values ctx0 ctx1 sv0 sv1 in + let sv = M.match_symbolic_values meta ctx0 ctx1 sv0 sv1 in { v1 with value = VSymbolic sv } | VLoan lc, _ -> ( match lc with @@ -278,27 +278,27 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct match lc with | VSharedLoan (ids, _) -> raise (ValueMatchFailure (LoansInRight ids)) | VMutLoan id -> raise (ValueMatchFailure (LoanInRight id))) - | VSymbolic sv, _ -> M.match_symbolic_with_other ctx0 ctx1 true sv v1 - | _, VSymbolic sv -> M.match_symbolic_with_other ctx0 ctx1 false sv v0 - | VBottom, _ -> M.match_bottom_with_other ctx0 ctx1 true v1 - | _, VBottom -> M.match_bottom_with_other ctx0 ctx1 false v0 + | VSymbolic sv, _ -> M.match_symbolic_with_other meta ctx0 ctx1 true sv v1 + | _, VSymbolic sv -> M.match_symbolic_with_other meta ctx0 ctx1 false sv v0 + | VBottom, _ -> M.match_bottom_with_other meta ctx0 ctx1 true v1 + | _, VBottom -> M.match_bottom_with_other meta ctx0 ctx1 false v0 | _ -> log#ldebug (lazy ("Unexpected match case:\n- value0: " - ^ typed_value_to_string ctx0 v0 + ^ typed_value_to_string meta ctx0 v0 ^ "\n- value1: " - ^ typed_value_to_string ctx1 v1)); - raise (Failure "Unexpected match case") + ^ typed_value_to_string meta ctx1 v1)); + craise meta "Unexpected match case" - and match_typed_avalues (ctx0 : eval_ctx) (ctx1 : eval_ctx) + and match_typed_avalues (meta : Meta.meta) (ctx0 : eval_ctx) (ctx1 : eval_ctx) (v0 : typed_avalue) (v1 : typed_avalue) : typed_avalue = log#ldebug (lazy ("match_typed_avalues:\n- value0: " - ^ typed_avalue_to_string ctx0 v0 + ^ typed_avalue_to_string meta ctx0 v0 ^ "\n- value1: " - ^ typed_avalue_to_string ctx1 v1)); + ^ typed_avalue_to_string meta ctx1 v1)); (* Using ValuesUtils.value_has_borrows on purpose here: we want to make explicit the fact that, though we have to pick @@ -308,8 +308,8 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct ValuesUtils.value_has_borrows ctx0.type_ctx.type_infos in - let match_rec = match_typed_values ctx0 ctx1 in - let match_arec = match_typed_avalues ctx0 ctx1 in + let match_rec = match_typed_values meta ctx0 ctx1 in + let match_arec = match_typed_avalues meta ctx0 ctx1 in let ty = M.match_rtys ctx0 ctx1 v0.ty v1.ty in match (v0.value, v1.value) with | AAdt av0, AAdt av1 -> @@ -323,15 +323,15 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct in { value; ty } else (* Merge *) - M.match_distinct_aadts ctx0 ctx1 v0.ty av0 v1.ty av1 ty - | ABottom, ABottom -> mk_abottom ty - | AIgnored, AIgnored -> mk_aignored ty + M.match_distinct_aadts meta ctx0 ctx1 v0.ty av0 v1.ty av1 ty + | ABottom, ABottom -> mk_abottom meta ty + | AIgnored, AIgnored -> mk_aignored meta ty | ABorrow bc0, ABorrow bc1 -> ( log#ldebug (lazy "match_typed_avalues: borrows"); match (bc0, bc1) with | ASharedBorrow bid0, ASharedBorrow bid1 -> log#ldebug (lazy "match_typed_avalues: shared borrows"); - M.match_ashared_borrows ctx0 ctx1 v0.ty bid0 v1.ty bid1 ty + M.match_ashared_borrows meta ctx0 ctx1 v0.ty bid0 v1.ty bid1 ty | AMutBorrow (bid0, av0), AMutBorrow (bid1, av1) -> log#ldebug (lazy "match_typed_avalues: mut borrows"); log#ldebug @@ -340,10 +340,10 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct let av = match_arec av0 av1 in log#ldebug (lazy "match_typed_avalues: mut borrows: matched children values"); - M.match_amut_borrows ctx0 ctx1 v0.ty bid0 av0 v1.ty bid1 av1 ty av + M.match_amut_borrows meta ctx0 ctx1 v0.ty bid0 av0 v1.ty bid1 av1 ty av | AIgnoredMutBorrow _, AIgnoredMutBorrow _ -> (* The abstractions are destructured: we shouldn't get there *) - raise (Failure "Unexpected") + craise meta "Unexpected" | AProjSharedBorrow asb0, AProjSharedBorrow asb1 -> ( match (asb0, asb1) with | [], [] -> @@ -352,7 +352,7 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct v0 | _ -> (* We should get there only if there are nested borrows *) - raise (Failure "Unexpected")) + craise meta "Unexpected") | _ -> (* TODO: getting there is not necessarily inconsistent (it may just be because the environments don't match) so we may want @@ -363,7 +363,7 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct we are *currently* ending it, in which case we need to completely end it before continuing. *) - raise (Failure "Unexpected")) + craise meta "Unexpected") | ALoan lc0, ALoan lc1 -> ( log#ldebug (lazy "match_typed_avalues: loans"); (* TODO: maybe we should enforce that the ids are always exactly the same - @@ -374,7 +374,7 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct let sv = match_rec sv0 sv1 in let av = match_arec av0 av1 in assert (not (value_has_borrows sv.value)); - M.match_ashared_loans ctx0 ctx1 v0.ty ids0 sv0 av0 v1.ty ids1 sv1 + M.match_ashared_loans meta ctx0 ctx1 v0.ty ids0 sv0 av0 v1.ty ids1 sv1 av1 ty sv av | AMutLoan (id0, av0), AMutLoan (id1, av1) -> log#ldebug (lazy "match_typed_avalues: mut loans"); @@ -383,18 +383,18 @@ module MakeMatcher (M : PrimMatcher) : Matcher = struct let av = match_arec av0 av1 in log#ldebug (lazy "match_typed_avalues: mut loans: matched children values"); - M.match_amut_loans ctx0 ctx1 v0.ty id0 av0 v1.ty id1 av1 ty av + M.match_amut_loans meta ctx0 ctx1 v0.ty id0 av0 v1.ty id1 av1 ty av | AIgnoredMutLoan _, AIgnoredMutLoan _ | AIgnoredSharedLoan _, AIgnoredSharedLoan _ -> (* Those should have been filtered when destructuring the abstractions - they are necessary only when there are nested borrows *) - raise (Failure "Unreachable") - | _ -> raise (Failure "Unreachable")) + craise meta "Unreachable" + | _ -> craise meta "Unreachable") | ASymbolic _, ASymbolic _ -> (* For now, we force all the symbolic values containing borrows to be eagerly expanded, and we don't support nested borrows *) - raise (Failure "Unreachable") - | _ -> M.match_avalues ctx0 ctx1 v0 v1 + craise meta "Unreachable" + | _ -> M.match_avalues meta ctx0 ctx1 v0 v1 end module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct @@ -413,11 +413,11 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct assert (ty0 = ty1); ty0 - let match_distinct_literals (_ : eval_ctx) (_ : eval_ctx) (ty : ety) + let match_distinct_literals (meta : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (ty : ety) (_ : literal) (_ : literal) : typed_value = - mk_fresh_symbolic_typed_value_from_no_regions_ty ty + mk_fresh_symbolic_typed_value_from_no_regions_ty meta ty - let match_distinct_adts (ctx0 : eval_ctx) (ctx1 : eval_ctx) (ty : ety) + let match_distinct_adts (meta : Meta.meta) (ctx0 : eval_ctx) (ctx1 : eval_ctx) (ty : ety) (adt0 : adt_value) (adt1 : adt_value) : typed_value = (* Check that the ADTs don't contain borrows - this is redundant with checks performed by the caller, but we prefer to be safe with regards to future @@ -447,12 +447,12 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct if bottom_in_adt_value ctx0.ended_regions adt0 || bottom_in_adt_value ctx1.ended_regions adt1 - then mk_bottom ty + then mk_bottom meta ty else (* No borrows, no loans, no bottoms: we can introduce a symbolic value *) - mk_fresh_symbolic_typed_value_from_no_regions_ty ty + mk_fresh_symbolic_typed_value_from_no_regions_ty meta ty - let match_shared_borrows (ctx0 : eval_ctx) (ctx1 : eval_ctx) match_rec + let match_shared_borrows (meta : Meta.meta) (ctx0 : eval_ctx) (ctx1 : eval_ctx) match_rec (ty : ety) (bid0 : borrow_id) (bid1 : borrow_id) : borrow_id = (* Lookup the shared values and match them - we do this mostly to make sure we end loans which might appear on one side @@ -483,7 +483,7 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct let borrows = [ mk_aborrow bid0; mk_aborrow bid1 ] in let loan = - ASharedLoan (BorrowId.Set.singleton bid2, sv, mk_aignored bv_ty) + ASharedLoan (BorrowId.Set.singleton bid2, sv, mk_aignored meta bv_ty) in (* Note that an aloan has a borrow type *) let loan : typed_avalue = { value = ALoan loan; ty = borrow_ty } in @@ -508,7 +508,7 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct (* Return the new borrow *) bid2 - let match_mut_borrows (ctx0 : eval_ctx) (_ : eval_ctx) (ty : ety) + let match_mut_borrows (meta : Meta.meta) (ctx0 : eval_ctx) (_ : eval_ctx) (ty : ety) (bid0 : borrow_id) (bv0 : typed_value) (bid1 : borrow_id) (bv1 : typed_value) (bv : typed_value) : borrow_id * typed_value = if bid0 = bid1 then ( @@ -576,14 +576,14 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct let borrow_av = let ty = borrow_ty in - let value = ABorrow (AMutBorrow (bid0, mk_aignored bv_ty)) in - mk_typed_avalue ty value + let value = ABorrow (AMutBorrow (bid0, mk_aignored meta bv_ty)) in + mk_typed_avalue meta ty value in let loan_av = let ty = borrow_ty in - let value = ALoan (AMutLoan (nbid, mk_aignored bv_ty)) in - mk_typed_avalue ty value + let value = ALoan (AMutLoan (nbid, mk_aignored meta bv_ty)) in + mk_typed_avalue meta ty value in let avalues = [ borrow_av; loan_av ] in @@ -617,7 +617,7 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct (* Generate a fresh symbolic value for the borrowed value *) let _, bv_ty, kind = ty_as_ref ty in - let sv = mk_fresh_symbolic_typed_value_from_no_regions_ty bv_ty in + let sv = mk_fresh_symbolic_typed_value_from_no_regions_ty meta bv_ty in let borrow_ty = mk_ref_ty (RFVar rid) bv_ty kind in @@ -625,12 +625,12 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct let mk_aborrow (bid : borrow_id) (bv : typed_value) : typed_avalue = let bv_ty = bv.ty in assert (ty_no_regions bv_ty); - let value = ABorrow (AMutBorrow (bid, mk_aignored bv_ty)) in + let value = ABorrow (AMutBorrow (bid, mk_aignored meta bv_ty)) in { value; ty = borrow_ty } in let borrows = [ mk_aborrow bid0 bv0; mk_aborrow bid1 bv1 ] in - let loan = AMutLoan (bid2, mk_aignored bv_ty) in + let loan = AMutLoan (bid2, mk_aignored meta bv_ty) in (* Note that an aloan has a borrow type *) let loan : typed_avalue = { value = ALoan loan; ty = borrow_ty } in @@ -685,7 +685,7 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct both borrows *) raise (ValueMatchFailure (LoanInLeft id0)) - let match_symbolic_values (ctx0 : eval_ctx) (_ : eval_ctx) + let match_symbolic_values (meta : Meta.meta) (ctx0 : eval_ctx) (_ : eval_ctx) (sv0 : symbolic_value) (sv1 : symbolic_value) : symbolic_value = let id0 = sv0.sv_id in let id1 = sv1.sv_id in @@ -699,9 +699,9 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct borrows *) assert (not (ty_has_borrows ctx0.type_ctx.type_infos sv0.sv_ty)); (* We simply introduce a fresh symbolic value *) - mk_fresh_symbolic_value sv0.sv_ty) + mk_fresh_symbolic_value meta sv0.sv_ty) - let match_symbolic_with_other (ctx0 : eval_ctx) (_ : eval_ctx) (left : bool) + let match_symbolic_with_other (meta : Meta.meta) (ctx0 : eval_ctx) (_ : eval_ctx) (left : bool) (sv : symbolic_value) (v : typed_value) : typed_value = (* Check that: - there are no borrows in the symbolic value @@ -721,9 +721,9 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct if value_is_left then raise (ValueMatchFailure (LoanInLeft id)) else raise (ValueMatchFailure (LoanInRight id))); (* Return a fresh symbolic value *) - mk_fresh_symbolic_typed_value sv.sv_ty + mk_fresh_symbolic_typed_value meta sv.sv_ty - let match_bottom_with_other (ctx0 : eval_ctx) (ctx1 : eval_ctx) (left : bool) + let match_bottom_with_other (meta : Meta.meta) (ctx0 : eval_ctx) (ctx1 : eval_ctx) (left : bool) (v : typed_value) : typed_value = (* If there are outer loans in the non-bottom value, raise an exception. Otherwise, convert it to an abstraction and return [Bottom]. @@ -736,7 +736,7 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct with | Some (BorrowContent _) -> (* Can't get there: we only ask for outer *loans* *) - raise (Failure "Unreachable") + craise meta "Unreachable" | Some (LoanContent lc) -> ( match lc with | VSharedLoan (ids, _) -> @@ -754,25 +754,25 @@ module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct let destructure_shared_values = true in let ctx = if value_is_left then ctx0 else ctx1 in let absl = - convert_value_to_abstractions abs_kind can_end + convert_value_to_abstractions meta abs_kind can_end destructure_shared_values ctx v in push_absl absl; (* Return [Bottom] *) - mk_bottom v.ty + mk_bottom meta v.ty (* As explained in comments: we don't use the join matcher to join avalues, only concrete values *) - let match_distinct_aadts _ _ _ _ _ _ _ = raise (Failure "Unreachable") - let match_ashared_borrows _ _ _ _ _ _ = raise (Failure "Unreachable") - let match_amut_borrows _ _ _ _ _ _ _ _ _ _ = raise (Failure "Unreachable") + let match_distinct_aadts (meta : Meta.meta) _ _ _ _ _ _ _ = craise meta "Unreachable" + let match_ashared_borrows (meta : Meta.meta) _ _ _ _ _ _ = craise meta "Unreachable" + let match_amut_borrows (meta : Meta.meta) _ _ _ _ _ _ _ _ _ _ = craise meta "Unreachable" - let match_ashared_loans _ _ _ _ _ _ _ _ _ _ _ _ _ = - raise (Failure "Unreachable") + let match_ashared_loans (meta: Meta.meta) _ _ _ _ _ _ _ _ _ _ _ _ _ = + craise meta "Unreachable" - let match_amut_loans _ _ _ _ _ _ _ _ _ _ = raise (Failure "Unreachable") - let match_avalues _ _ _ _ = raise (Failure "Unreachable") + let match_amut_loans (meta: Meta.meta) _ _ _ _ _ _ _ _ _ _ = craise meta "Unreachable" + let match_avalues (meta: Meta.meta) _ _ _ _ = craise meta "Unreachable" end (* Very annoying: functors only take modules as inputs... *) @@ -814,22 +814,22 @@ module MakeMoveMatcher (S : MatchMoveState) : PrimMatcher = struct assert (ty0 = ty1); ty0 - let match_distinct_literals (_ : eval_ctx) (_ : eval_ctx) (ty : ety) + let match_distinct_literals (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (ty : ety) (_ : literal) (l : literal) : typed_value = { value = VLiteral l; ty } - let match_distinct_adts (_ : eval_ctx) (_ : eval_ctx) (ty : ety) + let match_distinct_adts (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (ty : ety) (_ : adt_value) (adt1 : adt_value) : typed_value = (* Note that if there was a bottom inside the ADT on the left, the value on the left should have been simplified to bottom. *) { ty; value = VAdt adt1 } - let match_shared_borrows (_ : eval_ctx) (_ : eval_ctx) _ (_ : ety) + let match_shared_borrows (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) _ (_ : ety) (_ : borrow_id) (bid1 : borrow_id) : borrow_id = (* There can't be bottoms in shared values *) bid1 - let match_mut_borrows (_ : eval_ctx) (_ : eval_ctx) (_ : ety) (_ : borrow_id) + let match_mut_borrows (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (_ : ety) (_ : borrow_id) (_ : typed_value) (bid1 : borrow_id) (bv1 : typed_value) (_ : typed_value) : borrow_id * typed_value = (* There can't be bottoms in borrowed values *) @@ -845,15 +845,15 @@ module MakeMoveMatcher (S : MatchMoveState) : PrimMatcher = struct (id1 : loan_id) : loan_id = id1 - let match_symbolic_values (_ : eval_ctx) (_ : eval_ctx) (_ : symbolic_value) + let match_symbolic_values (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (_ : symbolic_value) (sv1 : symbolic_value) : symbolic_value = sv1 - let match_symbolic_with_other (_ : eval_ctx) (_ : eval_ctx) (left : bool) + let match_symbolic_with_other (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (left : bool) (sv : symbolic_value) (v : typed_value) : typed_value = if left then v else mk_typed_value_from_symbolic_value sv - let match_bottom_with_other (_ : eval_ctx) (_ : eval_ctx) (left : bool) + let match_bottom_with_other (meta : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (left : bool) (v : typed_value) : typed_value = let with_borrows = false in if left then ( @@ -865,35 +865,35 @@ module MakeMoveMatcher (S : MatchMoveState) : PrimMatcher = struct with | Some (BorrowContent _) -> (* Can't get there: we only ask for outer *loans* *) - raise (Failure "Unreachable") + craise meta "Unreachable" | Some (LoanContent _) -> (* We should have ended all the outer loans *) - raise (Failure "Unexpected outer loan") + craise meta "Unexpected outer loan" | None -> (* Move the value - note that we shouldn't get there if we were not allowed to move the value in the first place. *) push_moved_value v; (* Return [Bottom] *) - mk_bottom v.ty) + mk_bottom meta v.ty) else (* If we get there it means the source environment (e.g., the fixed-point) has a non-bottom value, while the target environment (e.g., the environment we have when we reach the continue) has bottom: we shouldn't get there. *) - raise (Failure "Unreachable") + craise meta "Unreachable" (* As explained in comments: we don't use the join matcher to join avalues, only concrete values *) - let match_distinct_aadts _ _ _ _ _ _ _ = raise (Failure "Unreachable") - let match_ashared_borrows _ _ _ _ _ _ = raise (Failure "Unreachable") - let match_amut_borrows _ _ _ _ _ _ _ _ _ _ = raise (Failure "Unreachable") + let match_distinct_aadts (meta : Meta.meta) _ _ _ _ _ _ _ = craise meta "Unreachable" + let match_ashared_borrows (meta : Meta.meta) _ _ _ _ _ _ = craise meta "Unreachable" + let match_amut_borrows (meta : Meta.meta) _ _ _ _ _ _ _ _ _ = craise meta "Unreachable" - let match_ashared_loans _ _ _ _ _ _ _ _ _ _ _ _ _ = - raise (Failure "Unreachable") + let match_ashared_loans (meta : Meta.meta) _ _ _ _ _ _ _ _ _ _ _ _ _ = + craise meta "Unreachable" - let match_amut_loans _ _ _ _ _ _ _ _ _ _ = raise (Failure "Unreachable") - let match_avalues _ _ _ _ = raise (Failure "Unreachable") + let match_amut_loans (meta : Meta.meta) _ _ _ _ _ _ _ _ _ _ = craise meta "Unreachable" + let match_avalues (meta : Meta.meta) _ _ _ _ = craise meta "Unreachable" end module MakeCheckEquivMatcher (S : MatchCheckEquivState) : CheckEquivMatcher = @@ -998,15 +998,15 @@ struct in match_types match_distinct_types match_regions ty0 ty1 - let match_distinct_literals (_ : eval_ctx) (_ : eval_ctx) (ty : ety) + let match_distinct_literals (meta : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (ty : ety) (_ : literal) (_ : literal) : typed_value = - mk_fresh_symbolic_typed_value_from_no_regions_ty ty + mk_fresh_symbolic_typed_value_from_no_regions_ty meta ty - let match_distinct_adts (_ : eval_ctx) (_ : eval_ctx) (_ty : ety) + let match_distinct_adts (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (_ty : ety) (_adt0 : adt_value) (_adt1 : adt_value) : typed_value = raise (Distinct "match_distinct_adts") - let match_shared_borrows (ctx0 : eval_ctx) (ctx1 : eval_ctx) + let match_shared_borrows (meta : Meta.meta) (ctx0 : eval_ctx) (ctx1 : eval_ctx) (match_typed_values : typed_value -> typed_value -> typed_value) (_ty : ety) (bid0 : borrow_id) (bid1 : borrow_id) : borrow_id = log#ldebug @@ -1027,16 +1027,16 @@ struct (lazy ("MakeCheckEquivMatcher: match_shared_borrows: looked up values:" ^ "sv0: " - ^ typed_value_to_string ctx0 v0 + ^ typed_value_to_string meta ctx0 v0 ^ ", sv1: " - ^ typed_value_to_string ctx1 v1)); + ^ typed_value_to_string meta ctx1 v1)); let _ = match_typed_values v0 v1 in () in bid - let match_mut_borrows (_ : eval_ctx) (_ : eval_ctx) (_ty : ety) + let match_mut_borrows (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (_ty : ety) (bid0 : borrow_id) (_bv0 : typed_value) (bid1 : borrow_id) (_bv1 : typed_value) (bv : typed_value) : borrow_id * typed_value = let bid = match_borrow_id bid0 bid1 in @@ -1052,7 +1052,7 @@ struct (bid1 : loan_id) : loan_id = match_loan_id bid0 bid1 - let match_symbolic_values (ctx0 : eval_ctx) (ctx1 : eval_ctx) + let match_symbolic_values (_ : Meta.meta) (ctx0 : eval_ctx) (ctx1 : eval_ctx) (sv0 : symbolic_value) (sv1 : symbolic_value) : symbolic_value = let id0 = sv0.sv_id in let id1 = sv1.sv_id in @@ -1089,7 +1089,7 @@ struct we want *) sv0) - let match_symbolic_with_other (_ : eval_ctx) (_ : eval_ctx) (left : bool) + let match_symbolic_with_other (meta : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) (left : bool) (sv : symbolic_value) (v : typed_value) : typed_value = if S.check_equiv then raise (Distinct "match_symbolic_with_other") else ( @@ -1103,7 +1103,7 @@ struct (* Return - the returned value is not used, so we can return whatever we want *) v) - let match_bottom_with_other (ctx0 : eval_ctx) (ctx1 : eval_ctx) (left : bool) + let match_bottom_with_other (meta : Meta.meta) (ctx0 : eval_ctx) (ctx1 : eval_ctx) (left : bool) (v : typed_value) : typed_value = (* It can happen that some variables get initialized in some branches and not in some others, which causes problems when matching. *) @@ -1112,7 +1112,7 @@ struct a continue, where the fixed point contains some bottom values. *) let value_is_left = not left in let ctx = if value_is_left then ctx0 else ctx1 in - if left && not (value_has_loans_or_borrows ctx v.value) then mk_bottom v.ty + if left && not (value_has_loans_or_borrows ctx v.value) then mk_bottom meta v.ty else raise (Distinct @@ -1120,51 +1120,51 @@ struct ^ Print.bool_to_string left ^ "\n- value to match with bottom:\n" ^ show_typed_value v)) - let match_distinct_aadts _ _ _ _ _ _ _ = + let match_distinct_aadts _ _ _ _ _ _ _ _ = raise (Distinct "match_distinct_adts") - let match_ashared_borrows (_ : eval_ctx) (_ : eval_ctx) _ty0 bid0 _ty1 bid1 ty + let match_ashared_borrows (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) _ty0 bid0 _ty1 bid1 ty = let bid = match_borrow_id bid0 bid1 in let value = ABorrow (ASharedBorrow bid) in { value; ty } - let match_amut_borrows (_ : eval_ctx) (_ : eval_ctx) _ty0 bid0 _av0 _ty1 bid1 + let match_amut_borrows (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) _ty0 bid0 _av0 _ty1 bid1 _av1 ty av = let bid = match_borrow_id bid0 bid1 in let value = ABorrow (AMutBorrow (bid, av)) in { value; ty } - let match_ashared_loans (_ : eval_ctx) (_ : eval_ctx) _ty0 ids0 _v0 _av0 _ty1 + let match_ashared_loans (_ : Meta.meta) (_ : eval_ctx) (_ : eval_ctx) _ty0 ids0 _v0 _av0 _ty1 ids1 _v1 _av1 ty v av = let bids = match_loan_ids ids0 ids1 in let value = ALoan (ASharedLoan (bids, v, av)) in { value; ty } - let match_amut_loans (ctx0 : eval_ctx) (ctx1 : eval_ctx) _ty0 id0 _av0 _ty1 + let match_amut_loans (meta : Meta.meta) (ctx0 : eval_ctx) (ctx1 : eval_ctx) _ty0 id0 _av0 _ty1 id1 _av1 ty av = log#ldebug (lazy ("MakeCheckEquivMatcher:match_amut_loans:" ^ "\n- id0: " ^ BorrowId.to_string id0 ^ "\n- id1: " ^ BorrowId.to_string id1 ^ "\n- ty: " ^ ty_to_string ctx0 ty ^ "\n- av: " - ^ typed_avalue_to_string ctx1 av)); + ^ typed_avalue_to_string meta ctx1 av)); let id = match_loan_id id0 id1 in let value = ALoan (AMutLoan (id, av)) in { value; ty } - let match_avalues (ctx0 : eval_ctx) (ctx1 : eval_ctx) v0 v1 = + let match_avalues (meta : Meta.meta) (ctx0 : eval_ctx) (ctx1 : eval_ctx) v0 v1 = log#ldebug (lazy ("avalues don't match:\n- v0: " - ^ typed_avalue_to_string ctx0 v0 + ^ typed_avalue_to_string meta ctx0 v0 ^ "\n- v1: " - ^ typed_avalue_to_string ctx1 v1)); + ^ typed_avalue_to_string meta ctx1 v1)); raise (Distinct "match_avalues") end -let match_ctxs (check_equiv : bool) (fixed_ids : ids_sets) +let match_ctxs (meta : Meta.meta) (check_equiv : bool) (fixed_ids : ids_sets) (lookup_shared_value_in_ctx0 : BorrowId.id -> typed_value) (lookup_shared_value_in_ctx1 : BorrowId.id -> typed_value) (ctx0 : eval_ctx) (ctx1 : eval_ctx) : ids_maps option = @@ -1172,9 +1172,9 @@ let match_ctxs (check_equiv : bool) (fixed_ids : ids_sets) (lazy ("match_ctxs:\n\n- fixed_ids:\n" ^ show_ids_sets fixed_ids ^ "\n\n- ctx0:\n" - ^ eval_ctx_to_string_no_filter ctx0 + ^ eval_ctx_to_string_no_filter meta ctx0 ^ "\n\n- ctx1:\n" - ^ eval_ctx_to_string_no_filter ctx1 + ^ eval_ctx_to_string_no_filter meta ctx1 ^ "\n\n")); (* Initialize the maps and instantiate the matcher *) @@ -1282,7 +1282,7 @@ let match_ctxs (check_equiv : bool) (fixed_ids : ids_sets) log#ldebug (lazy "match_abstractions: matching values"); let _ = List.map - (fun (v0, v1) -> M.match_typed_avalues ctx0 ctx1 v0 v1) + (fun (v0, v1) -> M.match_typed_avalues meta ctx0 ctx1 v0 v1) (List.combine avalues0 avalues1) in log#ldebug (lazy "match_abstractions: values matched OK"); @@ -1303,9 +1303,9 @@ let match_ctxs (check_equiv : bool) (fixed_ids : ids_sets) ^ "\n- aid_map: " ^ AbstractionId.InjSubst.show_t !aid_map ^ "\n\n- ctx0:\n" - ^ eval_ctx_to_string_no_filter { ctx0 with env = List.rev env0 } + ^ eval_ctx_to_string_no_filter meta { ctx0 with env = List.rev env0 } ^ "\n\n- ctx1:\n" - ^ eval_ctx_to_string_no_filter { ctx1 with env = List.rev env1 } + ^ eval_ctx_to_string_no_filter meta { ctx1 with env = List.rev env1 } ^ "\n\n")); match (env0, env1) with @@ -1321,12 +1321,12 @@ let match_ctxs (check_equiv : bool) (fixed_ids : ids_sets) assert ((not S.check_equiv) || ids_are_fixed ids)); (* We still match the values - allows to compute mappings (which are the identity actually) *) - let _ = M.match_typed_values ctx0 ctx1 v0 v1 in + let _ = M.match_typed_values meta ctx0 ctx1 v0 v1 in match_envs env0' env1' | EBinding (BVar b0, v0) :: env0', EBinding (BVar b1, v1) :: env1' -> assert (b0 = b1); (* Match the values *) - let _ = M.match_typed_values ctx0 ctx1 v0 v1 in + let _ = M.match_typed_values meta ctx0 ctx1 v0 v1 in (* Continue *) match_envs env0' env1' | EAbs abs0 :: env0', EAbs abs1 :: env1' -> @@ -1366,7 +1366,7 @@ let match_ctxs (check_equiv : bool) (fixed_ids : ids_sets) let env0, env1 = match (env0, env1) with | EFrame :: env0, EFrame :: env1 -> (env0, env1) - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" in match_envs env0 env1; @@ -1382,23 +1382,16 @@ let match_ctxs (check_equiv : bool) (fixed_ids : ids_sets) } in Some maps - with - | Distinct msg -> - log#ldebug (lazy ("match_ctxs: distinct: " ^ msg ^ "\n")); - None - | ValueMatchFailure k -> - log#ldebug - (lazy - ("match_ctxs: distinct: ValueMatchFailure" ^ show_updt_env_kind k - ^ "\n")); - None + with Distinct msg -> + log#ldebug (lazy ("match_ctxs: distinct: " ^ msg)); + None -let ctxs_are_equivalent (fixed_ids : ids_sets) (ctx0 : eval_ctx) +let ctxs_are_equivalent (meta : Meta.meta) (fixed_ids : ids_sets) (ctx0 : eval_ctx) (ctx1 : eval_ctx) : bool = let check_equivalent = true in - let lookup_shared_value _ = raise (Failure "Unreachable") in + let lookup_shared_value _ = craise meta "Unreachable" in Option.is_some - (match_ctxs check_equivalent fixed_ids lookup_shared_value + (match_ctxs meta check_equivalent fixed_ids lookup_shared_value lookup_shared_value ctx0 ctx1) let prepare_match_ctx_with_target (meta : Meta.meta) (config : config) (loop_id : LoopId.id) @@ -1409,23 +1402,23 @@ let prepare_match_ctx_with_target (meta : Meta.meta) (config : config) (loop_id (lazy ("prepare_match_ctx_with_target:\n" ^ "\n- fixed_ids: " ^ show_ids_sets fixed_ids ^ "\n" ^ "\n- src_ctx: " - ^ eval_ctx_to_string src_ctx ^ "\n- tgt_ctx: " ^ eval_ctx_to_string tgt_ctx + ^ eval_ctx_to_string meta src_ctx ^ "\n- tgt_ctx: " ^ eval_ctx_to_string meta tgt_ctx )); (* End the loans which lead to mismatches when joining *) let rec cf_reorganize_join_tgt : cm_fun = fun cf tgt_ctx -> (* Collect fixed values in the source and target contexts: end the loans in the source context which don't appear in the target context *) - let filt_src_env, _, _ = ctx_split_fixed_new fixed_ids src_ctx in - let filt_tgt_env, _, _ = ctx_split_fixed_new fixed_ids tgt_ctx in + let filt_src_env, _, _ = ctx_split_fixed_new meta fixed_ids src_ctx in + let filt_tgt_env, _, _ = ctx_split_fixed_new meta fixed_ids tgt_ctx in log#ldebug (lazy ("cf_reorganize_join_tgt: match_ctx_with_target:\n" ^ "\n- fixed_ids: " ^ show_ids_sets fixed_ids ^ "\n" ^ "\n- filt_src_ctx: " - ^ env_to_string src_ctx filt_src_env + ^ env_to_string meta src_ctx filt_src_env ^ "\n- filt_tgt_ctx: " - ^ env_to_string tgt_ctx filt_tgt_env)); + ^ env_to_string meta tgt_ctx filt_tgt_env)); (* Remove the abstractions *) let filter (ee : env_elem) : bool = @@ -1450,13 +1443,13 @@ let prepare_match_ctx_with_target (meta : Meta.meta) (config : config) (loop_id match (var0, var1) with | EBinding (BDummy b0, v0), EBinding (BDummy b1, v1) -> assert (b0 = b1); - let _ = M.match_typed_values src_ctx tgt_ctx v0 v1 in + let _ = M.match_typed_values meta src_ctx tgt_ctx v0 v1 in () | EBinding (BVar b0, v0), EBinding (BVar b1, v1) -> assert (b0 = b1); - let _ = M.match_typed_values src_ctx tgt_ctx v0 v1 in + let _ = M.match_typed_values meta src_ctx tgt_ctx v0 v1 in () - | _ -> raise (Failure "Unexpected")) + | _ -> craise meta "Unexpected") (List.combine filt_src_env filt_tgt_env) in (* No exception was thrown: continue *) @@ -1465,9 +1458,9 @@ let prepare_match_ctx_with_target (meta : Meta.meta) (config : config) (loop_id ("cf_reorganize_join_tgt: done with borrows/loans:\n" ^ "\n- fixed_ids: " ^ show_ids_sets fixed_ids ^ "\n" ^ "\n- filt_src_ctx: " - ^ env_to_string src_ctx filt_src_env + ^ env_to_string meta src_ctx filt_src_env ^ "\n- filt_tgt_ctx: " - ^ env_to_string tgt_ctx filt_tgt_env)); + ^ env_to_string meta tgt_ctx filt_tgt_env)); (* We are done with the borrows/loans: now make sure we move all the values which are bottom in the src environment (i.e., the @@ -1487,13 +1480,13 @@ let prepare_match_ctx_with_target (meta : Meta.meta) (config : config) (loop_id match (var0, var1) with | EBinding (BDummy b0, v0), EBinding ((BDummy b1 as var1), v1) -> assert (b0 = b1); - let v = M.match_typed_values src_ctx tgt_ctx v0 v1 in + let v = M.match_typed_values meta src_ctx tgt_ctx v0 v1 in (var1, v) | EBinding (BVar b0, v0), EBinding ((BVar b1 as var1), v1) -> assert (b0 = b1); - let v = M.match_typed_values src_ctx tgt_ctx v0 v1 in + let v = M.match_typed_values meta src_ctx tgt_ctx v0 v1 in (var1, v) - | _ -> raise (Failure "Unexpected")) + | _ -> craise meta "Unexpected") (List.combine filt_src_env filt_tgt_env) in let var_to_new_val = BinderMap.of_list var_to_new_val in @@ -1521,18 +1514,18 @@ let prepare_match_ctx_with_target (meta : Meta.meta) (config : config) (loop_id (lazy ("cf_reorganize_join_tgt: done with borrows/loans and moves:\n" ^ "\n- fixed_ids: " ^ show_ids_sets fixed_ids ^ "\n" ^ "\n- src_ctx: " - ^ eval_ctx_to_string src_ctx ^ "\n- tgt_ctx: " - ^ eval_ctx_to_string tgt_ctx)); + ^ eval_ctx_to_string meta src_ctx ^ "\n- tgt_ctx: " + ^ eval_ctx_to_string meta tgt_ctx)); cf tgt_ctx with ValueMatchFailure e -> (* Exception: end the corresponding borrows, and continue *) let cc = match e with - | LoanInRight bid -> InterpreterBorrows.end_borrow config bid - | LoansInRight bids -> InterpreterBorrows.end_borrows config bids + | LoanInRight bid -> InterpreterBorrows.end_borrow meta config bid + | LoansInRight bids -> InterpreterBorrows.end_borrows meta config bids | AbsInRight _ | AbsInLeft _ | LoanInLeft _ | LoansInLeft _ -> - raise (Failure "Unexpected") + craise meta "Unexpected" in comp cc cf_reorganize_join_tgt cf tgt_ctx in @@ -1587,9 +1580,9 @@ let match_ctx_with_target (config : config) (loop_id : LoopId.id) ^ eval_ctx_to_string src_ctx ^ "\n- tgt_ctx: " ^ eval_ctx_to_string tgt_ctx)); - let filt_tgt_env, _, _ = ctx_split_fixed_new fixed_ids tgt_ctx in + let filt_tgt_env, _, _ = ctx_split_fixed_new meta fixed_ids tgt_ctx in let filt_src_env, new_absl, new_dummyl = - ctx_split_fixed_new fixed_ids src_ctx + ctx_split_fixed_new meta fixed_ids src_ctx in assert (new_dummyl = []); let filt_tgt_ctx = { tgt_ctx with env = filt_tgt_env } in @@ -1603,13 +1596,13 @@ let match_ctx_with_target (config : config) (loop_id : LoopId.id) match snd (lookup_loan meta ek_all lid ctx) with | Concrete (VSharedLoan (_, v)) -> v | Abstract (ASharedLoan (_, v, _)) -> v - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" in let lookup_in_src id = lookup_shared_loan id src_ctx in let lookup_in_tgt id = lookup_shared_loan id tgt_ctx in (* Match *) Option.get - (match_ctxs check_equiv fixed_ids lookup_in_src lookup_in_tgt + (match_ctxs meta check_equiv fixed_ids lookup_in_src lookup_in_tgt filt_src_ctx filt_tgt_ctx) in let tgt_to_src_borrow_map = @@ -1623,13 +1616,13 @@ let match_ctx_with_target (config : config) (loop_id : LoopId.id) log#ldebug (lazy ("match_ctx_with_target: cf_introduce_loop_fp_abs:" ^ "\n\n- src_ctx: " - ^ eval_ctx_to_string src_ctx ^ "\n\n- tgt_ctx: " - ^ eval_ctx_to_string tgt_ctx ^ "\n\n- filt_tgt_ctx: " - ^ eval_ctx_to_string_no_filter filt_tgt_ctx + ^ eval_ctx_to_string meta src_ctx ^ "\n\n- tgt_ctx: " + ^ eval_ctx_to_string meta tgt_ctx ^ "\n\n- filt_tgt_ctx: " + ^ eval_ctx_to_string_no_filter meta filt_tgt_ctx ^ "\n\n- filt_src_ctx: " - ^ eval_ctx_to_string_no_filter filt_src_ctx + ^ eval_ctx_to_string_no_filter meta filt_src_ctx ^ "\n\n- new_absl:\n" - ^ eval_ctx_to_string + ^ eval_ctx_to_string meta { src_ctx with env = List.map (fun abs -> EAbs abs) new_absl } ^ "\n\n- fixed_ids:\n" ^ show_ids_sets fixed_ids ^ "\n\n- fp_bl_maps:\n" ^ show_borrow_loan_corresp fp_bl_maps @@ -1828,18 +1821,17 @@ let match_ctx_with_target (config : config) (loop_id : LoopId.id) log#ldebug (lazy ("match_ctx_with_target: cf_introduce_loop_fp_abs: done:\n\ - - result ctx:\n" ^ eval_ctx_to_string tgt_ctx)); + - result ctx:\n" ^ eval_ctx_to_string meta tgt_ctx)); (* Sanity check *) if !Config.sanity_checks then - Invariants.check_borrowed_values_invariant tgt_ctx; - + Invariants.check_borrowed_values_invariant meta tgt_ctx; (* End all the borrows which appear in the *new* abstractions *) let new_borrows = BorrowId.Set.of_list (List.map snd (BorrowId.Map.bindings !src_fresh_borrows_map)) in - let cc = InterpreterBorrows.end_borrows config new_borrows in + let cc = InterpreterBorrows.end_borrows meta config new_borrows in (* Compute the loop input values *) let input_values = diff --git a/compiler/InterpreterLoopsMatchCtxs.mli b/compiler/InterpreterLoopsMatchCtxs.mli index d6f89ed6..0db1ff1d 100644 --- a/compiler/InterpreterLoopsMatchCtxs.mli +++ b/compiler/InterpreterLoopsMatchCtxs.mli @@ -19,7 +19,7 @@ open InterpreterLoopsCore - [env] *) val compute_abs_borrows_loans_maps : - bool -> (abs -> bool) -> env -> abs_borrows_loans_maps + Meta.meta -> bool -> (abs -> bool) -> env -> abs_borrows_loans_maps (** Generic functor to implement matching functions between values, environments, etc. @@ -91,6 +91,7 @@ module MakeCheckEquivMatcher : functor (_ : MatchCheckEquivState) -> We return an optional ids map: [Some] if the match succeeded, [None] otherwise. *) val match_ctxs : + Meta.meta -> bool -> ids_sets -> (loan_id -> typed_value) -> @@ -135,7 +136,7 @@ val match_ctxs : - [ctx0] - [ctx1] *) -val ctxs_are_equivalent : ids_sets -> eval_ctx -> eval_ctx -> bool +val ctxs_are_equivalent : Meta.meta -> ids_sets -> eval_ctx -> eval_ctx -> bool (** Reorganize a target context so that we can match it with a source context (remember that the source context is generally the fixed point context, @@ -299,6 +300,7 @@ val prepare_match_ctx_with_target : - [src_ctx] *) val match_ctx_with_target : + Meta.meta -> config -> loop_id -> bool -> diff --git a/compiler/InterpreterPaths.ml b/compiler/InterpreterPaths.ml index cc1e3208..c6db7f2e 100644 --- a/compiler/InterpreterPaths.ml +++ b/compiler/InterpreterPaths.ml @@ -100,8 +100,8 @@ let rec access_projection (meta : Meta.meta) (access : projection_access) (ctx : (* Check consistency *) (match (proj_kind, type_id) with | ProjAdt (def_id, opt_variant_id), TAdtId def_id' -> - assert (def_id = def_id'); - assert (opt_variant_id = adt.variant_id) + cassert (def_id = def_id') meta "TODO: Error message"; + cassert (opt_variant_id = adt.variant_id) meta "TODO: Error message" | _ -> craise meta "Unreachable"); (* Actually project *) let fv = FieldId.nth adt.field_values field_id in @@ -117,7 +117,7 @@ let rec access_projection (meta : Meta.meta) (access : projection_access) (ctx : Ok (ctx, { res with updated })) (* Tuples *) | Field (ProjTuple arity, field_id), VAdt adt, TAdt (TTuple, _) -> ( - assert (arity = List.length adt.field_values); + cassert (arity = List.length adt.field_values) meta "TODO: Error message"; let fv = FieldId.nth adt.field_values field_id in (* Project *) match access_projection meta access ctx update p' fv with @@ -346,30 +346,30 @@ let write_place (meta : Meta.meta) (access : access_kind) (p : place) (nv : type | Error e -> craise meta ("Unreachable: " ^ show_path_fail_kind e) | Ok ctx -> ctx -let compute_expanded_bottom_adt_value (ctx : eval_ctx) (def_id : TypeDeclId.id) +let compute_expanded_bottom_adt_value (meta : Meta.meta) (ctx : eval_ctx) (def_id : TypeDeclId.id) (opt_variant_id : VariantId.id option) (generics : generic_args) : - typed_value = - assert (TypesUtils.generic_args_only_erased_regions generics); + typed_value = + cassert (TypesUtils.generic_args_only_erased_regions generics) meta "TODO: Error message"; (* Lookup the definition and check if it is an enumeration - it should be an enumeration if and only if the projection element is a field projection with *some* variant id. Retrieve the list of fields at the same time. *) - let def = ctx_lookup_type_decl ctx def_id in - assert (List.length generics.regions = List.length def.generics.regions); + let def = ctx_lookup_type_decl ctx def_id in (*TODO: check if can be moved before assert ?*) + cassert (List.length generics.regions = List.length def.generics.regions) meta "TODO: Error message"; (* Compute the field types *) let field_types = AssociatedTypes.type_decl_get_inst_norm_field_etypes ctx def opt_variant_id generics in (* Initialize the expanded value *) - let fields = List.map mk_bottom field_types in + let fields = List.map (mk_bottom meta) field_types in let av = VAdt { variant_id = opt_variant_id; field_values = fields } in let ty = TAdt (TAdtId def_id, generics) in { value = av; ty } -let compute_expanded_bottom_tuple_value (field_types : ety list) : typed_value = +let compute_expanded_bottom_tuple_value (meta : Meta.meta) (field_types : ety list) : typed_value = (* Generate the field values *) - let fields = List.map mk_bottom field_types in + let fields = List.map (mk_bottom meta) field_types in let v = VAdt { variant_id = None; field_values = fields } in let generics = TypesUtils.mk_generic_args [] field_types [] [] in let ty = TAdt (TTuple, generics) in @@ -425,16 +425,16 @@ let expand_bottom_value_from_projection (meta : Meta.meta) (access : access_kind (* "Regular" ADTs *) | ( Field (ProjAdt (def_id, opt_variant_id), _), TAdt (TAdtId def_id', generics) ) -> - assert (def_id = def_id'); - compute_expanded_bottom_adt_value ctx def_id opt_variant_id generics + cassert (def_id = def_id') meta "TODO: Error message"; + compute_expanded_bottom_adt_value meta ctx def_id opt_variant_id generics (* Tuples *) | ( Field (ProjTuple arity, _), TAdt (TTuple, { regions = []; types; const_generics = []; trait_refs = [] }) ) -> - assert (arity = List.length types); + cassert (arity = List.length types) meta "TODO: Error message"; (* Generate the field values *) - compute_expanded_bottom_tuple_value types + compute_expanded_bottom_tuple_value meta types | _ -> craise meta @@ -454,9 +454,9 @@ let rec update_ctx_along_read_place (meta : Meta.meta) (config : config) (access | Error err -> let cc = match err with - | FailSharedLoan bids -> end_borrows config bids - | FailMutLoan bid -> end_borrow config bid - | FailReservedMutBorrow bid -> promote_reserved_mut_borrow config bid + | FailSharedLoan bids -> end_borrows meta config bids + | FailMutLoan bid -> end_borrow meta config bid + | FailReservedMutBorrow bid -> promote_reserved_mut_borrow meta config bid | FailSymbolic (i, sp) -> (* Expand the symbolic value *) let proj, _ = @@ -464,7 +464,7 @@ let rec update_ctx_along_read_place (meta : Meta.meta) (config : config) (access (List.length p.projection - i) in let prefix = { p with projection = proj } in - expand_symbolic_value_no_branching config sp + expand_symbolic_value_no_branching meta config sp (Some (Synth.mk_mplace meta prefix ctx)) | FailBottom (_, _, _) -> (* We can't expand {!Bottom} values while reading them *) @@ -484,12 +484,12 @@ let rec update_ctx_along_write_place (meta : Meta.meta) (config : config) (acces (* Update the context *) let cc = match err with - | FailSharedLoan bids -> end_borrows config bids - | FailMutLoan bid -> end_borrow config bid - | FailReservedMutBorrow bid -> promote_reserved_mut_borrow config bid + | FailSharedLoan bids -> end_borrows meta config bids + | FailMutLoan bid -> end_borrow meta config bid + | FailReservedMutBorrow bid -> promote_reserved_mut_borrow meta config bid | FailSymbolic (_pe, sp) -> (* Expand the symbolic value *) - expand_symbolic_value_no_branching config sp + expand_symbolic_value_no_branching meta config sp (Some (Synth.mk_mplace meta p ctx)) | FailBottom (remaining_pes, pe, ty) -> (* Expand the {!Bottom} value *) @@ -525,7 +525,7 @@ let rec end_loans_at_place (meta : Meta.meta) (config : config) (access : access (* Nothing special to do *) super#visit_borrow_content env bc | VReservedMutBorrow bid -> (* We need to activate reserved borrows *) - let cc = promote_reserved_mut_borrow config bid in + let cc = promote_reserved_mut_borrow meta config bid in raise (UpdateCtx cc) method! visit_loan_content env lc = @@ -536,11 +536,11 @@ let rec end_loans_at_place (meta : Meta.meta) (config : config) (access : access match access with | Read -> super#visit_VSharedLoan env bids v | Write | Move -> - let cc = end_borrows config bids in + let cc = end_borrows meta config bids in raise (UpdateCtx cc)) | VMutLoan bid -> (* We always need to end mutable borrows *) - let cc = end_borrow config bid in + let cc = end_borrow meta config bid in raise (UpdateCtx cc) end in @@ -568,7 +568,7 @@ let drop_outer_loans_at_lplace (meta : Meta.meta) (config : config) (p : place) * a dummy variable *) let access = Write in let v = read_place meta access p ctx in - let ctx = write_place meta access p (mk_bottom v.ty) ctx in + let ctx = write_place meta access p (mk_bottom meta v.ty) ctx in let dummy_id = fresh_dummy_var_id () in let ctx = ctx_push_dummy_var ctx dummy_id v in (* Auxiliary function *) @@ -586,8 +586,8 @@ let drop_outer_loans_at_lplace (meta : Meta.meta) (config : config) (p : place) (* There are: end them then retry *) let cc = match c with - | LoanContent (VSharedLoan (bids, _)) -> end_borrows config bids - | LoanContent (VMutLoan bid) -> end_borrow config bid + | LoanContent (VSharedLoan (bids, _)) -> end_borrows meta config bids + | LoanContent (VMutLoan bid) -> end_borrow meta config bid | BorrowContent _ -> craise meta "Unreachable" in (* Retry *) @@ -603,7 +603,7 @@ let drop_outer_loans_at_lplace (meta : Meta.meta) (config : config) (p : place) (* Reinsert *) let ctx = write_place meta access p v ctx in (* Sanity check *) - assert (not (outer_loans_in_value v)); + cassert (not (outer_loans_in_value v)) meta "TODO: Error message"; (* Continue *) cf ctx) in @@ -616,7 +616,7 @@ let prepare_lplace (meta : Meta.meta) (config : config) (p : place) (cf : typed_ log#ldebug (lazy ("prepare_lplace:" ^ "\n- p: " ^ place_to_string ctx p - ^ "\n- Initial context:\n" ^ eval_ctx_to_string ctx)); + ^ "\n- Initial context:\n" ^ eval_ctx_to_string meta ctx)); (* Access the place *) let access = Write in let cc = update_ctx_along_write_place meta config access p in @@ -627,7 +627,7 @@ let prepare_lplace (meta : Meta.meta) (config : config) (p : place) (cf : typed_ fun ctx -> let v = read_place meta access p ctx in (* Sanity checks *) - assert (not (outer_loans_in_value v)); + cassert (not (outer_loans_in_value v)) meta "TODO: Error message"; (* Continue *) cf v ctx in diff --git a/compiler/InterpreterPaths.mli b/compiler/InterpreterPaths.mli index 3e29b810..faa68688 100644 --- a/compiler/InterpreterPaths.mli +++ b/compiler/InterpreterPaths.mli @@ -13,13 +13,13 @@ type access_kind = Read | Write | Move updates the environment (by ending borrows, expanding symbolic values, etc.) until it manages to fully access the provided place. *) -val update_ctx_along_read_place : config -> access_kind -> place -> cm_fun +val update_ctx_along_read_place : Meta.meta -> config -> access_kind -> place -> cm_fun (** Update the environment to be able to write to a place. See {!update_ctx_along_read_place}. *) -val update_ctx_along_write_place : config -> access_kind -> place -> cm_fun +val update_ctx_along_write_place : Meta.meta -> config -> access_kind -> place -> cm_fun (** Read the value at a given place. @@ -29,7 +29,7 @@ val update_ctx_along_write_place : config -> access_kind -> place -> cm_fun Note that we only access the value at the place, and do not check that the value is "well-formed" (for instance that it doesn't contain bottoms). *) -val read_place : access_kind -> place -> eval_ctx -> typed_value +val read_place : Meta.meta -> access_kind -> place -> eval_ctx -> typed_value (** Update the value at a given place. @@ -40,20 +40,21 @@ val read_place : access_kind -> place -> eval_ctx -> typed_value the overwritten value contains borrows, loans, etc. and will simply overwrite it. *) -val write_place : access_kind -> place -> typed_value -> eval_ctx -> eval_ctx +val write_place : Meta.meta -> access_kind -> place -> typed_value -> eval_ctx -> eval_ctx (** Compute an expanded tuple ⊥ value. [compute_expanded_bottom_tuple_value [ty0, ..., tyn]] returns [(⊥:ty0, ..., ⊥:tyn)] *) -val compute_expanded_bottom_tuple_value : ety list -> typed_value +val compute_expanded_bottom_tuple_value : Meta.meta -> ety list -> typed_value (** Compute an expanded ADT ⊥ value. The types in the generics should use erased regions. *) val compute_expanded_bottom_adt_value : + Meta.meta -> eval_ctx -> TypeDeclId.id -> VariantId.id option -> @@ -73,7 +74,7 @@ val compute_expanded_bottom_adt_value : that the place is *inside* a borrow, if we end the borrow, we won't be able to reinsert the value back). *) -val drop_outer_loans_at_lplace : config -> place -> cm_fun +val drop_outer_loans_at_lplace : Meta.meta -> config -> place -> cm_fun (** End the loans at a given place: read the value, if it contains a loan, end this loan, repeat. @@ -84,7 +85,7 @@ val drop_outer_loans_at_lplace : config -> place -> cm_fun when moving values, we can't move a value which contains loans and thus need to end them, etc. *) -val end_loans_at_place : config -> access_kind -> place -> cm_fun +val end_loans_at_place : Meta.meta -> config -> access_kind -> place -> cm_fun (** Small utility. @@ -95,4 +96,4 @@ val end_loans_at_place : config -> access_kind -> place -> cm_fun place. This value should not contain any outer loan (and we check it is the case). Note that this value is very likely to contain ⊥ subvalues. *) -val prepare_lplace : config -> place -> (typed_value -> m_fun) -> m_fun +val prepare_lplace : Meta.meta -> config -> place -> (typed_value -> m_fun) -> m_fun diff --git a/compiler/InterpreterProjectors.ml b/compiler/InterpreterProjectors.ml index d4a237b2..fff23aec 100644 --- a/compiler/InterpreterProjectors.ml +++ b/compiler/InterpreterProjectors.ml @@ -18,7 +18,7 @@ let rec apply_proj_borrows_on_shared_borrow (meta : Meta.meta) (ctx : eval_ctx) (* Sanity check - TODO: move those elsewhere (here we perform the check at every * recursive call which is a bit overkill...) *) let ety = Subst.erase_regions ty in - assert (ty_is_rty ty && ety = v.ty); + cassert (ty_is_rty ty && ety = v.ty) meta "TODO: error message"; (* Project - if there are no regions from the abstraction in the type, return [_] *) if not (ty_has_regions_in_set regions ty) then [] else @@ -27,7 +27,7 @@ let rec apply_proj_borrows_on_shared_borrow (meta : Meta.meta) (ctx : eval_ctx) | VAdt adt, TAdt (id, generics) -> (* Retrieve the types of the fields *) let field_types = - Assoc.ctx_adt_value_get_inst_norm_field_rtypes ctx adt id generics + Assoc.ctx_adt_value_get_inst_norm_field_rtypes meta ctx adt id generics in (* Project over the field values *) @@ -84,7 +84,7 @@ let rec apply_proj_borrows_on_shared_borrow (meta : Meta.meta) (ctx : eval_ctx) | VLoan _, _ -> craise meta "Unreachable" | VSymbolic s, _ -> (* Check that the projection doesn't contain ended regions *) - assert (not (projections_intersect meta s.sv_ty ctx.ended_regions ty regions)); + cassert (not (projections_intersect meta s.sv_ty ctx.ended_regions ty regions)) meta "TODO: error message"; [ AsbProjReborrows (s, ty) ] | _ -> craise meta "Unreachable" @@ -95,7 +95,7 @@ let rec apply_proj_borrows (meta : Meta.meta) (check_symbolic_no_ended : bool) ( (* Sanity check - TODO: move this elsewhere (here we perform the check at every * recursive call which is a bit overkill...) *) let ety = Substitute.erase_regions ty in - assert (ty_is_rty ty && ety = v.ty); + cassert (ty_is_rty ty && ety = v.ty) meta "TODO: error message"; (* Project - if there are no regions from the abstraction in the type, return [_] *) if not (ty_has_regions_in_set regions ty) then { value = AIgnored; ty } else @@ -105,7 +105,7 @@ let rec apply_proj_borrows (meta : Meta.meta) (check_symbolic_no_ended : bool) ( | VAdt adt, TAdt (id, generics) -> (* Retrieve the types of the fields *) let field_types = - Assoc.ctx_adt_value_get_inst_norm_field_rtypes ctx adt id generics + Assoc.ctx_adt_value_get_inst_norm_field_rtypes meta ctx adt id generics in (* Project over the field values *) let fields_types = List.combine adt.field_values field_types in @@ -212,13 +212,13 @@ let rec apply_proj_borrows (meta : Meta.meta) (check_symbolic_no_ended : bool) ( ^ "\n- ty2: " ^ ty_to_string ctx ty2 ^ "\n- rset2: " ^ RegionId.Set.to_string None rset2 ^ "\n")); - assert (not (projections_intersect meta ty1 rset1 ty2 rset2))); + cassert (not (projections_intersect meta ty1 rset1 ty2 rset2))) meta "TODO: error message"; ASymbolic (AProjBorrows (s, ty)) | _ -> log#lerror (lazy ("apply_proj_borrows: unexpected inputs:\n- input value: " - ^ typed_value_to_string ctx v + ^ typed_value_to_string meta ctx v ^ "\n- proj rty: " ^ ty_to_string ctx ty)); craise meta "Unreachable" in @@ -261,7 +261,7 @@ let apply_proj_loans_on_symbolic_expansion (meta : Meta.meta) (regions : RegionI (original_sv_ty : rty) : typed_avalue = (* Sanity check: if we have a proj_loans over a symbolic value, it should * contain regions which we will project *) - assert (ty_has_regions_in_set regions original_sv_ty); + cassert (ty_has_regions_in_set regions original_sv_ty) meta "TODO: error message"; (* Match *) let (value, ty) : avalue * ty = match (see, original_sv_ty) with @@ -276,7 +276,7 @@ let apply_proj_loans_on_symbolic_expansion (meta : Meta.meta) (regions : RegionI (AAdt { variant_id; field_values }, original_sv_ty) | SeMutRef (bid, spc), TRef (r, ref_ty, RMut) -> (* Sanity check *) - assert (spc.sv_ty = ref_ty); + cassert (spc.sv_ty = ref_ty) meta "TODO: error message"; (* Apply the projector to the borrowed value *) let child_av = mk_aproj_loans_value_from_symbolic_value regions spc in (* Check if the region is in the set of projected regions (note that @@ -294,7 +294,7 @@ let apply_proj_loans_on_symbolic_expansion (meta : Meta.meta) (regions : RegionI (ALoan (AIgnoredMutLoan (opt_bid, child_av)), ref_ty) | SeSharedRef (bids, spc), TRef (r, ref_ty, RShared) -> (* Sanity check *) - assert (spc.sv_ty = ref_ty); + cassert (spc.sv_ty = ref_ty) meta "TODO: error message"; (* Apply the projector to the borrowed value *) let child_av = mk_aproj_loans_value_from_symbolic_value regions spc in (* Check if the region is in the set of projected regions (note that @@ -332,7 +332,7 @@ let apply_proj_loans_on_symbolic_expansion (meta : Meta.meta) (regions : RegionI borrows - easy - and mutable borrows - in this case, we reborrow the whole borrow: [mut_borrow ... ~~> shared_loan {...} (mut_borrow ...)]). *) -let apply_reborrows (reborrows : (BorrowId.id * BorrowId.id) list) +let apply_reborrows (meta : Meta.meta) (reborrows : (BorrowId.id * BorrowId.id) list) (ctx : eval_ctx) : eval_ctx = (* This is a bit brutal, but whenever we insert a reborrow, we remove * it from the list. This allows us to check that all the reborrows were @@ -464,7 +464,7 @@ let apply_reborrows (reborrows : (BorrowId.id * BorrowId.id) list) (* Visit *) let ctx = obj#visit_eval_ctx () ctx in (* Check that there are no reborrows remaining *) - assert (!reborrows = []); + cassert (!reborrows = []) meta "TODO: error message"; (* Return *) ctx @@ -483,11 +483,11 @@ let prepare_reborrows (meta : Meta.meta) (config : config) (allow_reborrows : bo let apply_registered_reborrows (ctx : eval_ctx) : eval_ctx = match config.mode with | ConcreteMode -> - assert (!reborrows = []); + cassert (!reborrows = []) meta "TODO: error message"; ctx | SymbolicMode -> (* Apply the reborrows *) - apply_reborrows !reborrows ctx + apply_reborrows meta !reborrows ctx in (fresh_reborrow, apply_registered_reborrows) @@ -495,7 +495,7 @@ let prepare_reborrows (meta : Meta.meta) (config : config) (allow_reborrows : bo let apply_proj_borrows_on_input_value (meta : Meta.meta) (config : config) (ctx : eval_ctx) (regions : RegionId.Set.t) (ancestors_regions : RegionId.Set.t) (v : typed_value) (ty : rty) : eval_ctx * typed_avalue = - assert (ty_is_rty ty); + cassert (ty_is_rty ty) meta "TODO: error message"; let check_symbolic_no_ended = true in let allow_reborrows = true in (* Prepare the reborrows *) diff --git a/compiler/InterpreterProjectors.mli b/compiler/InterpreterProjectors.mli index 9e4ebc20..7ffe4917 100644 --- a/compiler/InterpreterProjectors.mli +++ b/compiler/InterpreterProjectors.mli @@ -15,11 +15,11 @@ open Contexts [original_sv_ty]: shouldn't have erased regions *) val apply_proj_loans_on_symbolic_expansion : - RegionId.Set.t -> RegionId.Set.t -> symbolic_expansion -> rty -> typed_avalue + Meta.meta -> RegionId.Set.t -> RegionId.Set.t -> symbolic_expansion -> rty -> typed_avalue (** Convert a symbolic expansion *which is not a borrow* to a value *) val symbolic_expansion_non_borrow_to_value : - symbolic_value -> symbolic_expansion -> typed_value + Meta.meta -> symbolic_value -> symbolic_expansion -> typed_value (** Convert a symbolic expansion *which is not a shared borrow* to a value. @@ -28,7 +28,7 @@ val symbolic_expansion_non_borrow_to_value : during a symbolic expansion. *) val symbolic_expansion_non_shared_borrow_to_value : - symbolic_value -> symbolic_expansion -> typed_value + Meta.meta -> symbolic_value -> symbolic_expansion -> typed_value (** Auxiliary function to prepare reborrowing operations (used when applying projectors). @@ -43,7 +43,7 @@ val symbolic_expansion_non_shared_borrow_to_value : - [allow_reborrows] *) val prepare_reborrows : - config -> bool -> (BorrowId.id -> BorrowId.id) * (eval_ctx -> eval_ctx) + Meta.meta -> config -> bool -> (BorrowId.id -> BorrowId.id) * (eval_ctx -> eval_ctx) (** Apply (and reduce) a projector over borrows to an avalue. We use this for instance to spread the borrows present in the inputs @@ -96,6 +96,7 @@ val prepare_reborrows : then we interpret the borrow [l] as belonging to region [r] *) val apply_proj_borrows : + Meta.meta -> bool -> eval_ctx -> (BorrowId.id -> BorrowId.id) -> @@ -115,6 +116,7 @@ val apply_proj_borrows : erased regions) *) val apply_proj_borrows_on_input_value : + Meta.meta -> config -> eval_ctx -> RegionId.Set.t -> diff --git a/compiler/InterpreterStatements.ml b/compiler/InterpreterStatements.ml index 8ccdcc93..e71b7b68 100644 --- a/compiler/InterpreterStatements.ml +++ b/compiler/InterpreterStatements.ml @@ -19,33 +19,33 @@ module S = SynthesizeSymbolic let log = L.statements_log (** Drop a value at a given place - TODO: factorize this with [assign_to_place] *) -let drop_value (config : config) (p : place) : cm_fun = +let drop_value (meta : Meta.meta) (config : config) (p : place) : cm_fun = fun cf ctx -> log#ldebug (lazy ("drop_value: place: " ^ place_to_string ctx p ^ "\n- Initial context:\n" - ^ eval_ctx_to_string ctx)); + ^ eval_ctx_to_string meta ctx)); (* Note that we use [Write], not [Move]: we allow to drop values *below* borrows *) let access = Write in (* First make sure we can access the place, by ending loans or expanding * symbolic values along the path, for instance *) - let cc = update_ctx_along_read_place config access p in + let cc = update_ctx_along_read_place meta config access p in (* Prepare the place (by ending the outer loans *at* the place). *) - let cc = comp cc (prepare_lplace config p) in + let cc = comp cc (prepare_lplace meta config p) in (* Replace the value with {!Bottom} *) let replace cf (v : typed_value) ctx = (* Move the value at destination (that we will overwrite) to a dummy variable * to preserve the borrows it may contain *) - let mv = InterpreterPaths.read_place access p ctx in + let mv = InterpreterPaths.read_place meta access p ctx in let dummy_id = fresh_dummy_var_id () in let ctx = ctx_push_dummy_var ctx dummy_id mv in (* Update the destination to ⊥ *) let nv = { v with value = VBottom } in - let ctx = write_place access p nv ctx in + let ctx = write_place meta access p nv ctx in log#ldebug (lazy ("drop_value: place: " ^ place_to_string ctx p ^ "\n- Final context:\n" - ^ eval_ctx_to_string ctx)); + ^ eval_ctx_to_string meta ctx)); cf ctx in (* Compose and apply *) @@ -99,14 +99,14 @@ let assign_to_place (meta : Meta.meta) (config : config) (rv : typed_value) (p : log#ldebug (lazy ("assign_to_place:" ^ "\n- rv: " - ^ typed_value_to_string ctx rv + ^ typed_value_to_string meta ctx rv ^ "\n- p: " ^ place_to_string ctx p ^ "\n- Initial context:\n" - ^ eval_ctx_to_string ctx)); + ^ eval_ctx_to_string meta ctx)); (* Push the rvalue to a dummy variable, for bookkeeping *) let rvalue_vid = fresh_dummy_var_id () in let cc = push_dummy_var rvalue_vid rv in (* Prepare the destination *) - let cc = comp cc (prepare_lplace config p) in + let cc = comp cc (prepare_lplace meta config p) in (* Retrieve the rvalue from the dummy variable *) let cc = comp cc (fun cf _lv -> remove_dummy_var meta rvalue_vid cf) in (* Update the destination *) @@ -114,21 +114,21 @@ let assign_to_place (meta : Meta.meta) (config : config) (rv : typed_value) (p : fun ctx -> (* Move the value at destination (that we will overwrite) to a dummy variable * to preserve the borrows *) - let mv = InterpreterPaths.read_place Write p ctx in + let mv = InterpreterPaths.read_place meta Write p ctx in let dest_vid = fresh_dummy_var_id () in let ctx = ctx_push_dummy_var ctx dest_vid mv in (* Write to the destination *) (* Checks - maybe the bookkeeping updated the rvalue and introduced bottoms *) cassert (not (bottom_in_value ctx.ended_regions rv)) meta "TODO: Error message"; (* Update the destination *) - let ctx = write_place Write p rv ctx in + let ctx = write_place meta Write p rv ctx in (* Debug *) log#ldebug (lazy ("assign_to_place:" ^ "\n- rv: " - ^ typed_value_to_string ctx rv + ^ typed_value_to_string meta ctx rv ^ "\n- p: " ^ place_to_string ctx p ^ "\n- Final context:\n" - ^ eval_ctx_to_string ctx)); + ^ eval_ctx_to_string meta ctx)); (* Continue *) cf ctx in @@ -140,7 +140,7 @@ let eval_assertion_concrete (meta : Meta.meta) (config : config) (assertion : as st_cm_fun = fun cf ctx -> (* There won't be any symbolic expansions: fully evaluate the operand *) - let eval_op = eval_operand config assertion.cond in + let eval_op = eval_operand meta config assertion.cond in let eval_assert cf (v : typed_value) : m_fun = fun ctx -> match v.value with @@ -149,7 +149,7 @@ let eval_assertion_concrete (meta : Meta.meta) (config : config) (assertion : as if b = assertion.expected then cf Unit ctx else cf Panic ctx | _ -> craise - meta ("Expected a boolean, got: " ^ typed_value_to_string ctx v) + meta ("Expected a boolean, got: " ^ typed_value_to_string meta ctx v) in (* Compose and apply *) comp eval_op eval_assert cf ctx @@ -163,7 +163,7 @@ let eval_assertion_concrete (meta : Meta.meta) (config : config) (assertion : as let eval_assertion (meta : Meta.meta) (config : config) (assertion : assertion) : st_cm_fun = fun cf ctx -> (* Evaluate the operand *) - let eval_op = eval_operand config assertion.cond in + let eval_op = eval_operand meta config assertion.cond in (* Evaluate the assertion *) let eval_assert cf (v : typed_value) : m_fun = fun ctx -> @@ -185,7 +185,7 @@ let eval_assertion (meta : Meta.meta) (config : config) (assertion : assertion) * We will of course synthesize an assertion in the generated code * (see below). *) let ctx = - apply_symbolic_expansion_non_borrow config sv (SeLiteral (VBool true)) + apply_symbolic_expansion_non_borrow meta config sv (SeLiteral (VBool true)) ctx in (* Continue *) @@ -194,7 +194,7 @@ let eval_assertion (meta : Meta.meta) (config : config) (assertion : assertion) S.synthesize_assertion ctx v expr | _ -> craise - meta ("Expected a boolean, got: " ^ typed_value_to_string ctx v) + meta ("Expected a boolean, got: " ^ typed_value_to_string meta ctx v) in (* Compose and apply *) comp eval_op eval_assert cf ctx @@ -218,11 +218,11 @@ let set_discriminant (meta : Meta.meta) (config : config) (p : place) (variant_i ("set_discriminant:" ^ "\n- p: " ^ place_to_string ctx p ^ "\n- variant id: " ^ VariantId.to_string variant_id - ^ "\n- initial context:\n" ^ eval_ctx_to_string ctx)); + ^ "\n- initial context:\n" ^ eval_ctx_to_string meta ctx)); (* Access the value *) let access = Write in - let cc = update_ctx_along_read_place config access p in - let cc = comp cc (prepare_lplace config p) in + let cc = update_ctx_along_read_place meta config access p in + let cc = comp cc (prepare_lplace meta config p) in (* Update the value *) let update_value cf (v : typed_value) : m_fun = fun ctx -> @@ -244,7 +244,7 @@ let set_discriminant (meta : Meta.meta) (config : config) (p : place) (variant_i let bottom_v = match type_id with | TAdtId def_id -> - compute_expanded_bottom_adt_value ctx def_id + compute_expanded_bottom_adt_value meta ctx def_id (Some variant_id) generics | _ -> craise meta "Unreachable" in @@ -253,7 +253,7 @@ let set_discriminant (meta : Meta.meta) (config : config) (p : place) (variant_i let bottom_v = match type_id with | TAdtId def_id -> - compute_expanded_bottom_adt_value ctx def_id (Some variant_id) + compute_expanded_bottom_adt_value meta ctx def_id (Some variant_id) generics | _ -> craise meta "Unreachable" in @@ -311,12 +311,12 @@ let get_assumed_function_return_type (meta : Meta.meta) (ctx : eval_ctx) (fid : in AssociatedTypes.ctx_normalize_erase_ty ctx ty -let move_return_value (config : config) (pop_return_value : bool) +let move_return_value (config : config) (meta : Meta.meta) (pop_return_value : bool) (cf : typed_value option -> m_fun) : m_fun = fun ctx -> if pop_return_value then let ret_vid = VarId.zero in - let cc = eval_operand config (Move (mk_place_from_var_id ret_vid)) in + let cc = eval_operand meta config (Move (mk_place_from_var_id ret_vid)) in cc (fun v ctx -> cf (Some v) ctx) ctx else cf None ctx @@ -324,7 +324,7 @@ let pop_frame (meta : Meta.meta) (config : config) (pop_return_value : bool) (cf : typed_value option -> m_fun) : m_fun = fun ctx -> (* Debug *) - log#ldebug (lazy ("pop_frame:\n" ^ eval_ctx_to_string ctx)); + log#ldebug (lazy ("pop_frame:\n" ^ eval_ctx_to_string meta ctx)); (* List the local variables, but the return variable *) let ret_vid = VarId.zero in @@ -347,7 +347,7 @@ let pop_frame (meta : Meta.meta) (config : config) (pop_return_value : bool) ^ "]")); (* Move the return value out of the return variable *) - let cc = move_return_value config pop_return_value in + let cc = move_return_value config meta pop_return_value in (* Sanity check *) let cc = comp_check_value cc (fun ret_value ctx -> @@ -364,7 +364,7 @@ let pop_frame (meta : Meta.meta) (config : config) (pop_return_value : bool) let cf_drop = List.fold_left (fun cf lid -> - drop_outer_loans_at_lplace config (mk_place_from_var_id lid) cf) + drop_outer_loans_at_lplace meta config (mk_place_from_var_id lid) cf) (cf ret_value) locals in (* Apply *) @@ -377,7 +377,7 @@ let pop_frame (meta : Meta.meta) (config : config) (pop_return_value : bool) log#ldebug (lazy ("pop_frame: after dropping outer loans in local variables:\n" - ^ eval_ctx_to_string ctx))) + ^ eval_ctx_to_string meta ctx))) in (* Pop the frame - we remove the [Frame] delimiter, and reintroduce all @@ -427,7 +427,7 @@ let eval_box_new_concrete (meta : Meta.meta) (config : config) (generics : gener (* Move the input value *) let cf_move = - eval_operand config (Move (mk_place_from_var_id input_var.index)) + eval_operand meta config (Move (mk_place_from_var_id input_var.index)) in (* Create the new box *) @@ -438,7 +438,7 @@ let eval_box_new_concrete (meta : Meta.meta) (config : config) (generics : gener let box_v = VAdt { variant_id = None; field_values = [ moved_input_value ] } in - let box_v = mk_typed_value box_ty box_v in + let box_v = mk_typed_value meta box_ty box_v in (* Move this value to the return variable *) let dest = mk_place_from_var_id VarId.zero in @@ -477,12 +477,12 @@ let eval_box_free (meta : Meta.meta) (config : config) (generics : generic_args) match (generics.regions, generics.types, generics.const_generics, args) with | [], [ boxed_ty ], [], [ Move input_box_place ] -> (* Required type checking *) - let input_box = InterpreterPaths.read_place Write input_box_place ctx in + let input_box = InterpreterPaths.read_place meta Write input_box_place ctx in (let input_ty = ty_get_box input_box.ty in cassert (input_ty = boxed_ty)) meta "TODO: Error message"; (* Drop the value *) - let cc = drop_value config input_box_place in + let cc = drop_value meta config input_box_place in (* Update the destination by setting it to [()] *) let cc = comp cc (assign_to_place meta config mk_unit_value dest) in @@ -519,7 +519,7 @@ let eval_assumed_function_call_concrete (meta : Meta.meta) (config : config) (fi (* "Normal" case: not box_free *) (* Evaluate the operands *) (* let ctx, args_vl = eval_operands config ctx args in *) - let cf_eval_ops = eval_operands config args in + let cf_eval_ops = eval_operands meta config args in (* Evaluate the call * @@ -758,7 +758,7 @@ let eval_transparent_function_call_symbolic_inst (meta : Meta.meta) (call : call ctx.fun_ctx.regions_hierarchies in let inst_sg = - instantiate_fun_sig ctx func.generics tr_self def.signature + instantiate_fun_sig meta ctx func.generics tr_self def.signature regions_hierarchy in (func.func, func.generics, None, def, regions_hierarchy, inst_sg) @@ -805,7 +805,7 @@ let eval_transparent_function_call_symbolic_inst (meta : Meta.meta) (call : call ctx.fun_ctx.regions_hierarchies in let inst_sg = - instantiate_fun_sig ctx generics tr_self + instantiate_fun_sig meta ctx generics tr_self method_def.signature regions_hierarchy in (* Also update the function identifier: we want to forget @@ -871,7 +871,7 @@ let eval_transparent_function_call_symbolic_inst (meta : Meta.meta) (call : call in let tr_self = TraitRef trait_ref in let inst_sg = - instantiate_fun_sig ctx all_generics tr_self + instantiate_fun_sig meta ctx all_generics tr_self method_def.signature regions_hierarchy in ( func.func, @@ -913,7 +913,7 @@ let eval_transparent_function_call_symbolic_inst (meta : Meta.meta) (call : call in let tr_self = TraitRef trait_ref in let inst_sg = - instantiate_fun_sig ctx generics tr_self method_def.signature + instantiate_fun_sig meta ctx generics tr_self method_def.signature regions_hierarchy in ( func.func, @@ -924,22 +924,22 @@ let eval_transparent_function_call_symbolic_inst (meta : Meta.meta) (call : call inst_sg ))) (** Evaluate a statement *) -let rec eval_statement (meta : Meta.meta) (config : config) (st : statement) : st_cm_fun = +let rec eval_statement (config : config) (st : statement) : st_cm_fun = fun cf ctx -> (* Debugging *) log#ldebug (lazy ("\n**About to evaluate statement**: [\n" ^ statement_to_string_with_tab ctx st - ^ "\n]\n\n**Context**:\n" ^ eval_ctx_to_string ctx ^ "\n\n")); + ^ "\n]\n\n**Context**:\n" ^ eval_ctx_to_string st.meta ctx ^ "\n\n")); (* Take a snapshot of the current context for the purpose of generating pretty names *) let cc = S.cf_save_snapshot in (* Expand the symbolic values if necessary - we need to do that before * checking the invariants *) - let cc = comp cc (greedy_expand_symbolic_values config) in + let cc = comp cc (greedy_expand_symbolic_values st.meta config) in (* Sanity check *) - let cc = comp cc (Invariants.cf_check_invariants meta) in + let cc = comp cc (Invariants.cf_check_invariants st.meta) in (* Evaluate *) let cf_eval_st cf : m_fun = @@ -955,47 +955,47 @@ let rec eval_statement (meta : Meta.meta) (config : config) (st : statement) : s match rvalue with | Global (gid, generics) -> (* Evaluate the global *) - eval_global meta config p gid generics cf ctx + eval_global config p gid generics cf ctx | _ -> (* Evaluate the rvalue *) - let cf_eval_rvalue = eval_rvalue_not_global config rvalue in + let cf_eval_rvalue = eval_rvalue_not_global st.meta config rvalue in (* Assign *) let cf_assign cf (res : (typed_value, eval_error) result) ctx = log#ldebug (lazy ("about to assign to place: " ^ place_to_string ctx p - ^ "\n- Context:\n" ^ eval_ctx_to_string ctx)); + ^ "\n- Context:\n" ^ eval_ctx_to_string st.meta ctx)); match res with | Error EPanic -> cf Panic ctx | Ok rv -> ( - let expr = assign_to_place meta config rv p (cf Unit) ctx in + let expr = assign_to_place st.meta config rv p (cf Unit) ctx in (* Update the synthesized AST - here we store meta-information. * We do it only in specific cases (it is not always useful, and * also it can lead to issues - for instance, if we borrow a * reserved borrow, we later can't translate it to pure values...) *) match rvalue with - | Global _ -> craise meta "Unreachable" + | Global _ -> craise st.meta "Unreachable" | Use _ | RvRef (_, (BShared | BMut | BTwoPhaseMut | BShallow)) | UnaryOp _ | BinaryOp _ | Discriminant _ | Aggregate _ -> let rp = rvalue_get_place rvalue in let rp = match rp with - | Some rp -> Some (S.mk_mplace meta rp ctx) + | Some rp -> Some (S.mk_mplace st.meta rp ctx) | None -> None in - S.synthesize_assignment ctx (S.mk_mplace meta p ctx) rv rp expr + S.synthesize_assignment ctx (S.mk_mplace st.meta p ctx) rv rp expr ) in (* Compose and apply *) comp cf_eval_rvalue cf_assign cf ctx) - | FakeRead p -> eval_fake_read config p (cf Unit) ctx + | FakeRead p -> eval_fake_read st.meta config p (cf Unit) ctx | SetDiscriminant (p, variant_id) -> - set_discriminant meta config p variant_id cf ctx - | Drop p -> drop_value config p (cf Unit) ctx - | Assert assertion -> eval_assertion meta config assertion cf ctx - | Call call -> eval_function_call meta config call cf ctx + set_discriminant st.meta config p variant_id cf ctx + | Drop p -> drop_value st.meta config p (cf Unit) ctx + | Assert assertion -> eval_assertion st.meta config assertion cf ctx + | Call call -> eval_function_call st.meta config call cf ctx | Panic -> cf Panic ctx | Return -> cf Return ctx | Break i -> cf (Break i) ctx @@ -1003,12 +1003,12 @@ let rec eval_statement (meta : Meta.meta) (config : config) (st : statement) : s | Nop -> cf Unit ctx | Sequence (st1, st2) -> (* Evaluate the first statement *) - let cf_st1 = eval_statement meta config st1 in + let cf_st1 = eval_statement config st1 in (* Evaluate the sequence *) let cf_st2 cf res = match res with (* Evaluation successful: evaluate the second statement *) - | Unit -> eval_statement meta config st2 cf + | Unit -> eval_statement config st2 cf (* Control-flow break: transmit. We enumerate the cases on purpose *) | Panic | Break _ | Continue _ | Return | LoopReturn _ | EndEnterLoop _ | EndContinue _ -> @@ -1018,14 +1018,14 @@ let rec eval_statement (meta : Meta.meta) (config : config) (st : statement) : s comp cf_st1 cf_st2 cf ctx | Loop loop_body -> InterpreterLoops.eval_loop config st.meta - (eval_statement meta config loop_body) + (eval_statement config loop_body) cf ctx - | Switch switch -> eval_switch meta config switch cf ctx + | Switch switch -> eval_switch st.meta config switch cf ctx in (* Compose and apply *) comp cc cf_eval_st cf ctx -and eval_global (meta : Meta.meta) (config : config) (dest : place) (gid : GlobalDeclId.id) +and eval_global (config : config) (dest : place) (gid : GlobalDeclId.id) (generics : generic_args) : st_cm_fun = fun cf ctx -> let global = ctx_lookup_global_decl ctx gid in @@ -1034,7 +1034,7 @@ and eval_global (meta : Meta.meta) (config : config) (dest : place) (gid : Globa (* Treat the evaluation of the global as a call to the global body *) let func = { func = FunId (FRegular global.body); generics } in let call = { func = FnOpRegular func; args = []; dest } in - (eval_transparent_function_call_concrete meta config global.body call) cf ctx + (eval_transparent_function_call_concrete global.meta config global.body call) cf ctx | SymbolicMode -> (* Generate a fresh symbolic value. In the translation, this fresh symbolic value will be * defined as equal to the value of the global (see {!S.synthesize_global_eval}). *) @@ -1052,7 +1052,7 @@ and eval_global (meta : Meta.meta) (config : config) (dest : place) (gid : Globa in let sval = mk_fresh_symbolic_value ty in let cc = - assign_to_place meta config (mk_typed_value_from_symbolic_value sval) dest + assign_to_place global.meta config (mk_typed_value_from_symbolic_value sval) dest in let e = cc (cf Unit) ctx in S.synthesize_global_eval gid generics sval e @@ -1074,7 +1074,7 @@ and eval_switch (meta : Meta.meta) (config : config) (switch : switch) : st_cm_f match switch with | If (op, st1, st2) -> (* Evaluate the operand *) - let cf_eval_op = eval_operand config op in + let cf_eval_op = eval_operand meta config op in (* Switch on the value *) let cf_if (cf : st_m_fun) (op_v : typed_value) : m_fun = fun ctx -> @@ -1083,17 +1083,17 @@ and eval_switch (meta : Meta.meta) (config : config) (switch : switch) : st_cm_f (* Evaluate the if and the branch body *) let cf_branch cf : m_fun = (* Branch *) - if b then eval_statement meta config st1 cf - else eval_statement meta config st2 cf + if b then eval_statement config st1 cf + else eval_statement config st2 cf in (* Compose the continuations *) cf_branch cf ctx | VSymbolic sv -> (* Expand the symbolic boolean, and continue by evaluating * the branches *) - let cf_true : st_cm_fun = eval_statement meta config st1 in - let cf_false : st_cm_fun = eval_statement meta config st2 in - expand_symbolic_bool config sv + let cf_true : st_cm_fun = eval_statement config st1 in + let cf_false : st_cm_fun = eval_statement config st2 in + expand_symbolic_bool meta config sv (S.mk_opt_place_from_op meta op ctx) cf_true cf_false cf ctx | _ -> craise meta "Inconsistent state" @@ -1102,7 +1102,7 @@ and eval_switch (meta : Meta.meta) (config : config) (switch : switch) : st_cm_f comp cf_eval_op cf_if cf ctx | SwitchInt (op, int_ty, stgts, otherwise) -> (* Evaluate the operand *) - let cf_eval_op = eval_operand config op in + let cf_eval_op = eval_operand meta config op in (* Switch on the value *) let cf_switch (cf : st_m_fun) (op_v : typed_value) : m_fun = fun ctx -> @@ -1114,8 +1114,8 @@ and eval_switch (meta : Meta.meta) (config : config) (switch : switch) : st_cm_f cassert (sv.int_ty = int_ty) meta "TODO: Error message"; (* Find the branch *) match List.find_opt (fun (svl, _) -> List.mem sv svl) stgts with - | None -> eval_statement meta config otherwise cf - | Some (_, tgt) -> eval_statement meta config tgt cf + | None -> eval_statement config otherwise cf + | Some (_, tgt) -> eval_statement config tgt cf in (* Compose *) cf_eval_branch cf ctx @@ -1124,7 +1124,7 @@ and eval_switch (meta : Meta.meta) (config : config) (switch : switch) : st_cm_f * proper branches *) let stgts = List.map - (fun (cv, tgt_st) -> (cv, eval_statement meta config tgt_st)) + (fun (cv, tgt_st) -> (cv, eval_statement config tgt_st)) stgts in (* Several branches may be grouped together: every branch is described @@ -1138,9 +1138,9 @@ and eval_switch (meta : Meta.meta) (config : config) (switch : switch) : st_cm_f stgts) in (* Translate the otherwise branch *) - let otherwise = eval_statement meta config otherwise in + let otherwise = eval_statement config otherwise in (* Expand and continue *) - expand_symbolic_int config sv + expand_symbolic_int meta config sv (S.mk_opt_place_from_op meta op ctx) int_ty stgts otherwise cf ctx | _ -> craise meta "Inconsistent state" @@ -1152,7 +1152,7 @@ and eval_switch (meta : Meta.meta) (config : config) (switch : switch) : st_cm_f let access = Read in let expand_prim_copy = false in let cf_read_p cf : m_fun = - access_rplace_reorganize_and_read config expand_prim_copy access p cf + access_rplace_reorganize_and_read meta config expand_prim_copy access p cf in (* Match on the value *) let cf_match (cf : st_m_fun) (p_v : typed_value) : m_fun = @@ -1170,12 +1170,12 @@ and eval_switch (meta : Meta.meta) (config : config) (switch : switch) : st_cm_f | None -> ( match otherwise with | None -> craise meta "No otherwise branch" - | Some otherwise -> eval_statement meta config otherwise cf ctx) - | Some (_, tgt) -> eval_statement meta config tgt cf ctx) + | Some otherwise -> eval_statement config otherwise cf ctx) + | Some (_, tgt) -> eval_statement config tgt cf ctx) | VSymbolic sv -> (* Expand the symbolic value - may lead to branching *) let cf_expand = - expand_symbolic_adt config sv (Some (S.mk_mplace meta p ctx)) + expand_symbolic_adt meta config sv (Some (S.mk_mplace meta p ctx)) in (* Re-evaluate the switch - the value is not symbolic anymore, which means we will go to the other branch *) @@ -1251,7 +1251,7 @@ and eval_transparent_function_call_concrete (meta : Meta.meta) (config : config) | Some body -> body in (* TODO: we need to normalize the types if we want to correctly support traits *) - cassert (generics.trait_refs = []) meta "Traits are not supported yet TODO: error message"; + cassert (generics.trait_refs = []) body.meta "Traits are not supported yet TODO: error message"; (* There shouldn't be any reference to Self *) let tr_self = UnknownTrait __FUNCTION__ in let subst = @@ -1260,8 +1260,8 @@ and eval_transparent_function_call_concrete (meta : Meta.meta) (config : config) let locals, body_st = Subst.fun_body_substitute_in_body subst body in (* Evaluate the input operands *) - cassert (List.length args = body.arg_count) meta "TODO: Error message"; - let cc = eval_operands config args in + cassert (List.length args = body.arg_count) body.meta "TODO: Error message"; + let cc = eval_operands body.meta config args in (* Push a frame delimiter - we use {!comp_transmit} to transmit the result * of the operands evaluation from above to the functions afterwards, while @@ -1280,7 +1280,7 @@ and eval_transparent_function_call_concrete (meta : Meta.meta) (config : config) in let cc = - comp_transmit cc (push_var meta ret_var (mk_bottom ret_var.var_ty)) + comp_transmit cc (push_var meta ret_var (mk_bottom meta ret_var.var_ty)) in (* 2. Push the input values *) @@ -1323,9 +1323,9 @@ and eval_transparent_function_call_symbolic (meta : Meta.meta) (config : config) eval_transparent_function_call_symbolic_inst meta call ctx in (* Sanity check *) - cassert (List.length call.args = List.length def.signature.inputs) meta "TODO: Error message"; + cassert (List.length call.args = List.length def.signature.inputs) def.meta "TODO: Error message"; (* Evaluate the function call *) - eval_function_call_symbolic_from_inst_sig meta config func def.signature + eval_function_call_symbolic_from_inst_sig def.meta config func def.signature regions_hierarchy inst_sg generics trait_method_generics call.args call.dest cf ctx @@ -1361,7 +1361,7 @@ and eval_function_call_symbolic_from_inst_sig (meta : Meta.meta) (config : confi (* Generate a fresh symbolic value for the return value *) let ret_sv_ty = inst_sg.output in - let ret_spc = mk_fresh_symbolic_value ret_sv_ty in + let ret_spc = mk_fresh_symbolic_value meta ret_sv_ty in let ret_value = mk_typed_value_from_symbolic_value ret_spc in let ret_av regions = mk_aproj_loans_value_from_symbolic_value regions ret_spc @@ -1370,7 +1370,7 @@ and eval_function_call_symbolic_from_inst_sig (meta : Meta.meta) (config : confi let dest_place = Some (S.mk_mplace meta dest ctx) in (* Evaluate the input operands *) - let cc = eval_operands config args in + let cc = eval_operands meta config args in (* Generate the abstractions and insert them in the context *) let abs_ids = List.map (fun rg -> rg.id) inst_sg.regions_hierarchy in @@ -1404,7 +1404,7 @@ and eval_function_call_symbolic_from_inst_sig (meta : Meta.meta) (config : confi let ctx, args_projs = List.fold_left_map (fun ctx (arg, arg_rty) -> - apply_proj_borrows_on_input_value config ctx abs.regions + apply_proj_borrows_on_input_value meta config ctx abs.regions abs.ancestors_regions arg arg_rty) ctx args_with_rtypes in @@ -1461,7 +1461,7 @@ and eval_function_call_symbolic_from_inst_sig (meta : Meta.meta) (config : confi abs_ids := with_loans_abs; (* End the abstractions which can be ended *) let no_loans_abs = AbstractionId.Set.of_list no_loans_abs in - let cc = InterpreterBorrows.end_abstractions config no_loans_abs in + let cc = InterpreterBorrows.end_abstractions meta config no_loans_abs in (* Recursive call *) let cc = comp cc end_abs_with_no_loans in (* Continue *) @@ -1529,7 +1529,7 @@ and eval_assumed_function_call_symbolic (meta : Meta.meta) (config : config) (fi let tr_self = UnknownTrait __FUNCTION__ in let sg = Assumed.get_assumed_fun_sig fid in let inst_sg = - instantiate_fun_sig ctx generics tr_self sg regions_hierarchy + instantiate_fun_sig meta ctx generics tr_self sg regions_hierarchy in (sg, regions_hierarchy, inst_sg) in @@ -1542,14 +1542,14 @@ and eval_assumed_function_call_symbolic (meta : Meta.meta) (config : config) (fi and eval_function_body (meta : Meta.meta) (config : config) (body : statement) : st_cm_fun = fun cf ctx -> log#ldebug (lazy "eval_function_body:"); - let cc = eval_statement meta config body in + let cc = eval_statement config body in let cf_finish cf res = log#ldebug (lazy "eval_function_body: cf_finish"); (* Note that we *don't* check the result ({!Panic}, {!Return}, etc.): we * delegate the check to the caller. *) (* Expand the symbolic values if necessary - we need to do that before * checking the invariants *) - let cc = greedy_expand_symbolic_values config in + let cc = greedy_expand_symbolic_values body.meta config in (* Sanity check *) let cc = comp_check_ctx cc (Invariants.check_invariants meta) in (* Continue *) diff --git a/compiler/InterpreterStatements.mli b/compiler/InterpreterStatements.mli index 3832d02f..3b1285a6 100644 --- a/compiler/InterpreterStatements.mli +++ b/compiler/InterpreterStatements.mli @@ -16,7 +16,7 @@ open Cps If the boolean is false, we don't move the return value, and call the continuation with [None]. *) -val pop_frame : config -> bool -> (typed_value option -> m_fun) -> m_fun +val pop_frame : Meta.meta -> config -> bool -> (typed_value option -> m_fun) -> m_fun (** Helper. @@ -48,4 +48,4 @@ val create_push_abstractions_from_abs_region_groups : val eval_statement : config -> statement -> st_cm_fun (** Evaluate a statement seen as a function body *) -val eval_function_body : config -> statement -> st_cm_fun +val eval_function_body : Meta.meta -> config -> statement -> st_cm_fun diff --git a/compiler/InterpreterUtils.ml b/compiler/InterpreterUtils.ml index 243cf67b..48869739 100644 --- a/compiler/InterpreterUtils.ml +++ b/compiler/InterpreterUtils.ml @@ -6,6 +6,7 @@ open LlbcAst open Utils open TypesUtils open Cps +open Errors (* TODO: we should probably rename the file to ContextsUtils *) @@ -16,10 +17,10 @@ let log = Logging.interpreter_log (** Auxiliary function - call a function which requires a continuation, and return the let context given to the continuation *) -let get_cf_ctx_no_synth (f : cm_fun) (ctx : eval_ctx) : eval_ctx = +let get_cf_ctx_no_synth (meta : Meta.meta) (f : cm_fun) (ctx : eval_ctx) : eval_ctx = let nctx = ref None in let cf ctx = - assert (!nctx = None); + cassert (!nctx = None) meta "TODO: error message"; nctx := Some ctx; None in @@ -61,9 +62,9 @@ let statement_to_string ctx = Print.EvalCtx.statement_to_string ctx "" " " let statement_to_string_with_tab ctx = Print.EvalCtx.statement_to_string ctx " " " " -let env_elem_to_string ctx = Print.EvalCtx.env_elem_to_string ctx "" " " -let env_to_string ctx env = eval_ctx_to_string { ctx with env } -let abs_to_string ctx = Print.EvalCtx.abs_to_string ctx "" " " +let env_elem_to_string meta ctx = Print.EvalCtx.env_elem_to_string meta ctx "" " " +let env_to_string meta ctx env = eval_ctx_to_string meta { ctx with env } +let abs_to_string meta ctx = Print.EvalCtx.abs_to_string meta ctx "" " " let same_symbolic_id (sv0 : symbolic_value) (sv1 : symbolic_value) : bool = sv0.sv_id = sv1.sv_id @@ -76,29 +77,29 @@ let mk_place_from_var_id (var_id : VarId.id) : place = { var_id; projection = [] } (** Create a fresh symbolic value *) -let mk_fresh_symbolic_value (ty : ty) : symbolic_value = +let mk_fresh_symbolic_value (meta : Meta.meta) (ty : ty) : symbolic_value = (* Sanity check *) - assert (ty_is_rty ty); + cassert (ty_is_rty ty) meta "TODO: error message"; let sv_id = fresh_symbolic_value_id () in let svalue = { sv_id; sv_ty = ty } in svalue -let mk_fresh_symbolic_value_from_no_regions_ty (ty : ty) : symbolic_value = - assert (ty_no_regions ty); - mk_fresh_symbolic_value ty +let mk_fresh_symbolic_value_from_no_regions_ty (meta : Meta.meta) (ty : ty) : symbolic_value = + cassert (ty_no_regions ty) meta "TODO: error message"; + mk_fresh_symbolic_value meta ty (** Create a fresh symbolic value *) -let mk_fresh_symbolic_typed_value (rty : ty) : typed_value = - assert (ty_is_rty rty); +let mk_fresh_symbolic_typed_value (meta : Meta.meta) (rty : ty) : typed_value = + cassert (ty_is_rty rty) meta "TODO: error message"; let ty = Substitute.erase_regions rty in (* Generate the fresh a symbolic value *) - let value = mk_fresh_symbolic_value rty in + let value = mk_fresh_symbolic_value meta rty in let value = VSymbolic value in { value; ty } -let mk_fresh_symbolic_typed_value_from_no_regions_ty (ty : ty) : typed_value = - assert (ty_no_regions ty); - mk_fresh_symbolic_typed_value ty +let mk_fresh_symbolic_typed_value_from_no_regions_ty (meta : Meta.meta) (ty : ty) : typed_value = + cassert (ty_no_regions ty) meta "TODO: error message"; + mk_fresh_symbolic_typed_value meta ty (** Create a typed value from a symbolic value. *) let mk_typed_value_from_symbolic_value (svalue : symbolic_value) : typed_value = @@ -124,9 +125,9 @@ let mk_aproj_loans_value_from_symbolic_value (regions : RegionId.Set.t) else { value = AIgnored; ty = svalue.sv_ty } (** Create a borrows projector from a symbolic value *) -let mk_aproj_borrows_from_symbolic_value (proj_regions : RegionId.Set.t) +let mk_aproj_borrows_from_symbolic_value (meta : Meta.meta) (proj_regions : RegionId.Set.t) (svalue : symbolic_value) (proj_ty : ty) : aproj = - assert (ty_is_rty proj_ty); + cassert (ty_is_rty proj_ty) meta "TODO: error message"; if ty_has_regions_in_set proj_regions proj_ty then AProjBorrows (svalue, proj_ty) else AIgnoredProjBorrows @@ -140,7 +141,7 @@ let borrow_in_asb (bid : BorrowId.id) (asb : abstract_shared_borrows) : bool = List.exists (borrow_is_asb bid) asb (** TODO: move *) -let remove_borrow_from_asb (bid : BorrowId.id) (asb : abstract_shared_borrows) : +let remove_borrow_from_asb (meta : Meta.meta) (bid : BorrowId.id) (asb : abstract_shared_borrows) : abstract_shared_borrows = let removed = ref 0 in let asb = @@ -152,7 +153,7 @@ let remove_borrow_from_asb (bid : BorrowId.id) (asb : abstract_shared_borrows) : false)) asb in - assert (!removed = 1); + cassert (!removed = 1) meta "TODO: error message"; asb (** We sometimes need to return a value whose type may vary depending on @@ -427,7 +428,7 @@ let empty_ids_set = fst (compute_ctxs_ids []) (** **WARNING**: this function doesn't compute the normalized types (for the trait type aliases). This should be computed afterwards. *) -let initialize_eval_ctx (ctx : decls_ctx) +let initialize_eval_ctx (meta : Meta.meta) (ctx : decls_ctx) (region_groups : RegionGroupId.id list) (type_vars : type_var list) (const_generic_vars : const_generic_var list) : eval_ctx = reset_global_counters (); @@ -436,7 +437,7 @@ let initialize_eval_ctx (ctx : decls_ctx) (List.map (fun (cg : const_generic_var) -> let ty = TLiteral cg.ty in - let cv = mk_fresh_symbolic_typed_value ty in + let cv = mk_fresh_symbolic_typed_value meta ty in (cg.index, cv)) const_generic_vars) in @@ -459,7 +460,7 @@ let initialize_eval_ctx (ctx : decls_ctx) region ids. This is mostly used in preparation of function calls (when evaluating in symbolic mode). *) -let instantiate_fun_sig (ctx : eval_ctx) (generics : generic_args) +let instantiate_fun_sig (meta : Meta.meta) (ctx : eval_ctx) (generics : generic_args) (tr_self : trait_instance_id) (sg : fun_sig) (regions_hierarchy : region_var_groups) : inst_fun_sig = log#ldebug @@ -498,8 +499,8 @@ let instantiate_fun_sig (ctx : eval_ctx) (generics : generic_args) (* Generate the type substitution Note that for now we don't support instantiating the type parameters with types containing regions. *) - assert (List.for_all TypesUtils.ty_no_regions generics.types); - assert (TypesUtils.trait_instance_id_no_regions tr_self); + cassert (List.for_all TypesUtils.ty_no_regions generics.types) meta "TODO: error message"; + cassert (TypesUtils.trait_instance_id_no_regions tr_self) meta "TODO: error message"; let tsubst = Substitute.make_type_subst_from_vars sg.generics.types generics.types in diff --git a/compiler/Invariants.ml b/compiler/Invariants.ml index 871bf90d..a8077ab7 100644 --- a/compiler/Invariants.ml +++ b/compiler/Invariants.ml @@ -55,7 +55,7 @@ let check_loans_borrows_relation_invariant (meta : Meta.meta) (ctx : eval_ctx) : (* Link all the id representants to a borrow information *) let borrows_infos : borrow_info BorrowId.Map.t ref = ref BorrowId.Map.empty in let context_to_string () : string = - eval_ctx_to_string ctx ^ "- representants:\n" + eval_ctx_to_string meta ctx ^ "- representants:\n" ^ ids_reprs_to_string " " !ids_reprs ^ "\n- info:\n" ^ borrows_infos_to_string " " !borrows_infos @@ -77,12 +77,12 @@ let check_loans_borrows_relation_invariant (meta : Meta.meta) (ctx : eval_ctx) : let infos = !borrows_infos in (* Use the first borrow id as representant *) let repr_bid = BorrowId.Set.min_elt bids in - assert (not (BorrowId.Map.mem repr_bid infos)); + cassert (not (BorrowId.Map.mem repr_bid infos)) meta "TODO: Error message"; (* Insert the mappings to the representant *) let reprs = BorrowId.Set.fold (fun bid reprs -> - assert (not (BorrowId.Map.mem bid reprs)); + cassert (not (BorrowId.Map.mem bid reprs)) meta "TODO: Error message"; BorrowId.Map.add bid repr_bid reprs) bids reprs in @@ -105,8 +105,8 @@ let check_loans_borrows_relation_invariant (meta : Meta.meta) (ctx : eval_ctx) : let reprs = !ids_reprs in let infos = !borrows_infos in (* Sanity checks *) - assert (not (BorrowId.Map.mem bid reprs)); - assert (not (BorrowId.Map.mem bid infos)); + cassert (not (BorrowId.Map.mem bid reprs)) meta "TODO: Error message"; + cassert (not (BorrowId.Map.mem bid infos)) meta "TODO: Error message"; (* Add the mapping for the representant *) let reprs = BorrowId.Map.add bid bid reprs in (* Add the mapping for the loan info *) @@ -212,10 +212,10 @@ let check_loans_borrows_relation_invariant (meta : Meta.meta) (ctx : eval_ctx) : | RShared, (BShared | BReserved) | RMut, BMut -> () | _ -> craise meta "Invariant not satisfied"); (* A reserved borrow can't point to a value inside an abstraction *) - assert (kind <> BReserved || not info.loan_in_abs); + cassert (kind <> BReserved || not info.loan_in_abs) meta "A reserved borrow can't point to a value inside an abstraction"; (* Insert the borrow id *) let borrow_ids = info.borrow_ids in - assert (not (BorrowId.Set.mem bid borrow_ids)); + cassert (not (BorrowId.Set.mem bid borrow_ids)) meta "TODO: Error message"; let info = { info with borrow_ids = BorrowId.Set.add bid borrow_ids } in (* Update the info in the map *) update_info bid info @@ -270,7 +270,7 @@ let check_loans_borrows_relation_invariant (meta : Meta.meta) (ctx : eval_ctx) : List.iter (fun (rkind, bid) -> let info = find_info bid in - assert (info.loan_kind = rkind)) + cassert (info.loan_kind = rkind) meta "Not all the ignored loans are present at the proper place") !ignored_loans; (* Then, check the borrow infos *) @@ -278,11 +278,11 @@ let check_loans_borrows_relation_invariant (meta : Meta.meta) (ctx : eval_ctx) : (fun _ info -> (* Note that we can't directly compare the sets - I guess they are * different depending on the order in which we add the elements... *) - assert ( + cassert ( BorrowId.Set.elements info.loan_ids - = BorrowId.Set.elements info.borrow_ids); + = BorrowId.Set.elements info.borrow_ids) meta "TODO: Error message"; match info.loan_kind with - | RMut -> assert (BorrowId.Set.cardinal info.loan_ids = 1) + | RMut -> cassert (BorrowId.Set.cardinal info.loan_ids = 1) meta "TODO: Error message" | RShared -> ()) !borrows_infos @@ -290,14 +290,14 @@ let check_loans_borrows_relation_invariant (meta : Meta.meta) (ctx : eval_ctx) : - borrows/loans can't contain ⊥ or reserved mut borrows - shared loans can't contain mutable loans *) -let check_borrowed_values_invariant (ctx : eval_ctx) : unit = +let check_borrowed_values_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = let visitor = object inherit [_] iter_eval_ctx as super method! visit_VBottom info = (* No ⊥ inside borrowed values *) - assert (Config.allow_bottom_below_borrow || not info.outer_borrow) + cassert (Config.allow_bottom_below_borrow || not info.outer_borrow) meta "There should be no ⊥ inside borrowed values" method! visit_ABottom _info = (* ⊥ inside an abstraction is not the same as in a regular value *) @@ -310,7 +310,7 @@ let check_borrowed_values_invariant (ctx : eval_ctx) : unit = | VSharedLoan (_, _) -> set_outer_shared info | VMutLoan _ -> (* No mutable loan inside a shared loan *) - assert (not info.outer_shared); + cassert (not info.outer_shared) meta "There should be no mutable loan inside a shared loan"; set_outer_mut info in (* Continue exploring *) @@ -322,7 +322,7 @@ let check_borrowed_values_invariant (ctx : eval_ctx) : unit = match bc with | VSharedBorrow _ -> set_outer_shared info | VReservedMutBorrow _ -> - assert (not info.outer_borrow); + cassert (not info.outer_borrow) meta "TODO: Error message"; set_outer_shared info | VMutBorrow (_, _) -> set_outer_mut info in @@ -369,7 +369,7 @@ let check_borrowed_values_invariant (ctx : eval_ctx) : unit = let check_literal_type (meta : Meta.meta) (cv : literal) (ty : literal_type) : unit = match (cv, ty) with - | VScalar sv, TInteger int_ty -> assert (sv.int_ty = int_ty) + | VScalar sv, TInteger int_ty -> cassert (sv.int_ty = int_ty) meta "TODO: Error message" | VBool _, TBool | VChar _, TChar -> () | _ -> craise meta "Erroneous typing" @@ -393,17 +393,17 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = method! visit_EBinding info binder v = (* We also check that the regions are erased *) - assert (ty_is_ety v.ty); + cassert (ty_is_ety v.ty) meta "The regions should be erased"; super#visit_EBinding info binder v method! visit_symbolic_value inside_abs v = (* Check that the types have regions *) - assert (ty_is_rty v.sv_ty); + cassert (ty_is_rty v.sv_ty) meta "The types should have regions"; super#visit_symbolic_value inside_abs v method! visit_typed_value info tv = (* Check that the types have erased regions *) - assert (ty_is_ety tv.ty); + cassert (ty_is_ety tv.ty) meta "The types should have erased regions"; (* Check the current pair (value, type) *) (match (tv.value, tv.ty) with | VLiteral cv, TLiteral ty -> check_literal_type meta cv ty @@ -413,13 +413,13 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = * parameters, etc. *) let def = ctx_lookup_type_decl ctx def_id in (* Check the number of parameters *) - assert ( - List.length generics.regions = List.length def.generics.regions); - assert (List.length generics.types = List.length def.generics.types); + cassert ( + List.length generics.regions = List.length def.generics.regions) meta "TODO: Error message"; + cassert (List.length generics.types = List.length def.generics.types) meta "TODO: Error message"; (* Check that the variant id is consistent *) (match (av.variant_id, def.kind) with | Some variant_id, Enum variants -> - assert (VariantId.to_int variant_id < List.length variants) + cassert (VariantId.to_int variant_id < List.length variants) meta "The variant id should be consistent" | None, Struct _ -> () | _ -> craise meta "Erroneous typing"); (* Check that the field types are correct *) @@ -429,24 +429,24 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = in let fields_with_types = List.combine av.field_values field_types in List.iter - (fun ((v, ty) : typed_value * ty) -> assert (v.ty = ty)) + (fun ((v, ty) : typed_value * ty) -> cassert (v.ty = ty) meta "The field types are not correct") fields_with_types (* Tuple case *) | VAdt av, TAdt (TTuple, generics) -> - assert (generics.regions = []); - assert (generics.const_generics = []); - assert (av.variant_id = None); + cassert (generics.regions = []) meta "TODO: Error message"; + cassert (generics.const_generics = []) meta "TODO: Error message"; + cassert (av.variant_id = None) meta "TODO: Error message"; (* Check that the fields have the proper values - and check that there * are as many fields as field types at the same time *) let fields_with_types = List.combine av.field_values generics.types in List.iter - (fun ((v, ty) : typed_value * ty) -> assert (v.ty = ty)) + (fun ((v, ty) : typed_value * ty) -> cassert (v.ty = ty) meta "The fields does not have the proper values or there are not as many fields as field types at the same time TODO: error message") fields_with_types (* Assumed type case *) | VAdt av, TAdt (TAssumed aty_id, generics) -> ( - assert (av.variant_id = None); + cassert (av.variant_id = None) meta "TODO: Error message"; match ( aty_id, av.field_values, @@ -456,20 +456,20 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = with (* Box *) | TBox, [ inner_value ], [], [ inner_ty ], [] -> - assert (inner_value.ty = inner_ty) + cassert (inner_value.ty = inner_ty) meta "TODO: Error message" | TArray, inner_values, _, [ inner_ty ], [ cg ] -> (* *) - assert ( + cassert ( List.for_all (fun (v : typed_value) -> v.ty = inner_ty) - inner_values); + inner_values) meta "TODO: Error message"; (* The length is necessarily concrete *) let len = (ValuesUtils.literal_as_scalar (TypesUtils.const_generic_as_literal cg)) .value in - assert (Z.of_int (List.length inner_values) = len) + cassert (Z.of_int (List.length inner_values) = len) meta "TODO: Error message" | (TSlice | TStr), _, _, _, _ -> craise meta "Unexpected" | _ -> craise meta "Erroneous type") | VBottom, _ -> (* Nothing to check *) () @@ -481,27 +481,27 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = match glc with | Concrete (VSharedLoan (_, sv)) | Abstract (ASharedLoan (_, sv, _)) -> - assert (sv.ty = ref_ty) + cassert (sv.ty = ref_ty) meta "TODO: Error message" | _ -> craise meta "Inconsistent context") | VMutBorrow (_, bv), RMut -> - assert ( + cassert ( (* Check that the borrowed value has the proper type *) - bv.ty = ref_ty) + bv.ty = ref_ty) meta "TODO: Error message" | _ -> craise meta "Erroneous typing") | VLoan lc, ty -> ( match lc with - | VSharedLoan (_, sv) -> assert (sv.ty = ty) + | VSharedLoan (_, sv) -> cassert (sv.ty = ty) meta "TODO: Error message" | VMutLoan bid -> ( (* Lookup the borrowed value to check it has the proper type *) let glc = lookup_borrow meta ek_all bid ctx in match glc with - | Concrete (VMutBorrow (_, bv)) -> assert (bv.ty = ty) + | Concrete (VMutBorrow (_, bv)) -> cassert (bv.ty = ty) meta "The borrowed value does not have the proper type" | Abstract (AMutBorrow (_, sv)) -> - assert (Substitute.erase_regions sv.ty = ty) + cassert (Substitute.erase_regions sv.ty = ty) meta "The borrowed value does not have the proper type" | _ -> craise meta "Inconsistent context")) | VSymbolic sv, ty -> let ty' = Substitute.erase_regions sv.sv_ty in - assert (ty' = ty) + cassert (ty' = ty) meta "TODO: Error message" | _ -> craise meta "Erroneous typing"); (* Continue exploring to inspect the subterms *) super#visit_typed_value info tv @@ -516,7 +516,7 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = * *) method! visit_typed_avalue info atv = (* Check that the types have regions *) - assert (ty_is_rty atv.ty); + cassert (ty_is_rty atv.ty) meta "The types should have regions"; (* Check the current pair (value, type) *) (match (atv.value, atv.ty) with (* ADT case *) @@ -525,16 +525,16 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = * parameters, etc. *) let def = ctx_lookup_type_decl ctx def_id in (* Check the number of parameters *) - assert ( - List.length generics.regions = List.length def.generics.regions); - assert (List.length generics.types = List.length def.generics.types); - assert ( + cassert ( + List.length generics.regions = List.length def.generics.regions) meta "TODO: Error message"; + cassert (List.length generics.types = List.length def.generics.types) meta "TODO: Error message"; + cassert ( List.length generics.const_generics - = List.length def.generics.const_generics); + = List.length def.generics.const_generics) meta "TODO: Error message"; (* Check that the variant id is consistent *) (match (av.variant_id, def.kind) with | Some variant_id, Enum variants -> - assert (VariantId.to_int variant_id < List.length variants) + cassert (VariantId.to_int variant_id < List.length variants) meta "The variant id should be consistent" | None, Struct _ -> () | _ -> craise meta "Erroneous typing"); (* Check that the field types are correct *) @@ -544,24 +544,24 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = in let fields_with_types = List.combine av.field_values field_types in List.iter - (fun ((v, ty) : typed_avalue * ty) -> assert (v.ty = ty)) + (fun ((v, ty) : typed_avalue * ty) -> cassert (v.ty = ty) meta "TODO: Error message") fields_with_types (* Tuple case *) | AAdt av, TAdt (TTuple, generics) -> - assert (generics.regions = []); - assert (generics.const_generics = []); - assert (av.variant_id = None); + cassert (generics.regions = []) meta "TODO: Error message"; + cassert (generics.const_generics = []) meta "TODO: Error message"; + cassert (av.variant_id = None) meta "TODO: Error message"; (* Check that the fields have the proper values - and check that there * are as many fields as field types at the same time *) let fields_with_types = List.combine av.field_values generics.types in List.iter - (fun ((v, ty) : typed_avalue * ty) -> assert (v.ty = ty)) + (fun ((v, ty) : typed_avalue * ty) -> cassert (v.ty = ty) meta "The fields do not have the proper values or there are not as many fields as field types at the same time TODO: Error message") fields_with_types (* Assumed type case *) | AAdt av, TAdt (TAssumed aty_id, generics) -> ( - assert (av.variant_id = None); + cassert (av.variant_id = None) meta "TODO: Error message"; match ( aty_id, av.field_values, @@ -571,27 +571,27 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = with (* Box *) | TBox, [ boxed_value ], [], [ boxed_ty ], [] -> - assert (boxed_value.ty = boxed_ty) + cassert (boxed_value.ty = boxed_ty) meta "TODO: Error message" | _ -> craise meta "Erroneous type") | ABottom, _ -> (* Nothing to check *) () | ABorrow bc, TRef (_, ref_ty, rkind) -> ( match (bc, rkind) with | AMutBorrow (_, av), RMut -> (* Check that the child value has the proper type *) - assert (av.ty = ref_ty) + cassert (av.ty = ref_ty) meta "TODO: Error message" | ASharedBorrow bid, RShared -> ( (* Lookup the borrowed value to check it has the proper type *) let _, glc = lookup_loan meta ek_all bid ctx in match glc with | Concrete (VSharedLoan (_, sv)) | Abstract (ASharedLoan (_, sv, _)) -> - assert (sv.ty = Substitute.erase_regions ref_ty) + cassert (sv.ty = Substitute.erase_regions ref_ty) meta "TODO: Error message" | _ -> craise meta "Inconsistent context") - | AIgnoredMutBorrow (_opt_bid, av), RMut -> assert (av.ty = ref_ty) + | AIgnoredMutBorrow (_opt_bid, av), RMut -> cassert (av.ty = ref_ty) meta "TODO: Error message" | ( AEndedIgnoredMutBorrow { given_back; child; given_back_meta = _ }, RMut ) -> - assert (given_back.ty = ref_ty); - assert (child.ty = ref_ty) + cassert (given_back.ty = ref_ty) meta "TODO: Error message"; + cassert (child.ty = ref_ty) meta "TODO: Error message" | AProjSharedBorrow _, RShared -> () | _ -> craise meta "Inconsistent context") | ALoan lc, aty -> ( @@ -599,54 +599,54 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = | AMutLoan (bid, child_av) | AIgnoredMutLoan (Some bid, child_av) -> ( let borrowed_aty = aloan_get_expected_child_type aty in - assert (child_av.ty = borrowed_aty); + cassert (child_av.ty = borrowed_aty) meta "TODO: Error message"; (* Lookup the borrowed value to check it has the proper type *) let glc = lookup_borrow meta ek_all bid ctx in match glc with | Concrete (VMutBorrow (_, bv)) -> - assert (bv.ty = Substitute.erase_regions borrowed_aty) + cassert (bv.ty = Substitute.erase_regions borrowed_aty) meta "TODO: Error message" | Abstract (AMutBorrow (_, sv)) -> - assert ( + cassert ( Substitute.erase_regions sv.ty - = Substitute.erase_regions borrowed_aty) + = Substitute.erase_regions borrowed_aty) meta "TODO: Error message" | _ -> craise meta "Inconsistent context") | AIgnoredMutLoan (None, child_av) -> let borrowed_aty = aloan_get_expected_child_type aty in - assert (child_av.ty = borrowed_aty) + cassert (child_av.ty = borrowed_aty) meta "TODO: Error message" | ASharedLoan (_, sv, child_av) | AEndedSharedLoan (sv, child_av) -> let borrowed_aty = aloan_get_expected_child_type aty in - assert (sv.ty = Substitute.erase_regions borrowed_aty); + cassert (sv.ty = Substitute.erase_regions borrowed_aty) meta "TODO: Error message"; (* TODO: the type of aloans doesn't make sense, see above *) - assert (child_av.ty = borrowed_aty) + cassert (child_av.ty = borrowed_aty) meta "TODO: Error message" | AEndedMutLoan { given_back; child; given_back_meta = _ } | AEndedIgnoredMutLoan { given_back; child; given_back_meta = _ } -> let borrowed_aty = aloan_get_expected_child_type aty in - assert (given_back.ty = borrowed_aty); - assert (child.ty = borrowed_aty) + cassert (given_back.ty = borrowed_aty) meta "TODO: Error message"; + cassert (child.ty = borrowed_aty) meta "TODO: Error message" | AIgnoredSharedLoan child_av -> - assert (child_av.ty = aloan_get_expected_child_type aty)) + cassert (child_av.ty = aloan_get_expected_child_type aty) meta "TODO: Error message") | ASymbolic aproj, ty -> ( let ty1 = Substitute.erase_regions ty in match aproj with | AProjLoans (sv, _) -> let ty2 = Substitute.erase_regions sv.sv_ty in - assert (ty1 = ty2); + cassert (ty1 = ty2) meta "TODO: Error message"; (* Also check that the symbolic values contain regions of interest - * otherwise they should have been reduced to [_] *) let abs = Option.get info in - assert (ty_has_regions_in_set abs.regions sv.sv_ty) + cassert (ty_has_regions_in_set abs.regions sv.sv_ty) meta "The symbolic values should contain regions of interest or they should have been reduced to [] TODO: error message" | AProjBorrows (sv, proj_ty) -> let ty2 = Substitute.erase_regions sv.sv_ty in - assert (ty1 = ty2); + cassert (ty1 = ty2) meta "TODO: Error message"; (* Also check that the symbolic values contain regions of interest - * otherwise they should have been reduced to [_] *) let abs = Option.get info in - assert (ty_has_regions_in_set abs.regions proj_ty) + cassert (ty_has_regions_in_set abs.regions proj_ty) meta "The symbolic values should contain regions of interest or they should have been reduced to [] TODO: error message" | AEndedProjLoans (_msv, given_back_ls) -> List.iter (fun (_, proj) -> match proj with - | AProjBorrows (_sv, ty') -> assert (ty' = ty) + | AProjBorrows (_sv, ty') -> cassert (ty' = ty) meta "TODO: Error message" | AEndedProjBorrows _ | AIgnoredProjBorrows -> () | _ -> craise meta "Unexpected") given_back_ls @@ -657,7 +657,7 @@ let check_typing_invariant (meta : Meta.meta) (ctx : eval_ctx) : unit = (lazy ("Erroneous typing:" ^ "\n- raw value: " ^ show_typed_avalue atv ^ "\n- value: " - ^ typed_avalue_to_string ctx atv + ^ typed_avalue_to_string meta ctx atv ^ "\n- type: " ^ ty_to_string ctx atv.ty)); craise meta "Erroneous typing"); (* Continue exploring to inspect the subterms *) @@ -766,15 +766,15 @@ let check_symbolic_values (meta : Meta.meta) (ctx : eval_ctx) : unit = *) (* A symbolic value can't be both in the regular environment and inside * projectors of borrows in abstractions *) - assert (info.env_count = 0 || info.aproj_borrows = []); + cassert (info.env_count = 0 || info.aproj_borrows = []) meta "A symbolic value can't be both in the regular environment and inside projectors of borrows in abstractions"; (* A symbolic value containing borrows can't be duplicated (i.e., copied): * it must be expanded first *) if ty_has_borrows ctx.type_ctx.type_infos info.ty then - assert (info.env_count <= 1); + cassert (info.env_count <= 1) meta "A symbolic value containing borrows can't be duplicated (i.e., copied): it must be expanded first"; (* A duplicated symbolic value is necessarily primitively copyable *) - assert (info.env_count <= 1 || ty_is_primitively_copyable info.ty); + cassert (info.env_count <= 1 || ty_is_primitively_copyable info.ty) meta "A duplicated symbolic value should necessarily be primitively copyable"; - assert (info.aproj_borrows = [] || info.aproj_loans <> []); + cassert (info.aproj_borrows = [] || info.aproj_loans <> []) meta "TODO: Error message"; (* At the same time: * - check that the loans don't intersect * - compute the set of regions for which we project loans @@ -786,7 +786,7 @@ let check_symbolic_values (meta : Meta.meta) (ctx : eval_ctx) : unit = let regions = RegionId.Set.fold (fun rid regions -> - assert (not (RegionId.Set.mem rid regions)); + cassert (not (RegionId.Set.mem rid regions)) meta "The loan projectors should contain the region projectors"; RegionId.Set.add rid regions) regions linfo.regions in @@ -796,8 +796,8 @@ let check_symbolic_values (meta : Meta.meta) (ctx : eval_ctx) : unit = (* Check that the union of the loan projectors contains the borrow projections. *) List.iter (fun binfo -> - assert ( - projection_contains meta info.ty loan_regions binfo.proj_ty binfo.regions)) + cassert ( + projection_contains meta info.ty loan_regions binfo.proj_ty binfo.regions) meta "The union of the loan projectors should contain the borrow projections") info.aproj_borrows; () in @@ -806,9 +806,9 @@ let check_symbolic_values (meta : Meta.meta) (ctx : eval_ctx) : unit = let check_invariants (meta : Meta.meta) (ctx : eval_ctx) : unit = if !Config.sanity_checks then ( - log#ldebug (lazy ("Checking invariants:\n" ^ eval_ctx_to_string ctx)); + log#ldebug (lazy ("Checking invariants:\n" ^ eval_ctx_to_string meta ctx)); check_loans_borrows_relation_invariant meta ctx; - check_borrowed_values_invariant ctx; + check_borrowed_values_invariant meta ctx; check_typing_invariant meta ctx; check_symbolic_values meta ctx) else log#ldebug (lazy "Not checking invariants (check is not activated)") diff --git a/compiler/Main.ml b/compiler/Main.ml index bea7e4a8..f860bec8 100644 --- a/compiler/Main.ml +++ b/compiler/Main.ml @@ -271,10 +271,10 @@ let () = (* Some options for the execution *) (* Test the unit functions with the concrete interpreter *) - if !test_unit_functions then Test.test_unit_functions meta m; + if !test_unit_functions then Test.test_unit_functions m; (* Translate the functions *) - Aeneas.Translate.translate_crate meta filename dest_dir m; + Aeneas.Translate.translate_crate filename dest_dir m; (* Print total elapsed time *) log#linfo diff --git a/compiler/PrePasses.ml b/compiler/PrePasses.ml index c6b098e6..3ea9c777 100644 --- a/compiler/PrePasses.ml +++ b/compiler/PrePasses.ml @@ -7,6 +7,7 @@ open Expressions open LlbcAst open Utils open LlbcAstUtils +open Errors let log = Logging.pre_passes_log @@ -214,11 +215,11 @@ let remove_loop_breaks (crate : crate) (f : fun_decl) : fun_decl = inherit [_] map_statement as super method! visit_Loop entered_loop loop = - assert (not entered_loop); + cassert (not entered_loop) st.meta "TODO: error message"; super#visit_Loop true loop method! visit_Break _ i = - assert (i = 0); + cassert (i = 0) st.meta "TODO: error message"; nst.content end in @@ -233,7 +234,7 @@ let remove_loop_breaks (crate : crate) (f : fun_decl) : fun_decl = method! visit_Sequence env st1 st2 = match st1.content with | Loop _ -> - assert (statement_has_no_loop_break_continue st2); + cassert (statement_has_no_loop_break_continue st2) st2.meta "TODO: error message"; (replace_breaks_with st1 st2).content | _ -> super#visit_Sequence env st1 st2 end @@ -392,13 +393,16 @@ let remove_shallow_borrows (crate : crate) (f : fun_decl) : fun_decl = let body = filter_visitor#visit_statement () body in (* Check that the filtered variables completely disappeared from the body *) + (* let statement = crate in *) let check_visitor = object - inherit [_] iter_statement - method! visit_var_id _ id = assert (not (VarId.Set.mem id !filtered)) + inherit [_] iter_statement as super + (* Remember the span of the statement we enter *) + method! visit_statement _ st = super#visit_statement st.meta st + method! visit_var_id meta id = cassert (not (VarId.Set.mem id !filtered)) meta "Filtered variables should have completely disappeared from the body" end in - check_visitor#visit_statement () body; + check_visitor#visit_statement body.meta body; (* Return the updated body *) body diff --git a/compiler/Print.ml b/compiler/Print.ml index 36aa2cb9..85e7eaf6 100644 --- a/compiler/Print.ml +++ b/compiler/Print.ml @@ -10,6 +10,7 @@ open ValuesUtils open Expressions open LlbcAst open Contexts +open Errors module Types = Charon.PrintTypes module Expressions = Charon.PrintExpressions @@ -42,12 +43,12 @@ module Values = struct * typed_avalue_to_string. At some point we had done it, because [typed_value] * and [typed_avalue] were instances of the same general type [g_typed_value], * but then we removed this general type because it proved to be a bad idea. *) - let rec typed_value_to_string (env : fmt_env) (v : typed_value) : string = + let rec typed_value_to_string (meta : Meta.meta) (env : fmt_env) (v : typed_value) : string = match v.value with | VLiteral cv -> literal_to_string cv | VAdt av -> ( let field_values = - List.map (typed_value_to_string env) av.field_values + List.map (typed_value_to_string meta env) av.field_values in match v.ty with | TAdt (TTuple, _) -> @@ -82,28 +83,28 @@ module Values = struct | TArray, _ -> (* Happens when we aggregate values *) "@Array[" ^ String.concat ", " field_values ^ "]" - | _ -> raise (Failure ("Inconsistent value: " ^ show_typed_value v)) + | _ -> craise meta ("Inconsistent value: " ^ show_typed_value v) ) - | _ -> raise (Failure "Inconsistent typed value")) + | _ -> craise meta "Inconsistent typed value") | VBottom -> "⊥ : " ^ ty_to_string env v.ty - | VBorrow bc -> borrow_content_to_string env bc - | VLoan lc -> loan_content_to_string env lc + | VBorrow bc -> borrow_content_to_string meta env bc + | VLoan lc -> loan_content_to_string meta env lc | VSymbolic s -> symbolic_value_to_string env s - and borrow_content_to_string (env : fmt_env) (bc : borrow_content) : string = + and borrow_content_to_string (meta : Meta.meta) (env : fmt_env) (bc : borrow_content) : string = match bc with | VSharedBorrow bid -> "shared_borrow@" ^ BorrowId.to_string bid | VMutBorrow (bid, tv) -> "mut_borrow@" ^ BorrowId.to_string bid ^ " (" - ^ typed_value_to_string env tv + ^ typed_value_to_string meta env tv ^ ")" | VReservedMutBorrow bid -> "reserved_borrow@" ^ BorrowId.to_string bid - and loan_content_to_string (env : fmt_env) (lc : loan_content) : string = + and loan_content_to_string (meta : Meta.meta) (env : fmt_env) (lc : loan_content) : string = match lc with | VSharedLoan (loans, v) -> let loans = BorrowId.Set.to_string None loans in - "@shared_loan(" ^ loans ^ ", " ^ typed_value_to_string env v ^ ")" + "@shared_loan(" ^ loans ^ ", " ^ typed_value_to_string meta env v ^ ")" | VMutLoan bid -> "ml@" ^ BorrowId.to_string bid let abstract_shared_borrow_to_string (env : fmt_env) @@ -141,11 +142,11 @@ module Values = struct | AEndedProjBorrows _mv -> "_" | AIgnoredProjBorrows -> "_" - let rec typed_avalue_to_string (env : fmt_env) (v : typed_avalue) : string = + let rec typed_avalue_to_string (meta : Meta.meta) (env : fmt_env) (v : typed_avalue) : string = match v.value with | AAdt av -> ( let field_values = - List.map (typed_avalue_to_string env) av.field_values + List.map (typed_avalue_to_string meta env) av.field_values in match v.ty with | TAdt (TTuple, _) -> @@ -177,75 +178,75 @@ module Values = struct (* Assumed type *) match (aty, field_values) with | TBox, [ bv ] -> "@Box(" ^ bv ^ ")" - | _ -> raise (Failure "Inconsistent value")) - | _ -> raise (Failure "Inconsistent typed value")) + | _ -> craise meta "Inconsistent value") + | _ -> craise meta "Inconsistent typed value") | ABottom -> "⊥ : " ^ ty_to_string env v.ty - | ABorrow bc -> aborrow_content_to_string env bc - | ALoan lc -> aloan_content_to_string env lc + | ABorrow bc -> aborrow_content_to_string meta env bc + | ALoan lc -> aloan_content_to_string meta env lc | ASymbolic s -> aproj_to_string env s | AIgnored -> "_" - and aloan_content_to_string (env : fmt_env) (lc : aloan_content) : string = + and aloan_content_to_string (meta : Meta.meta) (env : fmt_env) (lc : aloan_content) : string = match lc with | AMutLoan (bid, av) -> "@mut_loan(" ^ BorrowId.to_string bid ^ ", " - ^ typed_avalue_to_string env av + ^ typed_avalue_to_string meta env av ^ ")" | ASharedLoan (loans, v, av) -> let loans = BorrowId.Set.to_string None loans in "@shared_loan(" ^ loans ^ ", " - ^ typed_value_to_string env v + ^ typed_value_to_string meta env v ^ ", " - ^ typed_avalue_to_string env av + ^ typed_avalue_to_string meta env av ^ ")" | AEndedMutLoan ml -> "@ended_mut_loan{" - ^ typed_avalue_to_string env ml.child + ^ typed_avalue_to_string meta env ml.child ^ "; " - ^ typed_avalue_to_string env ml.given_back + ^ typed_avalue_to_string meta env ml.given_back ^ " }" | AEndedSharedLoan (v, av) -> "@ended_shared_loan(" - ^ typed_value_to_string env v + ^ typed_value_to_string meta env v ^ ", " - ^ typed_avalue_to_string env av + ^ typed_avalue_to_string meta env av ^ ")" | AIgnoredMutLoan (opt_bid, av) -> "@ignored_mut_loan(" ^ option_to_string BorrowId.to_string opt_bid ^ ", " - ^ typed_avalue_to_string env av + ^ typed_avalue_to_string meta env av ^ ")" | AEndedIgnoredMutLoan ml -> "@ended_ignored_mut_loan{ " - ^ typed_avalue_to_string env ml.child + ^ typed_avalue_to_string meta env ml.child ^ "; " - ^ typed_avalue_to_string env ml.given_back + ^ typed_avalue_to_string meta env ml.given_back ^ "}" | AIgnoredSharedLoan sl -> - "@ignored_shared_loan(" ^ typed_avalue_to_string env sl ^ ")" + "@ignored_shared_loan(" ^ typed_avalue_to_string meta env sl ^ ")" - and aborrow_content_to_string (env : fmt_env) (bc : aborrow_content) : string + and aborrow_content_to_string (meta : Meta.meta) (env : fmt_env) (bc : aborrow_content) : string = match bc with | AMutBorrow (bid, av) -> "mb@" ^ BorrowId.to_string bid ^ " (" - ^ typed_avalue_to_string env av + ^ typed_avalue_to_string meta env av ^ ")" | ASharedBorrow bid -> "sb@" ^ BorrowId.to_string bid | AIgnoredMutBorrow (opt_bid, av) -> "@ignored_mut_borrow(" ^ option_to_string BorrowId.to_string opt_bid ^ ", " - ^ typed_avalue_to_string env av + ^ typed_avalue_to_string meta env av ^ ")" | AEndedMutBorrow (_mv, child) -> - "@ended_mut_borrow(" ^ typed_avalue_to_string env child ^ ")" + "@ended_mut_borrow(" ^ typed_avalue_to_string meta env child ^ ")" | AEndedIgnoredMutBorrow { child; given_back; given_back_meta = _ } -> "@ended_ignored_mut_borrow{ " - ^ typed_avalue_to_string env child + ^ typed_avalue_to_string meta env child ^ "; " - ^ typed_avalue_to_string env given_back + ^ typed_avalue_to_string meta env given_back ^ ")" | AEndedSharedBorrow -> "@ended_shared_borrow" | AProjSharedBorrow sb -> @@ -275,11 +276,11 @@ module Values = struct ^ ")" | Identity -> "Identity" - let abs_to_string (env : fmt_env) (verbose : bool) (indent : string) + let abs_to_string (meta : Meta.meta) (env : fmt_env) (verbose : bool) (indent : string) (indent_incr : string) (abs : abs) : string = let indent2 = indent ^ indent_incr in let avs = - List.map (fun av -> indent2 ^ typed_avalue_to_string env av) abs.avalues + List.map (fun av -> indent2 ^ typed_avalue_to_string meta env av) abs.avalues in let avs = String.concat ",\n" avs in let kind = @@ -322,7 +323,7 @@ module Contexts = struct | BVar b -> var_binder_to_string env b | BDummy bid -> dummy_var_id_to_string bid - let env_elem_to_string (env : fmt_env) (verbose : bool) + let env_elem_to_string (meta : Meta.meta) (env : fmt_env) (verbose : bool) (with_var_types : bool) (indent : string) (indent_incr : string) (ev : env_elem) : string = match ev with @@ -331,17 +332,17 @@ module Contexts = struct let ty = if with_var_types then " : " ^ ty_to_string env tv.ty else "" in - indent ^ bv ^ ty ^ " -> " ^ typed_value_to_string env tv ^ " ;" - | EAbs abs -> abs_to_string env verbose indent indent_incr abs - | EFrame -> raise (Failure "Can't print a Frame element") + indent ^ bv ^ ty ^ " -> " ^ typed_value_to_string meta env tv ^ " ;" + | EAbs abs -> abs_to_string meta env verbose indent indent_incr abs + | EFrame -> craise meta "Can't print a Frame element" - let opt_env_elem_to_string (env : fmt_env) (verbose : bool) + let opt_env_elem_to_string (meta : Meta.meta) (env : fmt_env) (verbose : bool) (with_var_types : bool) (indent : string) (indent_incr : string) (ev : env_elem option) : string = match ev with | None -> indent ^ "..." | Some ev -> - env_elem_to_string env verbose with_var_types indent indent_incr ev + env_elem_to_string meta env verbose with_var_types indent indent_incr ev (** Filters "dummy" bindings from an environment, to gain space and clarity/ See [env_to_string]. *) @@ -378,7 +379,7 @@ module Contexts = struct "..." to gain space and clarity. [with_var_types]: if true, print the type of the variables *) - let env_to_string (filter : bool) (fmt_env : fmt_env) (verbose : bool) + let env_to_string (meta : Meta.meta) (filter : bool) (fmt_env : fmt_env) (verbose : bool) (with_var_types : bool) (env : env) : string = let env = if filter then filter_env env else List.map (fun ev -> Some ev) env @@ -387,7 +388,7 @@ module Contexts = struct ^ String.concat "\n" (List.map (fun ev -> - opt_env_elem_to_string fmt_env verbose with_var_types " " " " ev) + opt_env_elem_to_string meta fmt_env verbose with_var_types " " " " ev) env) ^ "\n}" @@ -467,7 +468,7 @@ module Contexts = struct let frames = split_aux [] [] env in frames - let eval_ctx_to_string_gen (verbose : bool) (filter : bool) + let eval_ctx_to_string_gen (meta : Meta.meta) (verbose : bool) (filter : bool) (with_var_types : bool) (ctx : eval_ctx) : string = let fmt_env = eval_ctx_to_fmt_env ctx in let ended_regions = RegionId.Set.to_string None ctx.ended_regions in @@ -485,24 +486,24 @@ module Contexts = struct | EBinding (BDummy _, _) -> num_dummies := !num_abs + 1 | EBinding (BVar _, _) -> num_bindings := !num_bindings + 1 | EAbs _ -> num_abs := !num_abs + 1 - | _ -> raise (Failure "Unreachable")) + | _ -> craise meta "Unreachable") f; "\n# Frame " ^ string_of_int i ^ ":" ^ "\n- locals: " ^ string_of_int !num_bindings ^ "\n- dummy bindings: " ^ string_of_int !num_dummies ^ "\n- abstractions: " ^ string_of_int !num_abs ^ "\n" - ^ env_to_string filter fmt_env verbose with_var_types f + ^ env_to_string meta filter fmt_env verbose with_var_types f ^ "\n") frames in "# Ended regions: " ^ ended_regions ^ "\n" ^ "# " ^ string_of_int num_frames ^ " frame(s)\n" ^ String.concat "" frames - let eval_ctx_to_string (ctx : eval_ctx) : string = - eval_ctx_to_string_gen false true true ctx + let eval_ctx_to_string (meta : Meta.meta) (ctx : eval_ctx) : string = + eval_ctx_to_string_gen meta false true true ctx - let eval_ctx_to_string_no_filter (ctx : eval_ctx) : string = - eval_ctx_to_string_gen false false true ctx + let eval_ctx_to_string_no_filter (meta : Meta.meta) (ctx : eval_ctx) : string = + eval_ctx_to_string_gen meta false false true ctx end (** Pretty-printing for LLBC ASTs (functions based on an evaluation context) *) @@ -540,22 +541,22 @@ module EvalCtx = struct let env = eval_ctx_to_fmt_env ctx in trait_instance_id_to_string env x - let borrow_content_to_string (ctx : eval_ctx) (bc : borrow_content) : string = + let borrow_content_to_string (meta : Meta.meta) (ctx : eval_ctx) (bc : borrow_content) : string = let env = eval_ctx_to_fmt_env ctx in - borrow_content_to_string env bc + borrow_content_to_string meta env bc - let loan_content_to_string (ctx : eval_ctx) (lc : loan_content) : string = + let loan_content_to_string (meta : Meta.meta) (ctx : eval_ctx) (lc : loan_content) : string = let env = eval_ctx_to_fmt_env ctx in - loan_content_to_string env lc + loan_content_to_string meta env lc - let aborrow_content_to_string (ctx : eval_ctx) (bc : aborrow_content) : string + let aborrow_content_to_string (meta : Meta.meta) (ctx : eval_ctx) (bc : aborrow_content) : string = let env = eval_ctx_to_fmt_env ctx in - aborrow_content_to_string env bc + aborrow_content_to_string meta env bc - let aloan_content_to_string (ctx : eval_ctx) (lc : aloan_content) : string = + let aloan_content_to_string (meta : Meta.meta) (ctx : eval_ctx) (lc : aloan_content) : string = let env = eval_ctx_to_fmt_env ctx in - aloan_content_to_string env lc + aloan_content_to_string meta env lc let aproj_to_string (ctx : eval_ctx) (p : aproj) : string = let env = eval_ctx_to_fmt_env ctx in @@ -565,13 +566,13 @@ module EvalCtx = struct let env = eval_ctx_to_fmt_env ctx in symbolic_value_to_string env sv - let typed_value_to_string (ctx : eval_ctx) (v : typed_value) : string = + let typed_value_to_string (meta : Meta.meta) (ctx : eval_ctx) (v : typed_value) : string = let env = eval_ctx_to_fmt_env ctx in - typed_value_to_string env v + typed_value_to_string meta env v - let typed_avalue_to_string (ctx : eval_ctx) (v : typed_avalue) : string = + let typed_avalue_to_string (meta : Meta.meta) (ctx : eval_ctx) (v : typed_avalue) : string = let env = eval_ctx_to_fmt_env ctx in - typed_avalue_to_string env v + typed_avalue_to_string meta env v let place_to_string (ctx : eval_ctx) (op : place) : string = let env = eval_ctx_to_fmt_env ctx in @@ -612,13 +613,13 @@ module EvalCtx = struct let env = eval_ctx_to_fmt_env ctx in trait_impl_to_string env " " " " timpl - let env_elem_to_string (ctx : eval_ctx) (indent : string) + let env_elem_to_string (meta : Meta.meta) (ctx : eval_ctx) (indent : string) (indent_incr : string) (ev : env_elem) : string = let env = eval_ctx_to_fmt_env ctx in - env_elem_to_string env false true indent indent_incr ev + env_elem_to_string meta env false true indent indent_incr ev - let abs_to_string (ctx : eval_ctx) (indent : string) (indent_incr : string) + let abs_to_string (meta : Meta.meta) (ctx : eval_ctx) (indent : string) (indent_incr : string) (abs : abs) : string = let env = eval_ctx_to_fmt_env ctx in - abs_to_string env false indent indent_incr abs + abs_to_string meta env false indent indent_incr abs end diff --git a/compiler/PrintPure.ml b/compiler/PrintPure.ml index 00a431a0..618a8afc 100644 --- a/compiler/PrintPure.ml +++ b/compiler/PrintPure.ml @@ -2,6 +2,7 @@ open Pure open PureUtils +open Errors (** The formatting context for pure definitions uses non-pure definitions to lookup names. The main reason is that when building the pure definitions @@ -293,7 +294,7 @@ let mplace_to_string (env : fmt_env) (p : mplace) : string = let name = name ^ "^" ^ E.VarId.to_string p.var_id ^ "llbc" in mprojection_to_string env name p.projection -let adt_variant_to_string (env : fmt_env) (adt_id : type_id) +let adt_variant_to_string (meta : Meta.meta) (env : fmt_env) (adt_id : type_id) (variant_id : VariantId.id option) : string = match adt_id with | TTuple -> "Tuple" @@ -307,29 +308,29 @@ let adt_variant_to_string (env : fmt_env) (adt_id : type_id) match aty with | TState | TArray | TSlice | TStr | TRawPtr _ -> (* Those types are opaque: we can't get there *) - raise (Failure "Unreachable") + craise meta "Unreachable" | TResult -> let variant_id = Option.get variant_id in if variant_id = result_return_id then "@Result::Return" else if variant_id = result_fail_id then "@Result::Fail" else - raise (Failure "Unreachable: improper variant id for result type") + craise meta "Unreachable: improper variant id for result type" | TError -> let variant_id = Option.get variant_id in if variant_id = error_failure_id then "@Error::Failure" else if variant_id = error_out_of_fuel_id then "@Error::OutOfFuel" - else raise (Failure "Unreachable: improper variant id for error type") + else craise meta "Unreachable: improper variant id for error type" | TFuel -> let variant_id = Option.get variant_id in if variant_id = fuel_zero_id then "@Fuel::Zero" else if variant_id = fuel_succ_id then "@Fuel::Succ" - else raise (Failure "Unreachable: improper variant id for fuel type")) + else craise meta "Unreachable: improper variant id for fuel type") -let adt_field_to_string (env : fmt_env) (adt_id : type_id) +let adt_field_to_string (meta : Meta.meta) (env : fmt_env) (adt_id : type_id) (field_id : FieldId.id) : string = match adt_id with | TTuple -> - raise (Failure "Unreachable") + craise meta "Unreachable" (* Tuples don't use the opaque field id for the field indices, but [int] *) | TAdtId def_id -> ( (* "Regular" ADT *) @@ -342,15 +343,15 @@ let adt_field_to_string (env : fmt_env) (adt_id : type_id) match aty with | TState | TFuel | TArray | TSlice | TStr -> (* Opaque types: we can't get there *) - raise (Failure "Unreachable") + craise meta "Unreachable" | TResult | TError | TRawPtr _ -> (* Enumerations: we can't get there *) - raise (Failure "Unreachable")) + craise meta "Unreachable") (** TODO: we don't need a general function anymore (it is now only used for patterns) *) -let adt_g_value_to_string (env : fmt_env) (value_to_string : 'v -> string) +let adt_g_value_to_string (meta : Meta.meta) (env : fmt_env) (value_to_string : 'v -> string) (variant_id : VariantId.id option) (field_values : 'v list) (ty : ty) : string = let field_values = List.map value_to_string field_values in @@ -385,50 +386,50 @@ let adt_g_value_to_string (env : fmt_env) (value_to_string : 'v -> string) match aty with | TState | TRawPtr _ -> (* This type is opaque: we can't get there *) - raise (Failure "Unreachable") + craise meta "Unreachable" | TResult -> let variant_id = Option.get variant_id in if variant_id = result_return_id then match field_values with | [ v ] -> "@Result::Return " ^ v - | _ -> raise (Failure "Result::Return takes exactly one value") + | _ -> craise meta "Result::Return takes exactly one value" else if variant_id = result_fail_id then match field_values with | [ v ] -> "@Result::Fail " ^ v - | _ -> raise (Failure "Result::Fail takes exactly one value") + | _ -> craise meta "Result::Fail takes exactly one value" else - raise (Failure "Unreachable: improper variant id for result type") + craise meta "Unreachable: improper variant id for result type" | TError -> - assert (field_values = []); + cassert (field_values = []) meta "TODO: error message"; let variant_id = Option.get variant_id in if variant_id = error_failure_id then "@Error::Failure" else if variant_id = error_out_of_fuel_id then "@Error::OutOfFuel" - else raise (Failure "Unreachable: improper variant id for error type") + else craise meta "Unreachable: improper variant id for error type" | TFuel -> let variant_id = Option.get variant_id in if variant_id = fuel_zero_id then ( - assert (field_values = []); + cassert (field_values = []) meta "TODO: error message"; "@Fuel::Zero") else if variant_id = fuel_succ_id then match field_values with | [ v ] -> "@Fuel::Succ " ^ v - | _ -> raise (Failure "@Fuel::Succ takes exactly one value") - else raise (Failure "Unreachable: improper variant id for fuel type") + | _ -> craise meta "@Fuel::Succ takes exactly one value" + else craise meta "Unreachable: improper variant id for fuel type" | TArray | TSlice | TStr -> - assert (variant_id = None); + cassert (variant_id = None) meta "TODO: error message"; let field_values = List.mapi (fun i v -> string_of_int i ^ " -> " ^ v) field_values in let id = assumed_ty_to_string aty in id ^ " [" ^ String.concat "; " field_values ^ "]") | _ -> - raise - (Failure + craise + meta ("Inconsistently typed value: expected ADT type but found:" ^ "\n- ty: " ^ ty_to_string env false ty ^ "\n- variant_id: " - ^ Print.option_to_string VariantId.to_string variant_id)) + ^ Print.option_to_string VariantId.to_string variant_id) -let rec typed_pattern_to_string (env : fmt_env) (v : typed_pattern) : string = +let rec typed_pattern_to_string (meta : Meta.meta) (env : fmt_env) (v : typed_pattern) : string = match v.value with | PatConstant cv -> literal_to_string cv | PatVar (v, None) -> var_to_string env v @@ -439,8 +440,8 @@ let rec typed_pattern_to_string (env : fmt_env) (v : typed_pattern) : string = ^ ")" | PatDummy -> "_" | PatAdt av -> - adt_g_value_to_string env - (typed_pattern_to_string env) + adt_g_value_to_string meta env + (typed_pattern_to_string meta env) av.variant_id av.field_values v.ty let fun_sig_to_string (env : fmt_env) (sg : fun_sig) : string = @@ -521,7 +522,7 @@ let fun_or_op_id_to_string (env : fmt_env) (fun_id : fun_or_op_id) : string = binop_to_string binop ^ "<" ^ integer_type_to_string int_ty ^ ">" (** [inside]: controls the introduction of parentheses *) -let rec texpression_to_string (env : fmt_env) (inside : bool) (indent : string) +let rec texpression_to_string (metadata : Meta.meta) (env : fmt_env) (inside : bool) (indent : string) (indent_incr : string) (e : texpression) : string = match e.e with | Var var_id -> var_id_to_string env var_id @@ -531,22 +532,22 @@ let rec texpression_to_string (env : fmt_env) (inside : bool) (indent : string) (* Recursively destruct the app, to have a pair (app, arguments list) *) let app, args = destruct_apps e in (* Convert to string *) - app_to_string env inside indent indent_incr app args + app_to_string metadata env inside indent indent_incr app args | Lambda _ -> let xl, e = destruct_lambdas e in - let e = lambda_to_string env indent indent_incr xl e in + let e = lambda_to_string metadata env indent indent_incr xl e in if inside then "(" ^ e ^ ")" else e | Qualif _ -> (* Qualifier without arguments *) - app_to_string env inside indent indent_incr e [] + app_to_string metadata env inside indent indent_incr e [] | Let (monadic, lv, re, e) -> - let e = let_to_string env indent indent_incr monadic lv re e in + let e = let_to_string metadata env indent indent_incr monadic lv re e in if inside then "(" ^ e ^ ")" else e | Switch (scrutinee, body) -> - let e = switch_to_string env indent indent_incr scrutinee body in + let e = switch_to_string metadata env indent indent_incr scrutinee body in if inside then "(" ^ e ^ ")" else e | Loop loop -> - let e = loop_to_string env indent indent_incr loop in + let e = loop_to_string metadata env indent indent_incr loop in if inside then "(" ^ e ^ ")" else e | StructUpdate supd -> ( let s = @@ -565,7 +566,7 @@ let rec texpression_to_string (env : fmt_env) (inside : bool) (indent : string) (fun (fid, fe) -> let field = FieldId.nth field_names fid in let fe = - texpression_to_string env false indent2 indent_incr fe + texpression_to_string metadata env false indent2 indent_incr fe in "\n" ^ indent1 ^ field ^ " := " ^ fe ^ ";") supd.updates @@ -576,21 +577,21 @@ let rec texpression_to_string (env : fmt_env) (inside : bool) (indent : string) let fields = List.map (fun (_, fe) -> - texpression_to_string env false indent2 indent_incr fe) + texpression_to_string metadata env false indent2 indent_incr fe) supd.updates in "[ " ^ String.concat ", " fields ^ " ]" - | _ -> raise (Failure "Unexpected")) + | _ -> craise metadata "Unexpected") | Meta (meta, e) -> ( - let meta_s = emeta_to_string env meta in - let e = texpression_to_string env inside indent indent_incr e in + let meta_s = emeta_to_string metadata env meta in + let e = texpression_to_string metadata env inside indent indent_incr e in match meta with | Assignment _ | SymbolicAssignments _ | SymbolicPlaces _ | Tag _ -> let e = meta_s ^ "\n" ^ indent ^ e in if inside then "(" ^ e ^ ")" else e | MPlace _ -> "(" ^ meta_s ^ " " ^ e ^ ")") -and app_to_string (env : fmt_env) (inside : bool) (indent : string) +and app_to_string (meta : Meta.meta) (env : fmt_env) (inside : bool) (indent : string) (indent_incr : string) (app : texpression) (args : texpression list) : string = (* There are two possibilities: either the [app] is an instantiated, @@ -610,13 +611,13 @@ and app_to_string (env : fmt_env) (inside : bool) (indent : string) (global_decl_id_to_string env global_id, generics) | AdtCons adt_cons_id -> let variant_s = - adt_variant_to_string env adt_cons_id.adt_id + adt_variant_to_string meta env adt_cons_id.adt_id adt_cons_id.variant_id in (ConstStrings.constructor_prefix ^ variant_s, []) | Proj { adt_id; field_id } -> - let adt_s = adt_variant_to_string env adt_id None in - let field_s = adt_field_to_string env adt_id field_id in + let adt_s = adt_variant_to_string meta env adt_id None in + let field_s = adt_field_to_string meta env adt_id field_id in (* Adopting an F*-like syntax *) (ConstStrings.constructor_prefix ^ adt_s ^ "?." ^ field_s, []) | TraitConst (trait_ref, const_name) -> @@ -626,7 +627,7 @@ and app_to_string (env : fmt_env) (inside : bool) (indent : string) | _ -> (* "Regular" expression case *) let inside = args <> [] || (args = [] && inside) in - (texpression_to_string env inside indent indent_incr app, []) + (texpression_to_string meta env inside indent indent_incr app, []) in (* Convert the arguments. * The arguments are expressions, so indentation might get weird... (though @@ -634,7 +635,7 @@ and app_to_string (env : fmt_env) (inside : bool) (indent : string) let arg_to_string = let inside = true in let indent1 = indent ^ indent_incr in - texpression_to_string env inside indent1 indent_incr + texpression_to_string meta env inside indent1 indent_incr in let args = List.map arg_to_string args in let all_args = List.append generics args in @@ -645,31 +646,31 @@ and app_to_string (env : fmt_env) (inside : bool) (indent : string) (* Add parentheses *) if all_args <> [] && inside then "(" ^ e ^ ")" else e -and lambda_to_string (env : fmt_env) (indent : string) (indent_incr : string) +and lambda_to_string (meta : Meta.meta) (env : fmt_env) (indent : string) (indent_incr : string) (xl : typed_pattern list) (e : texpression) : string = - let xl = List.map (typed_pattern_to_string env) xl in - let e = texpression_to_string env false indent indent_incr e in + let xl = List.map (typed_pattern_to_string meta env) xl in + let e = texpression_to_string meta env false indent indent_incr e in "λ " ^ String.concat " " xl ^ ". " ^ e -and let_to_string (env : fmt_env) (indent : string) (indent_incr : string) +and let_to_string (meta : Meta.meta) (env : fmt_env) (indent : string) (indent_incr : string) (monadic : bool) (lv : typed_pattern) (re : texpression) (e : texpression) : string = let indent1 = indent ^ indent_incr in let inside = false in - let re = texpression_to_string env inside indent1 indent_incr re in - let e = texpression_to_string env inside indent indent_incr e in - let lv = typed_pattern_to_string env lv in + let re = texpression_to_string meta env inside indent1 indent_incr re in + let e = texpression_to_string meta env inside indent indent_incr e in + let lv = typed_pattern_to_string meta env lv in if monadic then lv ^ " <-- " ^ re ^ ";\n" ^ indent ^ e else "let " ^ lv ^ " = " ^ re ^ " in\n" ^ indent ^ e -and switch_to_string (env : fmt_env) (indent : string) (indent_incr : string) +and switch_to_string (meta : Meta.meta) (env : fmt_env) (indent : string) (indent_incr : string) (scrutinee : texpression) (body : switch_body) : string = let indent1 = indent ^ indent_incr in (* Printing can mess up on the scrutinee, because it is an expression - but * in most situations it will be a value or a function call, so it should be * ok*) - let scrut = texpression_to_string env true indent1 indent_incr scrutinee in - let e_to_string = texpression_to_string env false indent1 indent_incr in + let scrut = texpression_to_string meta env true indent1 indent_incr scrutinee in + let e_to_string = texpression_to_string meta env false indent1 indent_incr in match body with | If (e_true, e_false) -> let e_true = e_to_string e_true in @@ -678,13 +679,13 @@ and switch_to_string (env : fmt_env) (indent : string) (indent_incr : string) ^ indent ^ "else\n" ^ indent1 ^ e_false | Match branches -> let branch_to_string (b : match_branch) : string = - let pat = typed_pattern_to_string env b.pat in + let pat = typed_pattern_to_string meta env b.pat in indent ^ "| " ^ pat ^ " ->\n" ^ indent1 ^ e_to_string b.branch in let branches = List.map branch_to_string branches in "match " ^ scrut ^ " with\n" ^ String.concat "\n" branches -and loop_to_string (env : fmt_env) (indent : string) (indent_incr : string) +and loop_to_string (meta : Meta.meta) (env : fmt_env) (indent : string) (indent_incr : string) (loop : loop) : string = let indent1 = indent ^ indent_incr in let indent2 = indent1 ^ indent_incr in @@ -695,17 +696,17 @@ and loop_to_string (env : fmt_env) (indent : string) (indent_incr : string) in let output_ty = "output_ty: " ^ ty_to_string env false loop.output_ty in let fun_end = - texpression_to_string env false indent2 indent_incr loop.fun_end + texpression_to_string meta env false indent2 indent_incr loop.fun_end in let loop_body = - texpression_to_string env false indent2 indent_incr loop.loop_body + texpression_to_string meta env false indent2 indent_incr loop.loop_body in "loop {\n" ^ indent1 ^ loop_inputs ^ "\n" ^ indent1 ^ output_ty ^ "\n" ^ indent1 ^ "fun_end: {\n" ^ indent2 ^ fun_end ^ "\n" ^ indent1 ^ "}\n" ^ indent1 ^ "loop_body: {\n" ^ indent2 ^ loop_body ^ "\n" ^ indent1 ^ "}\n" ^ indent ^ "}" -and emeta_to_string (env : fmt_env) (meta : emeta) : string = +and emeta_to_string (metadata : Meta.meta) (env : fmt_env) (meta : emeta) : string = let meta = match meta with | Assignment (lp, rv, rp) -> @@ -715,14 +716,14 @@ and emeta_to_string (env : fmt_env) (meta : emeta) : string = | Some rp -> " [@src=" ^ mplace_to_string env rp ^ "]" in "@assign(" ^ mplace_to_string env lp ^ " := " - ^ texpression_to_string env false "" "" rv + ^ texpression_to_string metadata env false "" "" rv ^ rp ^ ")" | SymbolicAssignments info -> let infos = List.map (fun (var_id, rv) -> VarId.to_string var_id ^ " == " - ^ texpression_to_string env false "" "" rv) + ^ texpression_to_string metadata env false "" "" rv) info in let infos = String.concat ", " infos in @@ -755,5 +756,5 @@ let fun_decl_to_string (env : fmt_env) (def : fun_decl) : string = if inputs = [] then indent else " fun " ^ String.concat " " inputs ^ " ->\n" ^ indent in - let body = texpression_to_string env inside indent indent body.body in + let body = texpression_to_string def.meta env inside indent indent body.body in "let " ^ name ^ " :\n " ^ signature ^ " =\n" ^ inputs ^ body diff --git a/compiler/PureMicroPasses.ml b/compiler/PureMicroPasses.ml index a1f6ce33..2fb33036 100644 --- a/compiler/PureMicroPasses.ml +++ b/compiler/PureMicroPasses.ml @@ -3,6 +3,7 @@ open Pure open PureUtils open TranslateCore +open Errors (** The local logger *) let log = Logging.pure_micro_passes_log @@ -221,7 +222,7 @@ let compute_pretty_names (def : fun_decl) : fun_decl = (* Register a variable for constraints propagation - used when an variable is * introduced (left-hand side of a left binding) *) let register_var (ctx : pn_ctx) (v : var) : pn_ctx = - assert (not (VarId.Map.mem v.id ctx.pure_vars)); + cassert (not (VarId.Map.mem v.id ctx.pure_vars)) def.meta "TODO: error message"; match v.basename with | None -> ctx | Some name -> @@ -610,7 +611,7 @@ let intro_struct_updates (ctx : trans_ctx) (def : fun_decl) : fun_decl = | App _ -> ( let app, args = destruct_apps e in let ignore () = - mk_apps + mk_apps def.meta (self#visit_texpression env app) (List.map (self#visit_texpression env) args) in @@ -755,7 +756,7 @@ let simplify_let_bindings (_ctx : trans_ctx) (def : fun_decl) : fun_decl = else if variant_id = result_fail_id then (* Fail case *) self#visit_expression env rv.e - else raise (Failure "Unexpected") + else craise def.meta "Unexpected" | App _ -> (* This might be the tuple case *) if not monadic then @@ -910,7 +911,7 @@ let inline_useless_var_reassignments (ctx : trans_ctx) ~(inline_named : bool) } ) -> (* Second case: we deconstruct a structure with one field that we will extract as tuple. *) - let adt_id, _ = PureUtils.ty_as_adt re.ty in + let adt_id, _ = PureUtils.ty_as_adt def.meta re.ty in (* Update the rhs (we may perform substitutions inside, and it is * better to do them *before* we inline it *) let re = self#visit_texpression env re in @@ -1091,7 +1092,7 @@ let filter_useless (_ctx : trans_ctx) (def : fun_decl) : fun_decl = f y ]} *) -let simplify_let_then_return _ctx def = +let simplify_let_then_return _ctx (def : fun_decl) = (* Match a pattern and an expression: evaluates to [true] if the expression is actually exactly the pattern *) let rec match_pattern_and_expr (pat : typed_pattern) (e : texpression) : bool @@ -1139,7 +1140,7 @@ let simplify_let_then_return _ctx def = (* The first let-binding is monadic *) match opt_destruct_ret next_e with | Some e -> - if match_pattern_and_expr lv e then rv.e else not_simpl_e + if match_pattern_and_expr def.meta lv e then rv.e else not_simpl_e | None -> not_simpl_e else (* The first let-binding is not monadic *) @@ -1147,7 +1148,7 @@ let simplify_let_then_return _ctx def = | Some e -> if match_pattern_and_expr lv e then (* We need to wrap the right-value in a ret *) - (mk_result_return_texpression rv).e + (mk_result_return_texpression def.meta rv).e else not_simpl_e | None -> if match_pattern_and_expr lv next_e then rv.e else not_simpl_e @@ -1197,13 +1198,13 @@ let simplify_aggregates (ctx : trans_ctx) (def : fun_decl) : fun_decl = in let fields = match adt_decl.kind with - | Enum _ | Opaque -> raise (Failure "Unreachable") + | Enum _ | Opaque -> craise def.meta "Unreachable" | Struct fields -> fields in let num_fields = List.length fields in (* In order to simplify, there must be as many arguments as * there are fields *) - assert (num_fields > 0); + cassert (num_fields > 0) def.meta "The number of fields is not > 0"; if num_fields = List.length args then (* We now need to check that all the arguments are of the form: * [x.field] for some variable [x], and where the projection @@ -1239,10 +1240,10 @@ let simplify_aggregates (ctx : trans_ctx) (def : fun_decl) : fun_decl = if List.for_all (fun (_, y) -> y = x) end_args then ( (* We can substitute *) (* Sanity check: all types correct *) - assert ( + cassert ( List.for_all (fun (generics1, _) -> generics1 = generics) - args); + args) def.meta "All types are not correct"; { e with e = Var x }) else super#visit_texpression env e else super#visit_texpression env e @@ -1397,7 +1398,7 @@ let decompose_loops (_ctx : trans_ctx) (def : fun_decl) : { fwd_info; effect_info = loop_fwd_effect_info; ignore_output } in - assert (fun_sig_info_is_wf loop_fwd_sig_info); + cassert (fun_sig_info_is_wf loop_fwd_sig_info) def.meta "TODO: error message"; let inputs_tys = let fuel = if !Config.use_fuel then [ mk_fuel_ty ] else [] in @@ -1437,9 +1438,9 @@ let decompose_loops (_ctx : trans_ctx) (def : fun_decl) : (* Introduce the forward input state *) let fwd_state_var, fwd_state_lvs = - assert ( + cassert ( loop_fwd_effect_info.stateful - = Option.is_some loop.input_state); + = Option.is_some loop.input_state) def.meta "TODO: error message"; match loop.input_state with | None -> ([], []) | Some input_state -> @@ -1476,7 +1477,7 @@ let decompose_loops (_ctx : trans_ctx) (def : fun_decl) : match fuel_vars with | None -> loop.loop_body | Some (fuel0, fuel) -> - SymbolicToPure.wrap_in_match_fuel fuel0 fuel loop.loop_body + SymbolicToPure.wrap_in_match_fuel def.meta fuel0 fuel loop.loop_body in let loop_body = { inputs; inputs_lvs; body = loop_body } in @@ -1569,9 +1570,9 @@ let eliminate_box_functions (_ctx : trans_ctx) (def : fun_decl) : fun_decl = match aid with | BoxNew -> let arg, args = Collections.List.pop args in - mk_apps arg args + mk_apps def.meta arg args | BoxFree -> - assert (args = []); + cassert (args = []) def.meta "TODO: error message"; mk_unit_rvalue | SliceIndexShared | SliceIndexMut | ArrayIndexShared | ArrayIndexMut | ArrayToSliceShared | ArrayToSliceMut @@ -1765,8 +1766,8 @@ let unfold_monadic_let_bindings (_ctx : trans_ctx) (def : fun_decl) : fun_decl = *) (* TODO: this information should be computed in SymbolicToPure and * store in an enum ("monadic" should be an enum, not a bool). *) - let re_ty = Option.get (opt_destruct_result re.ty) in - assert (lv.ty = re_ty); + let re_ty = Option.get (opt_destruct_result def.meta re.ty) in + cassert (lv.ty = re_ty) def.meta "TODO: error message"; let err_vid = fresh_id () in let err_var : var = { @@ -1778,7 +1779,7 @@ let unfold_monadic_let_bindings (_ctx : trans_ctx) (def : fun_decl) : fun_decl = let err_pat = mk_typed_pattern_from_var err_var None in let fail_pat = mk_result_fail_pattern err_pat.value lv.ty in let err_v = mk_texpression_from_var err_var in - let fail_value = mk_result_fail_texpression err_v e.ty in + let fail_value = mk_result_fail_texpression def.meta err_v e.ty in let fail_branch = { pat = fail_pat; branch = fail_value } in let success_pat = mk_result_return_pattern lv in let success_branch = { pat = success_pat; branch = e } in @@ -1980,7 +1981,7 @@ let filter_loop_inputs (ctx : trans_ctx) (transl : pure_fun_translation list) : (List.concat (List.map (fun { f; loops } -> [ f :: loops ]) transl)) in let subgroups = ReorderDecls.group_reorder_fun_decls all_decls in - +(* TODO meta or not meta ? *) log#ldebug (lazy ("filter_loop_inputs: all_decls:\n\n" @@ -2020,7 +2021,7 @@ let filter_loop_inputs (ctx : trans_ctx) (transl : pure_fun_translation list) : ^ String.concat ", " (List.map (var_to_string ctx) inputs_prefix) ^ "\n")); let inputs_set = VarId.Set.of_list (List.map var_get_id inputs_prefix) in - assert (Option.is_some decl.loop_id); + cassert (Option.is_some decl.loop_id) decl.meta "TODO: error message"; let fun_id = (E.FRegular decl.def_id, decl.loop_id) in @@ -2172,7 +2173,7 @@ let filter_loop_inputs (ctx : trans_ctx) (transl : pure_fun_translation list) : in let fwd_info = { fwd_info; effect_info; ignore_output } in - assert (fun_sig_info_is_wf fwd_info); + cassert (fun_sig_info_is_wf fwd_info) decl.meta "TODO: error message"; let signature = { generics; @@ -2238,17 +2239,17 @@ let filter_loop_inputs (ctx : trans_ctx) (transl : pure_fun_translation list) : in (* Rebuild *) - mk_apps e_app args) + mk_apps decl.meta e_app args) | _ -> let e_app = self#visit_texpression env e_app in let args = List.map (self#visit_texpression env) args in - mk_apps e_app args) + mk_apps decl.meta e_app args) | _ -> let e_app = self#visit_texpression env e_app in let args = List.map (self#visit_texpression env) args in - mk_apps e_app args) + mk_apps decl.meta e_app args) | _ -> super#visit_texpression env e end in diff --git a/compiler/PureTypeCheck.ml b/compiler/PureTypeCheck.ml index fc94fa4c..6bc11a7c 100644 --- a/compiler/PureTypeCheck.ml +++ b/compiler/PureTypeCheck.ml @@ -2,21 +2,22 @@ open Pure open PureUtils +open Errors (** Utility function, used for type checking. This function should only be used for "regular" ADTs, where the number of fields is fixed: it shouldn't be used for arrays, slices, etc. *) -let get_adt_field_types (type_decls : type_decl TypeDeclId.Map.t) +let get_adt_field_types (meta : Meta.meta) (type_decls : type_decl TypeDeclId.Map.t) (type_id : type_id) (variant_id : VariantId.id option) (generics : generic_args) : ty list = match type_id with | TTuple -> (* Tuple *) - assert (generics.const_generics = []); - assert (generics.trait_refs = []); - assert (variant_id = None); + cassert (generics.const_generics = []) meta "TODO: error message"; + cassert (generics.trait_refs = []) meta "TODO: error message"; + cassert (variant_id = None) meta "TODO: error message"; generics.types | TAdtId def_id -> (* "Regular" ADT *) @@ -27,29 +28,29 @@ let get_adt_field_types (type_decls : type_decl TypeDeclId.Map.t) match aty with | TState -> (* This type is opaque *) - raise (Failure "Unreachable: opaque type") + craise meta "Unreachable: opaque type" | TResult -> let ty = Collections.List.to_cons_nil generics.types in let variant_id = Option.get variant_id in if variant_id = result_return_id then [ ty ] else if variant_id = result_fail_id then [ mk_error_ty ] else - raise (Failure "Unreachable: improper variant id for result type") + craise meta "Unreachable: improper variant id for result type" | TError -> - assert (generics = empty_generic_args); + cassert (generics = empty_generic_args) meta "TODO: error message"; let variant_id = Option.get variant_id in - assert ( - variant_id = error_failure_id || variant_id = error_out_of_fuel_id); + cassert ( + variant_id = error_failure_id || variant_id = error_out_of_fuel_id) meta "TODO: error message"; [] | TFuel -> let variant_id = Option.get variant_id in if variant_id = fuel_zero_id then [] else if variant_id = fuel_succ_id then [ mk_fuel_ty ] - else raise (Failure "Unreachable: improper variant id for fuel type") + else craise meta "Unreachable: improper variant id for fuel type" | TArray | TSlice | TStr | TRawPtr _ -> (* Array: when not symbolic values (for instance, because of aggregates), the array expressions are introduced as struct updates *) - raise (Failure "Attempting to access the fields of an opaque type")) + craise meta "Attempting to access the fields of an opaque type") type tc_ctx = { type_decls : type_decl TypeDeclId.Map.t; (** The type declarations *) @@ -61,28 +62,28 @@ type tc_ctx = { (* TODO: add trait type constraints *) } -let check_literal (v : literal) (ty : literal_type) : unit = +let check_literal (meta : Meta.meta) (v : literal) (ty : literal_type) : unit = match (ty, v) with - | TInteger int_ty, VScalar sv -> assert (int_ty = sv.int_ty) + | TInteger int_ty, VScalar sv -> cassert (int_ty = sv.int_ty) meta "TODO: error message" | TBool, VBool _ | TChar, VChar _ -> () - | _ -> raise (Failure "Inconsistent type") + | _ -> craise meta "Inconsistent type" -let rec check_typed_pattern (ctx : tc_ctx) (v : typed_pattern) : tc_ctx = +let rec check_typed_pattern (meta : Meta.meta) (ctx : tc_ctx) (v : typed_pattern) : tc_ctx = log#ldebug (lazy ("check_typed_pattern: " ^ show_typed_pattern v)); match v.value with | PatConstant cv -> - check_literal cv (ty_as_literal v.ty); + check_literal meta cv (ty_as_literal meta v.ty); ctx | PatDummy -> ctx | PatVar (var, _) -> - assert (var.ty = v.ty); + cassert (var.ty = v.ty) meta "TODO: error message"; let env = VarId.Map.add var.id var.ty ctx.env in { ctx with env } | PatAdt av -> (* Compute the field types *) - let type_id, generics = ty_as_adt v.ty in + let type_id, generics = ty_as_adt meta v.ty in let field_tys = - get_adt_field_types ctx.type_decls type_id av.variant_id generics + get_adt_field_types meta ctx.type_decls type_id av.variant_id generics in let check_value (ctx : tc_ctx) (ty : ty) (v : typed_pattern) : tc_ctx = if ty <> v.ty then ( @@ -90,8 +91,8 @@ let rec check_typed_pattern (ctx : tc_ctx) (v : typed_pattern) : tc_ctx = log#serror ("check_typed_pattern: not the same types:" ^ "\n- ty: " ^ show_ty ty ^ "\n- v.ty: " ^ show_ty v.ty); - raise (Failure "Inconsistent types")); - check_typed_pattern ctx v + craise meta "Inconsistent types"); + check_typed_pattern meta ctx v in (* Check the field types: check that the field patterns have the expected * types, and check that the field patterns themselves are well-typed *) @@ -100,7 +101,7 @@ let rec check_typed_pattern (ctx : tc_ctx) (v : typed_pattern) : tc_ctx = ctx (List.combine field_tys av.field_values) -let rec check_texpression (ctx : tc_ctx) (e : texpression) : unit = +let rec check_texpression (meta : Meta.meta) (ctx : tc_ctx) (e : texpression) : unit = match e.e with | Var var_id -> ( (* Lookup the variable - note that the variable may not be there, @@ -109,24 +110,24 @@ let rec check_texpression (ctx : tc_ctx) (e : texpression) : unit = * we use a locally nameless representation *) match VarId.Map.find_opt var_id ctx.env with | None -> () - | Some ty -> assert (ty = e.ty)) + | Some ty -> cassert (ty = e.ty) meta "TODO: error message") | CVar cg_id -> let ty = T.ConstGenericVarId.Map.find cg_id ctx.const_generics in - assert (ty = e.ty) - | Const cv -> check_literal cv (ty_as_literal e.ty) + cassert (ty = e.ty) meta "TODO: error message" + | Const cv -> check_literal meta cv (ty_as_literal meta e.ty) | App (app, arg) -> - let input_ty, output_ty = destruct_arrow app.ty in - assert (input_ty = arg.ty); - assert (output_ty = e.ty); - check_texpression ctx app; - check_texpression ctx arg + let input_ty, output_ty = destruct_arrow meta app.ty in + cassert (input_ty = arg.ty) meta "TODO: error message"; + cassert (output_ty = e.ty) meta "TODO: error message"; + check_texpression meta ctx app; + check_texpression meta ctx arg | Lambda (pat, body) -> - let pat_ty, body_ty = destruct_arrow e.ty in - assert (pat.ty = pat_ty); - assert (body.ty = body_ty); + let pat_ty, body_ty = destruct_arrow meta e.ty in + cassert (pat.ty = pat_ty) meta "TODO: error message"; + cassert (body.ty = body_ty) meta "TODO: error message"; (* Check the pattern and register the introduced variables at the same time *) - let ctx = check_typed_pattern ctx pat in - check_texpression ctx body + let ctx = check_typed_pattern meta ctx pat in + check_texpression meta ctx body | Qualif qualif -> ( match qualif.id with | FunOrOp _ -> () (* TODO *) @@ -135,83 +136,83 @@ let rec check_texpression (ctx : tc_ctx) (e : texpression) : unit = | Proj { adt_id = proj_adt_id; field_id } -> (* Note we can only project fields of structures (not enumerations) *) (* Deconstruct the projector type *) - let adt_ty, field_ty = destruct_arrow e.ty in - let adt_id, adt_generics = ty_as_adt adt_ty in + let adt_ty, field_ty = destruct_arrow meta e.ty in + let adt_id, adt_generics = ty_as_adt meta adt_ty in (* Check the ADT type *) - assert (adt_id = proj_adt_id); - assert (adt_generics = qualif.generics); + cassert (adt_id = proj_adt_id) meta "TODO: error message"; + cassert (adt_generics = qualif.generics) meta "TODO: error message"; (* Retrieve and check the expected field type *) let variant_id = None in let expected_field_tys = - get_adt_field_types ctx.type_decls proj_adt_id variant_id + get_adt_field_types meta ctx.type_decls proj_adt_id variant_id qualif.generics in let expected_field_ty = FieldId.nth expected_field_tys field_id in - assert (expected_field_ty = field_ty) + cassert (expected_field_ty = field_ty) meta "TODO: error message" | AdtCons id -> ( let expected_field_tys = - get_adt_field_types ctx.type_decls id.adt_id id.variant_id + get_adt_field_types meta ctx.type_decls id.adt_id id.variant_id qualif.generics in let field_tys, adt_ty = destruct_arrows e.ty in - assert (expected_field_tys = field_tys); + cassert (expected_field_tys = field_tys) meta "TODO: error message"; match adt_ty with | TAdt (type_id, generics) -> - assert (type_id = id.adt_id); - assert (generics = qualif.generics) - | _ -> raise (Failure "Unreachable"))) + cassert (type_id = id.adt_id) meta "TODO: error message"; + cassert (generics = qualif.generics) meta "TODO: error message" + | _ -> craise meta "Unreachable")) | Let (monadic, pat, re, e_next) -> - let expected_pat_ty = if monadic then destruct_result re.ty else re.ty in - assert (pat.ty = expected_pat_ty); - assert (e.ty = e_next.ty); + let expected_pat_ty = if monadic then destruct_result meta re.ty else re.ty in + cassert (pat.ty = expected_pat_ty) meta "TODO: error message"; + cassert (e.ty = e_next.ty) meta "TODO: error message"; (* Check the right-expression *) - check_texpression ctx re; + check_texpression meta ctx re; (* Check the pattern and register the introduced variables at the same time *) - let ctx = check_typed_pattern ctx pat in + let ctx = check_typed_pattern meta ctx pat in (* Check the next expression *) - check_texpression ctx e_next + check_texpression meta ctx e_next | Switch (scrut, switch_body) -> ( - check_texpression ctx scrut; + check_texpression meta ctx scrut; match switch_body with | If (e_then, e_else) -> - assert (scrut.ty = TLiteral TBool); - assert (e_then.ty = e.ty); - assert (e_else.ty = e.ty); - check_texpression ctx e_then; - check_texpression ctx e_else + cassert (scrut.ty = TLiteral TBool) meta "TODO: error message"; + cassert (e_then.ty = e.ty) meta "TODO: error message"; + cassert (e_else.ty = e.ty) meta "TODO: error message"; + check_texpression meta ctx e_then; + check_texpression meta ctx e_else | Match branches -> let check_branch (br : match_branch) : unit = - assert (br.pat.ty = scrut.ty); - let ctx = check_typed_pattern ctx br.pat in - check_texpression ctx br.branch + cassert (br.pat.ty = scrut.ty) meta "TODO: error message"; + let ctx = check_typed_pattern meta ctx br.pat in + check_texpression meta ctx br.branch in List.iter check_branch branches) | Loop loop -> - assert (loop.fun_end.ty = e.ty); - check_texpression ctx loop.fun_end; - check_texpression ctx loop.loop_body + cassert (loop.fun_end.ty = e.ty) meta "TODO: error message"; + check_texpression meta ctx loop.fun_end; + check_texpression meta ctx loop.loop_body | StructUpdate supd -> ( (* Check the init value *) (if Option.is_some supd.init then match VarId.Map.find_opt (Option.get supd.init) ctx.env with | None -> () - | Some ty -> assert (ty = e.ty)); + | Some ty -> cassert (ty = e.ty) meta "TODO: error message"); (* Check the fields *) (* Retrieve and check the expected field type *) - let adt_id, adt_generics = ty_as_adt e.ty in - assert (adt_id = supd.struct_id); + let adt_id, adt_generics = ty_as_adt meta e.ty in + cassert (adt_id = supd.struct_id) meta "TODO: error message"; (* The id can only be: a custom type decl or an array *) match adt_id with | TAdtId _ -> let variant_id = None in let expected_field_tys = - get_adt_field_types ctx.type_decls adt_id variant_id adt_generics + get_adt_field_types meta ctx.type_decls adt_id variant_id adt_generics in List.iter (fun ((fid, fe) : _ * texpression) -> let expected_field_ty = FieldId.nth expected_field_tys fid in - assert (expected_field_ty = fe.ty); - check_texpression ctx fe) + cassert (expected_field_ty = fe.ty) meta "TODO: error message"; + check_texpression meta ctx fe) supd.updates | TAssumed TArray -> let expected_field_ty = @@ -219,10 +220,10 @@ let rec check_texpression (ctx : tc_ctx) (e : texpression) : unit = in List.iter (fun ((_, fe) : _ * texpression) -> - assert (expected_field_ty = fe.ty); - check_texpression ctx fe) + cassert (expected_field_ty = fe.ty) meta "TODO: error message"; + check_texpression meta ctx fe) supd.updates - | _ -> raise (Failure "Unexpected")) + | _ -> craise meta "Unexpected") | Meta (_, e_next) -> - assert (e_next.ty = e.ty); - check_texpression ctx e_next + cassert (e_next.ty = e.ty) meta "TODO: error message"; + check_texpression meta ctx e_next diff --git a/compiler/PureUtils.ml b/compiler/PureUtils.ml index 81e3fbe1..05373ce8 100644 --- a/compiler/PureUtils.ml +++ b/compiler/PureUtils.ml @@ -1,4 +1,5 @@ open Pure +open Errors (** Default logger *) let log = Logging.pure_utils_log @@ -74,10 +75,10 @@ let inputs_info_is_wf (info : inputs_info) : bool = let fun_sig_info_is_wf (info : fun_sig_info) : bool = inputs_info_is_wf info.fwd_info -let dest_arrow_ty (ty : ty) : ty * ty = +let dest_arrow_ty (meta : Meta.meta) (ty : ty) : ty * ty = match ty with | TArrow (arg_ty, ret_ty) -> (arg_ty, ret_ty) - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" let compute_literal_type (cv : literal) : literal_type = match cv with @@ -213,30 +214,30 @@ let fun_sig_substitute (subst : subst) (sg : fun_sig) : inst_fun_sig = Rem.: this function will *fail* if there are {!Pure.Loop} nodes (you should call it on an expression where those nodes have been eliminated). *) -let rec let_group_requires_parentheses (e : texpression) : bool = +let rec let_group_requires_parentheses (meta : Meta.meta) (e : texpression) : bool = match e.e with | Var _ | CVar _ | Const _ | App _ | Qualif _ | StructUpdate _ -> false | Let (monadic, _, _, next_e) -> - if monadic then true else let_group_requires_parentheses next_e + if monadic then true else let_group_requires_parentheses meta next_e | Switch (_, _) -> false - | Meta (_, next_e) -> let_group_requires_parentheses next_e + | Meta (_, next_e) -> let_group_requires_parentheses meta next_e | Lambda (_, _) -> (* Being conservative here *) true | Loop _ -> (* Should have been eliminated *) - raise (Failure "Unreachable") + craise meta "Unreachable" -let texpression_requires_parentheses e = +let texpression_requires_parentheses meta e = match !Config.backend with | FStar | Lean -> false - | Coq | HOL4 -> let_group_requires_parentheses e + | Coq | HOL4 -> let_group_requires_parentheses meta e let is_var (e : texpression) : bool = match e.e with Var _ -> true | _ -> false -let as_var (e : texpression) : VarId.id = - match e.e with Var v -> v | _ -> raise (Failure "Unreachable") +let as_var (meta : Meta.meta) (e : texpression) : VarId.id = + match e.e with Var v -> v | _ -> craise meta "Unreachable" let is_cvar (e : texpression) : bool = match e.e with CVar _ -> true | _ -> false @@ -247,10 +248,10 @@ let is_global (e : texpression) : bool = let is_const (e : texpression) : bool = match e.e with Const _ -> true | _ -> false -let ty_as_adt (ty : ty) : type_id * generic_args = +let ty_as_adt (meta : Meta.meta) (ty : ty) : type_id * generic_args = match ty with | TAdt (id, generics) -> (id, generics) - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" (** Remove the external occurrences of {!Meta} *) let rec unmeta (e : texpression) : texpression = @@ -287,13 +288,13 @@ let rec destruct_lets (e : texpression) : (** Destruct an expression into a list of nested lets, where there is no interleaving between monadic and non-monadic lets. *) -let destruct_lets_no_interleave (e : texpression) : +let destruct_lets_no_interleave (meta : Meta.meta) (e : texpression) : (bool * typed_pattern * texpression) list * texpression = (* Find the "kind" of the first let (monadic or non-monadic) *) let m = match e.e with | Let (monadic, _, _, _) -> monadic - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" in (* Destruct the rest *) let rec destruct_lets (e : texpression) : @@ -320,9 +321,9 @@ let destruct_apps (e : texpression) : texpression * texpression list = aux [] e (** Make an [App (app, arg)] expression *) -let mk_app (app : texpression) (arg : texpression) : texpression = +let mk_app (meta : Meta.meta) (app : texpression) (arg : texpression) : texpression = let raise_or_return msg = - if !Config.fail_hard then raise (Failure msg) + if !Config.fail_hard then craise meta msg else let e = App (app, arg) in (* Dummy type - TODO: introduce an error type *) @@ -343,8 +344,8 @@ let mk_app (app : texpression) (arg : texpression) : texpression = | _ -> raise_or_return "Expected an arrow type" (** The reverse of {!destruct_apps} *) -let mk_apps (app : texpression) (args : texpression list) : texpression = - List.fold_left (fun app arg -> mk_app app arg) app args +let mk_apps (meta : Meta.meta) (app : texpression) (args : texpression list) : texpression = + List.fold_left (fun app arg -> mk_app meta app arg) app args (** Destruct an expression into a qualif identifier and a list of arguments, * if possible *) @@ -367,28 +368,28 @@ let opt_destruct_function_call (e : texpression) : | FunOrOp fun_id -> Some (fun_id, qualif.generics, args) | _ -> None) -let opt_destruct_result (ty : ty) : ty option = +let opt_destruct_result (meta : Meta.meta) (ty : ty) : ty option = match ty with | TAdt (TAssumed TResult, generics) -> - assert (generics.const_generics = []); - assert (generics.trait_refs = []); + cassert (generics.const_generics = []) meta "TODO: Error message"; + cassert (generics.trait_refs = []) meta "TODO: Error message"; Some (Collections.List.to_cons_nil generics.types) | _ -> None -let destruct_result (ty : ty) : ty = Option.get (opt_destruct_result ty) +let destruct_result (meta : Meta.meta) (ty : ty) : ty = Option.get (opt_destruct_result meta ty) -let opt_destruct_tuple (ty : ty) : ty list option = +let opt_destruct_tuple (meta : Meta.meta) (ty : ty) : ty list option = match ty with | TAdt (TTuple, generics) -> - assert (generics.const_generics = []); - assert (generics.trait_refs = []); + cassert (generics.const_generics = []) meta "TODO: Error message"; + cassert (generics.trait_refs = []) meta "TODO: Error message"; Some generics.types | _ -> None -let destruct_arrow (ty : ty) : ty * ty = +let destruct_arrow (meta : Meta.meta) (ty : ty) : ty * ty = match ty with | TArrow (ty0, ty1) -> (ty0, ty1) - | _ -> raise (Failure "Not an arrow type") + | _ -> craise meta "Not an arrow type" let rec destruct_arrows (ty : ty) : ty list * ty = match ty with @@ -422,17 +423,17 @@ let iter_switch_body_branches (f : texpression -> unit) (sb : switch_body) : f e_else | Match branches -> List.iter (fun (b : match_branch) -> f b.branch) branches -let mk_switch (scrut : texpression) (sb : switch_body) : texpression = +let mk_switch (meta : Meta.meta) (scrut : texpression) (sb : switch_body) : texpression = (* Sanity check: the scrutinee has the proper type *) (match sb with - | If (_, _) -> assert (scrut.ty = TLiteral TBool) + | If (_, _) -> cassert (scrut.ty = TLiteral TBool) meta "The scrutinee does not have the proper type" | Match branches -> List.iter - (fun (b : match_branch) -> assert (b.pat.ty = scrut.ty)) + (fun (b : match_branch) -> cassert (b.pat.ty = scrut.ty) meta "The scrutinee does not have the proper type") branches); (* Sanity check: all the branches have the same type *) let ty = get_switch_body_ty sb in - iter_switch_body_branches (fun e -> assert (e.ty = ty)) sb; + iter_switch_body_branches (fun e -> cassert (e.ty = ty) meta "All branches should have the same type") sb; (* Put together *) let e = Switch (scrut, sb) in { e; ty } @@ -497,7 +498,7 @@ let mk_simpl_tuple_pattern (vl : typed_pattern list) : typed_pattern = { value; ty } (** Similar to {!mk_simpl_tuple_pattern} *) -let mk_simpl_tuple_texpression (vl : texpression list) : texpression = +let mk_simpl_tuple_texpression (meta : Meta.meta) (vl : texpression list) : texpression = match vl with | [ v ] -> v | _ -> @@ -510,20 +511,20 @@ let mk_simpl_tuple_texpression (vl : texpression list) : texpression = let qualif = { id; generics = mk_generic_args_from_types tys } in (* Put everything together *) let cons = { e = Qualif qualif; ty } in - mk_apps cons vl + mk_apps meta cons vl let mk_adt_pattern (adt_ty : ty) (variant_id : VariantId.id option) (vl : typed_pattern list) : typed_pattern = let value = PatAdt { variant_id; field_values = vl } in { value; ty = adt_ty } -let ty_as_integer (t : ty) : T.integer_type = +let ty_as_integer (meta : Meta.meta) (t : ty) : T.integer_type = match t with | TLiteral (TInteger int_ty) -> int_ty - | _ -> raise (Failure "Unreachable") + | _ -> craise meta "Unreachable" -let ty_as_literal (t : ty) : T.literal_type = - match t with TLiteral ty -> ty | _ -> raise (Failure "Unreachable") +let ty_as_literal (meta : Meta.meta) (t : ty) : T.literal_type = + match t with TLiteral ty -> ty | _ -> craise meta "Unreachable" let mk_state_ty : ty = TAdt (TAssumed TState, empty_generic_args) @@ -540,15 +541,15 @@ let mk_error (error : VariantId.id) : texpression = let e = Qualif qualif in { e; ty } -let unwrap_result_ty (ty : ty) : ty = +let unwrap_result_ty (meta : Meta.meta) (ty : ty) : ty = match ty with | TAdt ( TAssumed TResult, { types = [ ty ]; const_generics = []; trait_refs = [] } ) -> ty - | _ -> raise (Failure "not a result type") + | _ -> craise meta "not a result type" -let mk_result_fail_texpression (error : texpression) (ty : ty) : texpression = +let mk_result_fail_texpression (meta : Meta.meta) (error : texpression) (ty : ty) : texpression = let type_args = [ ty ] in let ty = TAdt (TAssumed TResult, mk_generic_args_from_types type_args) in let id = @@ -558,14 +559,14 @@ let mk_result_fail_texpression (error : texpression) (ty : ty) : texpression = let cons_e = Qualif qualif in let cons_ty = mk_arrow error.ty ty in let cons = { e = cons_e; ty = cons_ty } in - mk_app cons error + mk_app meta cons error -let mk_result_fail_texpression_with_error_id (error : VariantId.id) (ty : ty) : +let mk_result_fail_texpression_with_error_id (meta : Meta.meta) (error : VariantId.id) (ty : ty) : texpression = let error = mk_error error in - mk_result_fail_texpression error ty + mk_result_fail_texpression meta error ty -let mk_result_return_texpression (v : texpression) : texpression = +let mk_result_return_texpression (meta : Meta.meta) (v : texpression) : texpression = let type_args = [ v.ty ] in let ty = TAdt (TAssumed TResult, mk_generic_args_from_types type_args) in let id = @@ -575,7 +576,7 @@ let mk_result_return_texpression (v : texpression) : texpression = let cons_e = Qualif qualif in let cons_ty = mk_arrow v.ty ty in let cons = { e = cons_e; ty = cons_ty } in - mk_app cons v + mk_app meta cons v (** Create a [Fail err] pattern which captures the error *) let mk_result_fail_pattern (error_pat : pattern) (ty : ty) : typed_pattern = @@ -613,7 +614,7 @@ let mk_fuel_var (id : VarId.id) : var = let mk_fuel_texpression (id : VarId.id) : texpression = { e = Var id; ty = mk_fuel_ty } -let rec typed_pattern_to_texpression (pat : typed_pattern) : texpression option +let rec typed_pattern_to_texpression (meta : Meta.meta) (pat : typed_pattern) : texpression option = let e_opt = match pat.value with @@ -621,13 +622,13 @@ let rec typed_pattern_to_texpression (pat : typed_pattern) : texpression option | PatVar (v, _) -> Some (Var v.id) | PatDummy -> None | PatAdt av -> - let fields = List.map typed_pattern_to_texpression av.field_values in + let fields = List.map (typed_pattern_to_texpression meta) av.field_values in if List.mem None fields then None else let fields_values = List.map (fun e -> Option.get e) fields in (* Retrieve the type id and the type args from the pat type (simpler this way *) - let adt_id, generics = ty_as_adt pat.ty in + let adt_id, generics = ty_as_adt meta pat.ty in (* Create the constructor *) let qualif_id = AdtCons { adt_id; variant_id = av.variant_id } in @@ -640,7 +641,7 @@ let rec typed_pattern_to_texpression (pat : typed_pattern) : texpression option let cons = { e = cons_e; ty = cons_ty } in (* Apply the constructor *) - Some (mk_apps cons fields_values).e + Some (mk_apps meta cons fields_values).e in match e_opt with None -> None | Some e -> Some { e; ty = pat.ty } diff --git a/compiler/RegionsHierarchy.ml b/compiler/RegionsHierarchy.ml index 0b589453..4ebdd01a 100644 --- a/compiler/RegionsHierarchy.ml +++ b/compiler/RegionsHierarchy.ml @@ -34,23 +34,24 @@ open LlbcAst open LlbcAstUtils open Assumed open SCC +open Errors module Subst = Substitute (** The local logger *) let log = Logging.regions_hierarchy_log -let compute_regions_hierarchy_for_sig (type_decls : type_decl TypeDeclId.Map.t) +let compute_regions_hierarchy_for_sig (meta : Meta.meta option) (type_decls : type_decl TypeDeclId.Map.t) (fun_decls : fun_decl FunDeclId.Map.t) (global_decls : global_decl GlobalDeclId.Map.t) (trait_decls : trait_decl TraitDeclId.Map.t) - (trait_impls : trait_impl TraitImplId.Map.t) (fun_name : string) + (trait_impls : trait_impl TraitImplId.Map.t) (* ?meta *) (fun_name : string) (sg : fun_sig) : region_var_groups = log#ldebug (lazy (__FUNCTION__ ^ ": " ^ fun_name)); (* Initialize a normalization context (we may need to normalize some associated types) *) let norm_ctx : AssociatedTypes.norm_ctx = let norm_trait_types = - AssociatedTypes.compute_norm_trait_types_from_preds + AssociatedTypes.compute_norm_trait_types_from_preds meta sg.preds.trait_type_constraints in { @@ -105,8 +106,8 @@ let compute_regions_hierarchy_for_sig (type_decls : type_decl TypeDeclId.Map.t) let add_edge ~(short : region) ~(long : region) = (* Sanity checks *) - assert (short <> RErased); - assert (long <> RErased); + cassert_opt_meta (short <> RErased) meta "TODO: Error message"; + cassert_opt_meta (long <> RErased) meta "TODO: Error message"; (* Ignore the locally bound regions (at the level of arrow types for instance *) match (short, long) with | RBVar _, _ | _, RBVar _ -> () @@ -172,13 +173,13 @@ let compute_regions_hierarchy_for_sig (type_decls : type_decl TypeDeclId.Map.t) | TTraitType (trait_ref, _) -> (* The trait should reference a clause, and not an implementation (otherwise it should have been normalized) *) - assert ( - AssociatedTypes.trait_instance_id_is_local_clause trait_ref.trait_id); + cassert_opt_meta ( + AssociatedTypes.trait_instance_id_is_local_clause trait_ref.trait_id) meta "The trait should reference a clause, and not an implementation (otherwise it should have been normalized)"; (* We have nothing to do *) () | TArrow (regions, inputs, output) -> (* TODO: *) - assert (regions = []); + cassert_opt_meta (regions = []) meta "Regions should be empty"; (* We can ignore the outer regions *) List.iter (explore_ty []) (output :: inputs) and explore_generics (outer : region list) (generics : generic_args) = @@ -221,7 +222,7 @@ let compute_regions_hierarchy_for_sig (type_decls : type_decl TypeDeclId.Map.t) (SccId.Map.bindings sccs.sccs) in (* The SCC should only contain the 'static *) - assert (static_scc = [ RStatic ]); + cassert_opt_meta (static_scc = [ RStatic ]) meta "The SCC should only contain the 'static"; (* Remove the group as well as references to this group from the other SCCs *) let { sccs; scc_deps } = sccs in @@ -277,7 +278,7 @@ let compute_regions_hierarchy_for_sig (type_decls : type_decl TypeDeclId.Map.t) (fun r -> match r with | RFVar rid -> RegionId.Map.find rid region_id_to_var_map - | _ -> raise (Failure "Unreachable")) + | _ -> craise (Option.get meta) "Unreachable") scc in @@ -317,19 +318,19 @@ let compute_regions_hierarchies (type_decls : type_decl TypeDeclId.Map.t) let regular = List.map (fun ((fid, d) : FunDeclId.id * fun_decl) -> - (FRegular fid, (Types.name_to_string env d.name, d.signature))) + (FRegular fid, (Types.name_to_string env d.name, d.signature, Some d.meta))) (FunDeclId.Map.bindings fun_decls) in let assumed = List.map (fun (info : assumed_fun_info) -> - (FAssumed info.fun_id, (info.name, info.fun_sig))) + (FAssumed info.fun_id, (info.name, info.fun_sig, None))) assumed_fun_infos in FunIdMap.of_list (List.map - (fun (fid, (name, sg)) -> + (fun (fid, (name, sg, meta)) -> ( fid, - compute_regions_hierarchy_for_sig type_decls fun_decls global_decls - trait_decls trait_impls name sg )) + compute_regions_hierarchy_for_sig meta type_decls fun_decls global_decls + trait_decls trait_impls name sg)) (regular @ assumed)) diff --git a/compiler/Substitute.ml b/compiler/Substitute.ml index dbd310b7..a35fdbf3 100644 --- a/compiler/Substitute.ml +++ b/compiler/Substitute.ml @@ -7,6 +7,7 @@ open Types open Values open LlbcAst open Contexts +open Errors (** Generate fresh regions for region variables. @@ -67,25 +68,25 @@ let ctx_adt_get_instantiated_field_types (ctx : eval_ctx) **IMPORTANT**: this function doesn't normalize the types, you may want to use the [AssociatedTypes] equivalent instead. *) -let ctx_adt_value_get_instantiated_field_types (ctx : eval_ctx) +let ctx_adt_value_get_instantiated_field_types (meta : Meta.meta) (ctx : eval_ctx) (adt : adt_value) (id : type_id) (generics : generic_args) : ty list = match id with | TAdtId id -> (* Retrieve the types of the fields *) ctx_adt_get_instantiated_field_types ctx id adt.variant_id generics | TTuple -> - assert (generics.regions = []); + cassert (generics.regions = []) meta "Regions should be empty TODO: error message"; generics.types | TAssumed aty -> ( match aty with | TBox -> - assert (generics.regions = []); - assert (List.length generics.types = 1); - assert (generics.const_generics = []); + cassert (generics.regions = []) meta "Regions should be empty TODO: error message"; + cassert (List.length generics.types = 1) meta "Too many types TODO: error message"; + cassert (generics.const_generics = []) meta "const_generics should be empty TODO: error message"; generics.types | TArray | TSlice | TStr -> (* Those types don't have fields *) - raise (Failure "Unreachable")) + craise meta "Unreachable") (** Substitute a function signature, together with the regions hierarchy associated to that signature. @@ -144,30 +145,30 @@ let subst_ids_visitor (r_subst : RegionId.id -> RegionId.id) method! visit_abstraction_id _ id = asubst id end -let typed_value_subst_ids (r_subst : RegionId.id -> RegionId.id) +let typed_value_subst_ids (meta : Meta.meta) (r_subst : RegionId.id -> RegionId.id) (ty_subst : TypeVarId.id -> TypeVarId.id) (cg_subst : ConstGenericVarId.id -> ConstGenericVarId.id) (ssubst : SymbolicValueId.id -> SymbolicValueId.id) (bsubst : BorrowId.id -> BorrowId.id) (v : typed_value) : typed_value = - let asubst _ = raise (Failure "Unreachable") in + let asubst _ = craise meta "Unreachable" in let vis = subst_ids_visitor r_subst ty_subst cg_subst ssubst bsubst asubst in vis#visit_typed_value () v -let typed_value_subst_rids (r_subst : RegionId.id -> RegionId.id) +let typed_value_subst_rids (meta : Meta.meta) (r_subst : RegionId.id -> RegionId.id) (v : typed_value) : typed_value = - typed_value_subst_ids r_subst + typed_value_subst_ids meta r_subst (fun x -> x) (fun x -> x) (fun x -> x) (fun x -> x) v -let typed_avalue_subst_ids (r_subst : RegionId.id -> RegionId.id) +let typed_avalue_subst_ids (meta : Meta.meta) (r_subst : RegionId.id -> RegionId.id) (ty_subst : TypeVarId.id -> TypeVarId.id) (cg_subst : ConstGenericVarId.id -> ConstGenericVarId.id) (ssubst : SymbolicValueId.id -> SymbolicValueId.id) (bsubst : BorrowId.id -> BorrowId.id) (v : typed_avalue) : typed_avalue = - let asubst _ = raise (Failure "Unreachable") in + let asubst _ = craise meta "Unreachable" in let vis = subst_ids_visitor r_subst ty_subst cg_subst ssubst bsubst asubst in vis#visit_typed_avalue () v @@ -189,9 +190,9 @@ let env_subst_ids (r_subst : RegionId.id -> RegionId.id) let vis = subst_ids_visitor r_subst ty_subst cg_subst ssubst bsubst asubst in vis#visit_env () x -let typed_avalue_subst_rids (r_subst : RegionId.id -> RegionId.id) +let typed_avalue_subst_rids (meta : Meta.meta) (r_subst : RegionId.id -> RegionId.id) (x : typed_avalue) : typed_avalue = - let asubst _ = raise (Failure "Unreachable") in + let asubst _ = craise meta "Unreachable" in let vis = subst_ids_visitor r_subst (fun x -> x) diff --git a/compiler/SymbolicToPure.ml b/compiler/SymbolicToPure.ml index b612ab70..6e3a537e 100644 --- a/compiler/SymbolicToPure.ml +++ b/compiler/SymbolicToPure.ml @@ -325,7 +325,7 @@ let symbolic_value_to_string (ctx : bs_ctx) (sv : V.symbolic_value) : string = let typed_value_to_string (ctx : bs_ctx) (v : V.typed_value) : string = let env = bs_ctx_to_fmt_env ctx in - Print.Values.typed_value_to_string env v + Print.Values.typed_value_to_string ctx.fun_decl.meta env v let pure_ty_to_string (ctx : bs_ctx) (ty : ty) : string = let env = bs_ctx_to_pure_fmt_env ctx in @@ -349,7 +349,7 @@ let pure_type_decl_to_string (ctx : bs_ctx) (def : type_decl) : string = let texpression_to_string (ctx : bs_ctx) (e : texpression) : string = let env = bs_ctx_to_pure_fmt_env ctx in - PrintPure.texpression_to_string env false "" " " e + PrintPure.texpression_to_string ctx.fun_decl.meta env false "" " " e let fun_id_to_string (ctx : bs_ctx) (id : A.fun_id) : string = let env = bs_ctx_to_fmt_env ctx in @@ -363,9 +363,9 @@ let fun_decl_to_string (ctx : bs_ctx) (def : Pure.fun_decl) : string = let env = bs_ctx_to_pure_fmt_env ctx in PrintPure.fun_decl_to_string env def -let typed_pattern_to_string (ctx : bs_ctx) (p : Pure.typed_pattern) : string = +let typed_pattern_to_string (meta : Meta.meta) (ctx : bs_ctx) (p : Pure.typed_pattern) : string = let env = bs_ctx_to_pure_fmt_env ctx in - PrintPure.typed_pattern_to_string env p + PrintPure.typed_pattern_to_string meta env p let ctx_get_effect_info_for_bid (ctx : bs_ctx) (bid : RegionGroupId.id option) : fun_effect_info = @@ -384,7 +384,7 @@ let abs_to_string (ctx : bs_ctx) (abs : V.abs) : string = let verbose = false in let indent = "" in let indent_incr = " " in - Print.Values.abs_to_string env verbose indent indent_incr abs + Print.Values.abs_to_string ctx.fun_decl.meta env verbose indent indent_incr abs let bs_ctx_lookup_llbc_type_decl (id : TypeDeclId.id) (ctx : bs_ctx) : T.type_decl = @@ -450,7 +450,7 @@ let rec translate_sty (meta : Meta.meta) (ty : T.ty) : ty = match type_id with | T.TAdtId adt_id -> TAdt (TAdtId adt_id, generics) | T.TTuple -> - assert (generics.const_generics = []); + cassert (generics.const_generics = []) meta "TODO: error message"; mk_simpl_tuple_ty generics.types | T.TAssumed aty -> ( match aty with @@ -541,7 +541,7 @@ let translate_type_decl_kind (meta : Meta.meta) (kind : T.type_decl_kind) : type Remark: this is not symbolic to pure but LLBC to pure. Still, I don't see the point of moving this definition for now. *) -let translate_type_decl (meta : Meta.meta) (ctx : Contexts.decls_ctx) (def : T.type_decl) : +let translate_type_decl (ctx : Contexts.decls_ctx) (def : T.type_decl) : type_decl = log#ldebug (lazy @@ -555,11 +555,11 @@ let translate_type_decl (meta : Meta.meta) (ctx : Contexts.decls_ctx) (def : T.t let name = Print.Types.name_to_string env def.name in let { T.regions; types; const_generics; trait_clauses } = def.generics in (* Can't translate types with regions for now *) - assert (regions = []); - let trait_clauses = List.map (translate_trait_clause meta) trait_clauses in + cassert (regions = []) def.meta "Translating types with regions is not supported yet"; + let trait_clauses = List.map (translate_trait_clause def.meta) trait_clauses in let generics = { types; const_generics; trait_clauses } in - let kind = translate_type_decl_kind meta def.T.kind in - let preds = translate_predicates meta def.preds in + let kind = translate_type_decl_kind def.meta def.T.kind in + let preds = translate_predicates def.meta def.preds in let is_local = def.is_local in let meta = def.meta in { @@ -616,11 +616,11 @@ let rec translate_fwd_ty (meta : Meta.meta) (type_infos : type_infos) (ty : T.ty | TAssumed TBox -> ( (* We eliminate boxes *) (* No general parametricity for now *) - assert ( + cassert ( not (List.exists (TypesUtils.ty_has_borrows type_infos) - generics.types)); + generics.types)) meta "General parametricity is not supported yet"; match t_generics.types with | [ bty ] -> bty | _ -> @@ -655,15 +655,15 @@ and translate_fwd_trait_instance_id (meta : Meta.meta) (type_infos : type_infos) translate_trait_instance_id meta (translate_fwd_ty meta type_infos) id (** Simply calls [translate_fwd_ty] *) -let ctx_translate_fwd_ty (meta : Meta.meta) (ctx : bs_ctx) (ty : T.ty) : ty = +let ctx_translate_fwd_ty (ctx : bs_ctx) (ty : T.ty) : ty = let type_infos = ctx.type_ctx.type_infos in - translate_fwd_ty meta type_infos ty + translate_fwd_ty ctx.fun_decl.meta type_infos ty (** Simply calls [translate_fwd_generic_args] *) -let ctx_translate_fwd_generic_args (meta : Meta.meta) (ctx : bs_ctx) (generics : T.generic_args) : +let ctx_translate_fwd_generic_args (ctx : bs_ctx) (generics : T.generic_args) : generic_args = let type_infos = ctx.type_ctx.type_infos in - translate_fwd_generic_args meta type_infos generics + translate_fwd_generic_args ctx.fun_decl.meta type_infos generics (** Translate a type, when some regions may have ended. @@ -701,7 +701,7 @@ let rec translate_back_ty (meta : Meta.meta) (type_infos : type_infos) else None | TAssumed TBox -> ( (* Don't accept ADTs (which are not tuples) with borrows for now *) - assert (not (TypesUtils.ty_has_borrows type_infos ty)); + cassert (not (TypesUtils.ty_has_borrows type_infos ty)) meta "ADTs with borrows are not supported yet"; (* Eliminate the box *) match generics.types with | [ bty ] -> translate bty @@ -747,17 +747,17 @@ let rec translate_back_ty (meta : Meta.meta) (type_infos : type_infos) | TArrow _ -> craise meta "TODO" (** Simply calls [translate_back_ty] *) -let ctx_translate_back_ty (meta : Meta.meta) (ctx : bs_ctx) (keep_region : 'r -> bool) +let ctx_translate_back_ty (ctx : bs_ctx) (keep_region : 'r -> bool) (inside_mut : bool) (ty : T.ty) : ty option = let type_infos = ctx.type_ctx.type_infos in - translate_back_ty meta type_infos keep_region inside_mut ty + translate_back_ty ctx.fun_decl.meta type_infos keep_region inside_mut ty -let mk_type_check_ctx (meta : Meta.meta) (ctx : bs_ctx) : PureTypeCheck.tc_ctx = +let mk_type_check_ctx (ctx : bs_ctx) : PureTypeCheck.tc_ctx = let const_generics = T.ConstGenericVarId.Map.of_list (List.map (fun (cg : T.const_generic_var) -> - (cg.index, ctx_translate_fwd_ty meta ctx (T.TLiteral cg.ty))) + (cg.index, ctx_translate_fwd_ty ctx (T.TLiteral cg.ty))) ctx.sg.generics.const_generics) in let env = VarId.Map.empty in @@ -768,23 +768,25 @@ let mk_type_check_ctx (meta : Meta.meta) (ctx : bs_ctx) : PureTypeCheck.tc_ctx = const_generics; } -let type_check_pattern (meta : Meta.meta) (ctx : bs_ctx) (v : typed_pattern) : unit = - let ctx = mk_type_check_ctx meta ctx in - let _ = PureTypeCheck.check_typed_pattern ctx v in +let type_check_pattern (ctx : bs_ctx) (v : typed_pattern) : unit = + let meta = ctx.fun_decl.meta in + let ctx = mk_type_check_ctx ctx in + let _ = PureTypeCheck.check_typed_pattern meta ctx v in () -let type_check_texpression (meta : Meta.meta) (ctx : bs_ctx) (e : texpression) : unit = +let type_check_texpression (ctx : bs_ctx) (e : texpression) : unit = if !Config.type_check_pure_code then - let ctx = mk_type_check_ctx meta ctx in - PureTypeCheck.check_texpression ctx e + let meta = ctx.fun_decl.meta in + let ctx = mk_type_check_ctx ctx in + PureTypeCheck.check_texpression meta ctx e -let translate_fun_id_or_trait_method_ref (meta : Meta.meta) (ctx : bs_ctx) +let translate_fun_id_or_trait_method_ref (ctx : bs_ctx) (id : A.fun_id_or_trait_method_ref) : fun_id_or_trait_method_ref = match id with | FunId fun_id -> FunId fun_id | TraitMethod (trait_ref, method_name, fun_decl_id) -> let type_infos = ctx.type_ctx.type_infos in - let trait_ref = translate_fwd_trait_ref meta type_infos trait_ref in + let trait_ref = translate_fwd_trait_ref ctx.fun_decl.meta type_infos trait_ref in TraitMethod (trait_ref, method_name, fun_decl_id) let bs_ctx_register_forward_call (call_id : V.FunCallId.id) (forward : S.call) @@ -792,7 +794,7 @@ let bs_ctx_register_forward_call (call_id : V.FunCallId.id) (forward : S.call) (back_funs : texpression option RegionGroupId.Map.t option) (ctx : bs_ctx) : bs_ctx = let calls = ctx.calls in - assert (not (V.FunCallId.Map.mem call_id calls)); + cassert (not (V.FunCallId.Map.mem call_id calls)) ctx.fun_decl.meta "TODO: error message"; let info = { forward; forward_inputs = args; back_funs } in let calls = V.FunCallId.Map.add call_id info calls in { ctx with calls } @@ -806,7 +808,7 @@ let bs_ctx_register_forward_call (call_id : V.FunCallId.id) (forward : S.call) that we need to call. This function may be [None] if it has to be ignored (because it does nothing). *) -let bs_ctx_register_backward_call (meta : Meta.meta) (abs : V.abs) (call_id : V.FunCallId.id) +let bs_ctx_register_backward_call (abs : V.abs) (call_id : V.FunCallId.id) (back_id : T.RegionGroupId.id) (back_args : texpression list) (ctx : bs_ctx) : bs_ctx * texpression option = (* Insert the abstraction in the call informations *) @@ -814,7 +816,7 @@ let bs_ctx_register_backward_call (meta : Meta.meta) (abs : V.abs) (call_id : V. let calls = V.FunCallId.Map.add call_id info ctx.calls in (* Insert the abstraction in the abstractions map *) let abstractions = ctx.abstractions in - assert (not (V.AbstractionId.Map.mem abs.abs_id abstractions)); + cassert (not (V.AbstractionId.Map.mem abs.abs_id abstractions)) ctx.fun_decl.meta "This abstraction should not be in the abstractions map"; let abstractions = V.AbstractionId.Map.add abs.abs_id (abs, back_args) abstractions in @@ -876,7 +878,7 @@ let mk_fuel_input_as_list (ctx : bs_ctx) (info : fun_effect_info) : if function_uses_fuel info then [ mk_fuel_texpression ctx.fuel ] else [] (** Small utility. *) -let compute_raw_fun_effect_info (fun_infos : fun_info A.FunDeclId.Map.t) +let compute_raw_fun_effect_info (* (meta : Meta.meta) *) (fun_infos : fun_info A.FunDeclId.Map.t) (fun_id : A.fun_id_or_trait_method_ref) (lid : V.LoopId.id option) (gid : T.RegionGroupId.id option) : fun_effect_info = match fun_id with @@ -894,7 +896,7 @@ let compute_raw_fun_effect_info (fun_infos : fun_info A.FunDeclId.Map.t) is_rec = info.is_rec || Option.is_some lid; } | FunId (FAssumed aid) -> - assert (lid = None); + assert (lid = None) (* meta "TODO: error message" *); { can_fail = Assumed.assumed_fun_can_fail aid; stateful_group = false; @@ -904,7 +906,7 @@ let compute_raw_fun_effect_info (fun_infos : fun_info A.FunDeclId.Map.t) } (** TODO: not very clean. *) -let get_fun_effect_info (meta : Meta.meta) (ctx : bs_ctx) (fun_id : A.fun_id_or_trait_method_ref) +let get_fun_effect_info (ctx : bs_ctx) (fun_id : A.fun_id_or_trait_method_ref) (lid : V.LoopId.id option) (gid : T.RegionGroupId.id option) : fun_effect_info = match lid with @@ -919,19 +921,19 @@ let get_fun_effect_info (meta : Meta.meta) (ctx : bs_ctx) (fun_id : A.fun_id_or_ in { info with is_rec = info.is_rec || Option.is_some lid } | FunId (FAssumed _) -> - compute_raw_fun_effect_info ctx.fun_ctx.fun_infos fun_id lid gid) + compute_raw_fun_effect_info (* ctx.fun_decl.meta *) ctx.fun_ctx.fun_infos fun_id lid gid) | Some lid -> ( (* This is necessarily for the current function *) match fun_id with | FunId (FRegular fid) -> ( - assert (fid = ctx.fun_decl.def_id); + cassert (fid = ctx.fun_decl.def_id) ctx.fun_decl.meta "TODO: error message"; (* Lookup the loop *) let lid = V.LoopId.Map.find lid ctx.loop_ids_map in let loop_info = LoopId.Map.find lid ctx.loops in match gid with | None -> loop_info.fwd_effect_info | Some gid -> RegionGroupId.Map.find gid loop_info.back_effect_infos) - | _ -> craise meta "Unreachable") + | _ -> craise ctx.fun_decl.meta "Unreachable") (** Translate a function signature to a decomposed function signature. @@ -960,11 +962,11 @@ let translate_fun_sig_with_regions_hierarchy_to_decomposed (meta : Meta.meta) List.map (fun (g : T.region_var_group) -> g.id) regions_hierarchy in let ctx = - InterpreterUtils.initialize_eval_ctx decls_ctx region_groups + InterpreterUtils.initialize_eval_ctx meta decls_ctx region_groups sg.generics.types sg.generics.const_generics in (* Compute the normalization map for the *sty* types and add it to the context *) - AssociatedTypes.ctx_add_norm_trait_types_from_preds ctx + AssociatedTypes.ctx_add_norm_trait_types_from_preds meta ctx sg.preds.trait_type_constraints in @@ -1029,7 +1031,7 @@ let translate_fun_sig_with_regions_hierarchy_to_decomposed (meta : Meta.meta) (* For now we don't supported nested borrows, so we check that there aren't parent regions *) let parents = list_ancestor_region_groups regions_hierarchy gid in - assert (T.RegionGroupId.Set.is_empty parents); + cassert (T.RegionGroupId.Set.is_empty parents) meta "Nested borrows are not supported yet"; (* For now, we don't allow nested borrows, so the additional inputs to the backward function can only come from borrows that were returned like in (for the backward function we introduce for 'a): @@ -1186,7 +1188,7 @@ let translate_fun_sig_with_regions_hierarchy_to_decomposed (meta : Meta.meta) else false in let info = { fwd_info; effect_info = fwd_effect_info; ignore_output } in - assert (fun_sig_info_is_wf info); + cassert (fun_sig_info_is_wf info) meta "TODO: error message"; info in @@ -1205,17 +1207,18 @@ let translate_fun_sig_with_regions_hierarchy_to_decomposed (meta : Meta.meta) fwd_info; } -let translate_fun_sig_to_decomposed (meta : Meta.meta) (decls_ctx : C.decls_ctx) +let translate_fun_sig_to_decomposed (decls_ctx : C.decls_ctx) (fun_id : FunDeclId.id) (sg : A.fun_sig) (input_names : string option list) : decomposed_fun_sig = (* Retrieve the list of parent backward functions *) let regions_hierarchy = FunIdMap.find (FRegular fun_id) decls_ctx.fun_ctx.regions_hierarchies in + let meta = (FunDeclId.Map.find fun_id decls_ctx.fun_ctx.fun_decls).meta in translate_fun_sig_with_regions_hierarchy_to_decomposed meta decls_ctx (FunId (FRegular fun_id)) regions_hierarchy sg input_names -let translate_fun_sig_from_decl_to_decomposed (meta : Meta.meta) (decls_ctx : C.decls_ctx) +let translate_fun_sig_from_decl_to_decomposed (decls_ctx : C.decls_ctx) (fdef : LlbcAst.fun_decl) : decomposed_fun_sig = let input_names = match fdef.body with @@ -1226,7 +1229,7 @@ let translate_fun_sig_from_decl_to_decomposed (meta : Meta.meta) (decls_ctx : C. (LlbcAstUtils.fun_body_get_input_vars body) in let sg = - translate_fun_sig_to_decomposed meta decls_ctx fdef.def_id fdef.signature + translate_fun_sig_to_decomposed decls_ctx fdef.def_id fdef.signature input_names in log#ldebug @@ -1322,7 +1325,7 @@ let compute_output_ty_from_decomposed (dsg : Pure.decomposed_fun_sig) : ty = in mk_output_ty_from_effect_info effect_info output -let translate_fun_sig_from_decomposed (dsg : Pure.decomposed_fun_sig) : fun_sig +let translate_fun_sig_from_decomposed (meta : Meta.meta) (dsg : Pure.decomposed_fun_sig) : fun_sig = let generics = dsg.generics in let llbc_generics = dsg.llbc_generics in @@ -1358,21 +1361,21 @@ let bs_ctx_fresh_state_var (ctx : bs_ctx) : bs_ctx * var * typed_pattern = (** WARNING: do not call this function directly. Call [fresh_named_var_for_symbolic_value] instead. *) -let fresh_var_llbc_ty (meta : Meta.meta) (basename : string option) (ty : T.ty) (ctx : bs_ctx) : +let fresh_var_llbc_ty (basename : string option) (ty : T.ty) (ctx : bs_ctx) : bs_ctx * var = (* Generate the fresh variable *) let id, var_counter = VarId.fresh !(ctx.var_counter) in - let ty = ctx_translate_fwd_ty meta ctx ty in + let ty = ctx_translate_fwd_ty ctx ty in let var = { id; basename; ty } in (* Update the context *) ctx.var_counter := var_counter; (* Return *) (ctx, var) -let fresh_named_var_for_symbolic_value (meta : Meta.meta) (basename : string option) +let fresh_named_var_for_symbolic_value (basename : string option) (sv : V.symbolic_value) (ctx : bs_ctx) : bs_ctx * var = (* Generate the fresh variable *) - let ctx, var = fresh_var_llbc_ty meta basename sv.sv_ty ctx in + let ctx, var = fresh_var_llbc_ty basename sv.sv_ty ctx in (* Insert in the map *) let sv_to_var = V.SymbolicValueId.Map.add_strict sv.sv_id var ctx.sv_to_var in (* Update the context *) @@ -1380,19 +1383,19 @@ let fresh_named_var_for_symbolic_value (meta : Meta.meta) (basename : string opt (* Return *) (ctx, var) -let fresh_var_for_symbolic_value (meta : Meta.meta) (sv : V.symbolic_value) (ctx : bs_ctx) : +let fresh_var_for_symbolic_value (sv : V.symbolic_value) (ctx : bs_ctx) : bs_ctx * var = - fresh_named_var_for_symbolic_value meta None sv ctx + fresh_named_var_for_symbolic_value None sv ctx -let fresh_vars_for_symbolic_values (meta : Meta.meta) (svl : V.symbolic_value list) (ctx : bs_ctx) +let fresh_vars_for_symbolic_values (svl : V.symbolic_value list) (ctx : bs_ctx) : bs_ctx * var list = - List.fold_left_map (fun ctx sv -> fresh_var_for_symbolic_value meta sv ctx) ctx svl + List.fold_left_map (fun ctx sv -> fresh_var_for_symbolic_value sv ctx) ctx svl -let fresh_named_vars_for_symbolic_values (meta : Meta.meta) +let fresh_named_vars_for_symbolic_values (svl : (string option * V.symbolic_value) list) (ctx : bs_ctx) : bs_ctx * var list = List.fold_left_map - (fun ctx (name, sv) -> fresh_named_var_for_symbolic_value meta name sv ctx) + (fun ctx (name, sv) -> fresh_named_var_for_symbolic_value name sv ctx) ctx svl (** This generates a fresh variable **which is not to be linked to any symbolic value** *) @@ -1470,12 +1473,12 @@ let fresh_back_vars_for_current_fun (ctx : bs_ctx) fresh_opt_vars back_vars ctx (** IMPORTANT: do not use this one directly, but rather {!symbolic_value_to_texpression} *) -let lookup_var_for_symbolic_value (meta : Meta.meta) (sv : V.symbolic_value) (ctx : bs_ctx) : var = +let lookup_var_for_symbolic_value (sv : V.symbolic_value) (ctx : bs_ctx) : var = match V.SymbolicValueId.Map.find_opt sv.sv_id ctx.sv_to_var with | Some v -> v | None -> craise - meta + ctx.fun_decl.meta ("Could not find var for symbolic value: " ^ V.SymbolicValueId.to_string sv.sv_id) @@ -1494,15 +1497,15 @@ let rec unbox_typed_value (meta : Meta.meta) (v : V.typed_value) : V.typed_value of (translated) type unit, it is important that we do not lookup variables in case the symbolic value has type unit. *) -let symbolic_value_to_texpression (meta : Meta.meta) (ctx : bs_ctx) (sv : V.symbolic_value) : +let symbolic_value_to_texpression (ctx : bs_ctx) (sv : V.symbolic_value) : texpression = (* Translate the type *) - let ty = ctx_translate_fwd_ty meta ctx sv.sv_ty in + let ty = ctx_translate_fwd_ty ctx sv.sv_ty in (* If the type is unit, directly return unit *) if ty_is_unit ty then mk_unit_rvalue else (* Otherwise lookup the variable *) - let var = lookup_var_for_symbolic_value meta sv ctx in + let var = lookup_var_for_symbolic_value sv ctx in mk_texpression_from_var var (** Translate a typed value. @@ -1521,13 +1524,13 @@ let symbolic_value_to_texpression (meta : Meta.meta) (ctx : bs_ctx) (sv : V.symb - end abstraction - return *) -let rec typed_value_to_texpression (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.eval_ctx) +let rec typed_value_to_texpression (ctx : bs_ctx) (ectx : C.eval_ctx) (v : V.typed_value) : texpression = (* We need to ignore boxes *) - let v = unbox_typed_value meta v in - let translate = typed_value_to_texpression meta ctx ectx in + let v = unbox_typed_value ctx.fun_decl.meta v in + let translate = typed_value_to_texpression ctx ectx in (* Translate the type *) - let ty = ctx_translate_fwd_ty meta ctx v.ty in + let ty = ctx_translate_fwd_ty ctx v.ty in (* Translate the value *) let value = match v.value with @@ -1538,12 +1541,12 @@ let rec typed_value_to_texpression (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.e (* Eliminate the tuple wrapper if it is a tuple with exactly one field *) match v.ty with | TAdt (TTuple, _) -> - assert (variant_id = None); - mk_simpl_tuple_texpression field_values + cassert (variant_id = None) ctx.fun_decl.meta "TODO: error message"; + mk_simpl_tuple_texpression ctx.fun_decl.meta field_values | _ -> (* Retrieve the type and the translated generics from the translated type (simpler this way) *) - let adt_id, generics = ty_as_adt ty in + let adt_id, generics = ty_as_adt ctx.fun_decl.meta ty in (* Create the constructor *) let qualif_id = AdtCons { adt_id; variant_id = av.variant_id } in let qualif = { id = qualif_id; generics } in @@ -1554,28 +1557,28 @@ let rec typed_value_to_texpression (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.e let cons_ty = mk_arrows field_tys ty in let cons = { e = cons_e; ty = cons_ty } in (* Apply the constructor *) - mk_apps cons field_values) - | VBottom -> craise meta "Unreachable" + mk_apps ctx.fun_decl.meta cons field_values) + | VBottom -> craise ctx.fun_decl.meta "Unreachable" | VLoan lc -> ( match lc with | VSharedLoan (_, v) -> translate v - | VMutLoan _ -> craise meta "Unreachable") + | VMutLoan _ -> craise ctx.fun_decl.meta "Unreachable") | VBorrow bc -> ( match bc with | VSharedBorrow bid -> (* Lookup the shared value in the context, and continue *) - let sv = InterpreterBorrowsCore.lookup_shared_value meta ectx bid in + let sv = InterpreterBorrowsCore.lookup_shared_value ctx.fun_decl.meta ectx bid in translate sv | VReservedMutBorrow bid -> (* Same as for shared borrows. However, note that we use reserved borrows * only in *meta-data*: a value *actually used* in the translation can't come * from an unpromoted reserved borrow *) - let sv = InterpreterBorrowsCore.lookup_shared_value meta ectx bid in + let sv = InterpreterBorrowsCore.lookup_shared_value ctx.fun_decl.meta ectx bid in translate sv | VMutBorrow (_, v) -> (* Borrows are the identity in the extraction *) translate v) - | VSymbolic sv -> symbolic_value_to_texpression meta ctx sv + | VSymbolic sv -> symbolic_value_to_texpression ctx sv in (* Debugging *) log#ldebug @@ -1585,7 +1588,7 @@ let rec typed_value_to_texpression (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.e ^ "\n- translated expression:\n" ^ texpression_to_string ctx value)); (* Sanity check *) - type_check_texpression meta ctx value; + type_check_texpression ctx value; (* Return *) value @@ -1604,9 +1607,9 @@ let rec typed_value_to_texpression (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.e ^^ ]} *) -let rec typed_avalue_to_consumed (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.eval_ctx) +let rec typed_avalue_to_consumed (ctx : bs_ctx) (ectx : C.eval_ctx) (av : V.typed_avalue) : texpression option = - let translate = typed_avalue_to_consumed meta ctx ectx in + let translate = typed_avalue_to_consumed ctx ectx in let value = match av.value with | AAdt adt_v -> ( @@ -1616,7 +1619,7 @@ let rec typed_avalue_to_consumed (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.eva let adt_id, _ = TypesUtils.ty_as_adt av.ty in match adt_id with | TAdtId _ | TAssumed (TBox | TArray | TSlice | TStr) -> - assert (field_values = []); + cassert (field_values = []) ctx.fun_decl.meta "Only tuples can currently contain borrows"; None | TTuple -> (* Return *) @@ -1624,29 +1627,29 @@ let rec typed_avalue_to_consumed (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.eva else (* Note that if there is exactly one field value, * [mk_simpl_tuple_rvalue] is the identity *) - let rv = mk_simpl_tuple_texpression field_values in + let rv = mk_simpl_tuple_texpression ctx.fun_decl.meta field_values in Some rv) - | ABottom -> craise meta "Unreachable" - | ALoan lc -> aloan_content_to_consumed meta ctx ectx lc - | ABorrow bc -> aborrow_content_to_consumed meta ctx bc - | ASymbolic aproj -> aproj_to_consumed meta ctx aproj + | ABottom -> craise ctx.fun_decl.meta "Unreachable" + | ALoan lc -> aloan_content_to_consumed ctx ectx lc + | ABorrow bc -> aborrow_content_to_consumed ctx bc + | ASymbolic aproj -> aproj_to_consumed ctx aproj | AIgnored -> None in (* Sanity check - Rk.: we do this at every recursive call, which is a bit * expansive... *) (match value with | None -> () - | Some value -> type_check_texpression meta ctx value); + | Some value -> type_check_texpression ctx value); (* Return *) value -and aloan_content_to_consumed (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.eval_ctx) +and aloan_content_to_consumed (ctx : bs_ctx) (ectx : C.eval_ctx) (lc : V.aloan_content) : texpression option = match lc with - | AMutLoan (_, _) | ASharedLoan (_, _, _) -> craise meta "Unreachable" + | AMutLoan (_, _) | ASharedLoan (_, _, _) -> craise ctx.fun_decl.meta "Unreachable" | AEndedMutLoan { child = _; given_back = _; given_back_meta } -> (* Return the meta-value *) - Some (typed_value_to_texpression meta ctx ectx given_back_meta) + Some (typed_value_to_texpression ctx ectx given_back_meta) | AEndedSharedLoan (_, _) -> (* We don't dive into shared loans: there is nothing to give back * inside (note that there could be a mutable borrow in the shared @@ -1655,7 +1658,7 @@ and aloan_content_to_consumed (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.eval_c None | AIgnoredMutLoan (_, _) -> (* There can be *inner* not ended mutable loans, but not outer ones *) - craise meta "Unreachable" + craise ctx.fun_decl.meta "Unreachable" | AEndedIgnoredMutLoan _ -> (* This happens with nested borrows: we need to dive in *) raise Unimplemented @@ -1663,11 +1666,11 @@ and aloan_content_to_consumed (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.eval_c (* Ignore *) None -and aborrow_content_to_consumed (meta : Meta.meta) (_ctx : bs_ctx) (bc : V.aborrow_content) : +and aborrow_content_to_consumed (_ctx : bs_ctx) (bc : V.aborrow_content) : texpression option = match bc with | V.AMutBorrow (_, _) | ASharedBorrow _ | AIgnoredMutBorrow (_, _) -> - craise meta "Unreachable" + craise _ctx.fun_decl.meta "Unreachable" | AEndedMutBorrow (_, _) -> (* We collect consumed values: ignore *) None @@ -1678,31 +1681,31 @@ and aborrow_content_to_consumed (meta : Meta.meta) (_ctx : bs_ctx) (bc : V.aborr (* Ignore *) None -and aproj_to_consumed (meta : Meta.meta) (ctx : bs_ctx) (aproj : V.aproj) : texpression option = +and aproj_to_consumed (ctx : bs_ctx) (aproj : V.aproj) : texpression option = match aproj with | V.AEndedProjLoans (msv, []) -> (* The symbolic value was left unchanged *) - Some (symbolic_value_to_texpression meta ctx msv) + Some (symbolic_value_to_texpression ctx msv) | V.AEndedProjLoans (_, [ (mnv, child_aproj) ]) -> - assert (child_aproj = AIgnoredProjBorrows); + cassert (child_aproj = AIgnoredProjBorrows) ctx.fun_decl.meta "TODO: error message"; (* The symbolic value was updated *) - Some (symbolic_value_to_texpression meta ctx mnv) + Some (symbolic_value_to_texpression ctx mnv) | V.AEndedProjLoans (_, _) -> (* The symbolic value was updated, and the given back values come from sevearl * abstractions *) raise Unimplemented | AEndedProjBorrows _ -> (* We consider consumed values *) None | AIgnoredProjBorrows | AProjLoans (_, _) | AProjBorrows (_, _) -> - craise meta "Unreachable" + craise ctx.fun_decl.meta "Unreachable" (** Convert the abstraction values in an abstraction to consumed values. See [typed_avalue_to_consumed]. *) -let abs_to_consumed (meta : Meta.meta) (ctx : bs_ctx) (ectx : C.eval_ctx) (abs : V.abs) : +let abs_to_consumed (ctx : bs_ctx) (ectx : C.eval_ctx) (abs : V.abs) : texpression list = log#ldebug (lazy ("abs_to_consumed:\n" ^ abs_to_string ctx abs)); - List.filter_map (typed_avalue_to_consumed meta ctx ectx) abs.avalues + List.filter_map (typed_avalue_to_consumed ctx ectx) abs.avalues let translate_mprojection_elem (pe : E.projection_elem) : mprojection_elem option = @@ -1737,7 +1740,7 @@ let translate_opt_mplace (p : S.mplace option) : mplace option = [mp]: it is possible to provide some meta-place information, to guide the heuristics which later find pretty names for the variables. *) -let rec typed_avalue_to_given_back (meta : Meta.meta) (mp : mplace option) (av : V.typed_avalue) +let rec typed_avalue_to_given_back (mp : mplace option) (av : V.typed_avalue) (ctx : bs_ctx) : bs_ctx * typed_pattern option = let ctx, value = match av.value with @@ -1749,7 +1752,7 @@ let rec typed_avalue_to_given_back (meta : Meta.meta) (mp : mplace option) (av : let mp = None in let ctx, field_values = List.fold_left_map - (fun ctx fv -> typed_avalue_to_given_back meta mp fv ctx) + (fun ctx fv -> typed_avalue_to_given_back mp fv ctx) ctx adt_v.field_values in let field_values = List.filter_map (fun x -> x) field_values in @@ -1759,41 +1762,41 @@ let rec typed_avalue_to_given_back (meta : Meta.meta) (mp : mplace option) (av : let adt_id, _ = TypesUtils.ty_as_adt av.ty in match adt_id with | TAdtId _ | TAssumed (TBox | TArray | TSlice | TStr) -> - assert (field_values = []); + cassert (field_values = []) ctx.fun_decl.meta "Only tuples can currently contain borrows"; (ctx, None) | TTuple -> (* Return *) let variant_id = adt_v.variant_id in - assert (variant_id = None); + cassert (variant_id = None) ctx.fun_decl.meta "TODO: error message"; if field_values = [] then (ctx, None) else (* Note that if there is exactly one field value, [mk_simpl_tuple_pattern] * is the identity *) let lv = mk_simpl_tuple_pattern field_values in (ctx, Some lv)) - | ABottom -> craise meta "Unreachable" - | ALoan lc -> aloan_content_to_given_back meta mp lc ctx - | ABorrow bc -> aborrow_content_to_given_back meta mp bc ctx - | ASymbolic aproj -> aproj_to_given_back meta mp aproj ctx + | ABottom -> craise ctx.fun_decl.meta "Unreachable" + | ALoan lc -> aloan_content_to_given_back mp lc ctx + | ABorrow bc -> aborrow_content_to_given_back mp bc ctx + | ASymbolic aproj -> aproj_to_given_back mp aproj ctx | AIgnored -> (ctx, None) in (* Sanity check - Rk.: we do this at every recursive call, which is a bit * expansive... *) - (match value with None -> () | Some value -> type_check_pattern meta ctx value); + (match value with None -> () | Some value -> type_check_pattern ctx value); (* Return *) (ctx, value) -and aloan_content_to_given_back (meta : Meta.meta) (_mp : mplace option) (lc : V.aloan_content) +and aloan_content_to_given_back (_mp : mplace option) (lc : V.aloan_content) (ctx : bs_ctx) : bs_ctx * typed_pattern option = match lc with - | AMutLoan (_, _) | ASharedLoan (_, _, _) -> craise meta "Unreachable" + | AMutLoan (_, _) | ASharedLoan (_, _, _) -> craise ctx.fun_decl.meta "Unreachable" | AEndedMutLoan { child = _; given_back = _; given_back_meta = _ } | AEndedSharedLoan (_, _) -> (* We consider given back values, and thus ignore those *) (ctx, None) | AIgnoredMutLoan (_, _) -> (* There can be *inner* not ended mutable loans, but not outer ones *) - craise meta "Unreachable" + craise ctx.fun_decl.meta "Unreachable" | AEndedIgnoredMutLoan _ -> (* This happens with nested borrows: we need to dive in *) raise Unimplemented @@ -1801,14 +1804,14 @@ and aloan_content_to_given_back (meta : Meta.meta) (_mp : mplace option) (lc : V (* Ignore *) (ctx, None) -and aborrow_content_to_given_back (meta : Meta.meta) (mp : mplace option) (bc : V.aborrow_content) +and aborrow_content_to_given_back (mp : mplace option) (bc : V.aborrow_content) (ctx : bs_ctx) : bs_ctx * typed_pattern option = match bc with | V.AMutBorrow (_, _) | ASharedBorrow _ | AIgnoredMutBorrow (_, _) -> - craise meta "Unreachable" + craise ctx.fun_decl.meta "Unreachable" | AEndedMutBorrow (msv, _) -> (* Return the meta-symbolic-value *) - let ctx, var = fresh_var_for_symbolic_value meta msv ctx in + let ctx, var = fresh_var_for_symbolic_value msv ctx in (ctx, Some (mk_typed_pattern_from_var var mp)) | AEndedIgnoredMutBorrow _ -> (* This happens with nested borrows: we need to dive in *) @@ -1817,29 +1820,29 @@ and aborrow_content_to_given_back (meta : Meta.meta) (mp : mplace option) (bc : (* Ignore *) (ctx, None) -and aproj_to_given_back (meta : Meta.meta) (mp : mplace option) (aproj : V.aproj) (ctx : bs_ctx) : +and aproj_to_given_back (mp : mplace option) (aproj : V.aproj) (ctx : bs_ctx) : bs_ctx * typed_pattern option = match aproj with | V.AEndedProjLoans (_, child_projs) -> (* There may be children borrow projections in case of nested borrows, * in which case we need to dive in - we disallow nested borrows for now *) - assert ( + cassert ( List.for_all (fun (_, aproj) -> aproj = V.AIgnoredProjBorrows) - child_projs); + child_projs) ctx.fun_decl.meta "Nested borrows are not supported yet"; (ctx, None) | AEndedProjBorrows mv -> (* Return the meta-value *) - let ctx, var = fresh_var_for_symbolic_value meta mv ctx in + let ctx, var = fresh_var_for_symbolic_value mv ctx in (ctx, Some (mk_typed_pattern_from_var var mp)) | AIgnoredProjBorrows | AProjLoans (_, _) | AProjBorrows (_, _) -> - craise meta "Unreachable" + craise ctx.fun_decl.meta "Unreachable" (** Convert the abstraction values in an abstraction to given back values. See [typed_avalue_to_given_back]. *) -let abs_to_given_back (meta : Meta.meta) (mpl : mplace option list option) (abs : V.abs) +let abs_to_given_back (mpl : mplace option list option) (abs : V.abs) (ctx : bs_ctx) : bs_ctx * typed_pattern list = let avalues = match mpl with @@ -1848,17 +1851,17 @@ let abs_to_given_back (meta : Meta.meta) (mpl : mplace option list option) (abs in let ctx, values = List.fold_left_map - (fun ctx (mp, av) -> typed_avalue_to_given_back meta mp av ctx) + (fun ctx (mp, av) -> typed_avalue_to_given_back mp av ctx) ctx avalues in let values = List.filter_map (fun x -> x) values in (ctx, values) (** Simply calls [abs_to_given_back] *) -let abs_to_given_back_no_mp (meta : Meta.meta) (abs : V.abs) (ctx : bs_ctx) : +let abs_to_given_back_no_mp (abs : V.abs) (ctx : bs_ctx) : bs_ctx * typed_pattern list = let mpl = List.map (fun _ -> None) abs.avalues in - abs_to_given_back meta (Some mpl) abs ctx + abs_to_given_back (Some mpl) abs ctx (** Return the ordered list of the (transitive) parents of a given abstraction. @@ -1917,32 +1920,32 @@ let eval_ctx_to_symbolic_assignments_info (ctx : bs_ctx) (* Return the computed information *) !info -let rec translate_expression (metadata : Meta.meta) (e : S.expression) (ctx : bs_ctx) : texpression = +let rec translate_expression (e : S.expression) (ctx : bs_ctx) : texpression = match e with | S.Return (ectx, opt_v) -> (* We reached a return. Remark: we can't get there if we are inside a loop. *) - translate_return metadata ectx opt_v ctx + translate_return ectx opt_v ctx | ReturnWithLoop (loop_id, is_continue) -> (* We reached a return and are inside a loop. *) translate_return_with_loop loop_id is_continue ctx | Panic -> translate_panic ctx - | FunCall (call, e) -> translate_function_call metadata call e ctx - | EndAbstraction (ectx, abs, e) -> translate_end_abstraction metadata ectx abs e ctx + | FunCall (call, e) -> translate_function_call call e ctx + | EndAbstraction (ectx, abs, e) -> translate_end_abstraction ectx abs e ctx | EvalGlobal (gid, generics, sv, e) -> - translate_global_eval metadata gid generics sv e ctx - | Assertion (ectx, v, e) -> translate_assertion metadata ectx v e ctx - | Expansion (p, sv, exp) -> translate_expansion metadata p sv exp ctx + translate_global_eval gid generics sv e ctx + | Assertion (ectx, v, e) -> translate_assertion ectx v e ctx + | Expansion (p, sv, exp) -> translate_expansion p sv exp ctx | IntroSymbolic (ectx, p, sv, v, e) -> - translate_intro_symbolic metadata ectx p sv v e ctx - | Meta (meta, e) -> translate_emeta metadata meta e ctx + translate_intro_symbolic ectx p sv v e ctx + | Meta (meta, e) -> translate_emeta meta e ctx | ForwardEnd (ectx, loop_input_values, e, back_e) -> (* Translate the end of a function, or the end of a loop. The case where we (re-)enter a loop is handled here. *) - translate_forward_end metadata ectx loop_input_values e back_e ctx - | Loop loop -> translate_loop metadata loop ctx + translate_forward_end ectx loop_input_values e back_e ctx + | Loop loop -> translate_loop loop ctx and translate_panic (ctx : bs_ctx) : texpression = (* Here we use the function return type - note that it is ok because @@ -1957,10 +1960,10 @@ and translate_panic (ctx : bs_ctx) : texpression = (* Create the [Fail] value *) let ret_ty = mk_simpl_tuple_ty [ mk_state_ty; output_ty ] in let ret_v = - mk_result_fail_texpression_with_error_id error_failure_id ret_ty + mk_result_fail_texpression_with_error_id ctx.fun_decl.meta error_failure_id ret_ty in ret_v - else mk_result_fail_texpression_with_error_id error_failure_id output_ty + else mk_result_fail_texpression_with_error_id ctx.fun_decl.meta error_failure_id output_ty in if ctx.inside_loop && Option.is_some ctx.bid then (* We are synthesizing the backward function of a loop body *) @@ -1998,7 +2001,7 @@ and translate_panic (ctx : bs_ctx) : texpression = Remark: in case we merge the forward/backward functions, we introduce those in [translate_forward_end]. *) -and translate_return (meta : Meta.meta) (ectx : C.eval_ctx) (opt_v : V.typed_value option) +and translate_return (ectx : C.eval_ctx) (opt_v : V.typed_value option) (ctx : bs_ctx) : texpression = (* There are two cases: - either we reach the return of a forward function or a forward loop body, @@ -2012,16 +2015,16 @@ and translate_return (meta : Meta.meta) (ectx : C.eval_ctx) (opt_v : V.typed_val | None -> (* Forward function *) let v = Option.get opt_v in - typed_value_to_texpression meta ctx ectx v + typed_value_to_texpression ctx ectx v | Some _ -> (* Backward function *) (* Sanity check *) - assert (opt_v = None); + cassert (opt_v = None) ctx.fun_decl.meta "TODO: Error message"; (* Group the variables in which we stored the values we need to give back. See the explanations for the [SynthInput] case in [translate_end_abstraction] *) let backward_outputs = Option.get ctx.backward_outputs in let field_values = List.map mk_texpression_from_var backward_outputs in - mk_simpl_tuple_texpression field_values + mk_simpl_tuple_texpression ctx.fun_decl.meta field_values in (* We may need to return a state * - error-monad: Return x @@ -2031,17 +2034,17 @@ and translate_return (meta : Meta.meta) (ectx : C.eval_ctx) (opt_v : V.typed_val let output = if effect_info.stateful then let state_rvalue = mk_state_texpression ctx.state_var in - mk_simpl_tuple_texpression [ state_rvalue; output ] + mk_simpl_tuple_texpression ctx.fun_decl.meta [ state_rvalue; output ] else output in (* Wrap in a result - TODO: check effect_info.can_fail to not always wrap *) - mk_result_return_texpression output + mk_result_return_texpression ctx.fun_decl.meta output and translate_return_with_loop (loop_id : V.LoopId.id) (is_continue : bool) (ctx : bs_ctx) : texpression = - assert (is_continue = ctx.inside_loop); + cassert (is_continue = ctx.inside_loop) ctx.fun_decl.meta "TODO: error message"; let loop_id = V.LoopId.Map.find loop_id ctx.loop_ids_map in - assert (loop_id = Option.get ctx.loop_id); + cassert (loop_id = Option.get ctx.loop_id) ctx.fun_decl.meta "TODO: error message"; (* Lookup the loop information *) let loop_id = Option.get ctx.loop_id in @@ -2065,7 +2068,7 @@ and translate_return_with_loop (loop_id : V.LoopId.id) (is_continue : bool) match ctx.backward_outputs with Some outputs -> outputs | None -> [] in let field_values = List.map mk_texpression_from_var backward_outputs in - mk_simpl_tuple_texpression field_values + mk_simpl_tuple_texpression ctx.fun_decl.meta field_values in (* We may need to return a state @@ -2079,13 +2082,13 @@ and translate_return_with_loop (loop_id : V.LoopId.id) (is_continue : bool) let output = if effect_info.stateful then let state_rvalue = mk_state_texpression ctx.state_var in - mk_simpl_tuple_texpression [ state_rvalue; output ] + mk_simpl_tuple_texpression ctx.fun_decl.meta [ state_rvalue; output ] else output in (* Wrap in a result - TODO: check effect_info.can_fail to not always wrap *) - mk_emeta (Tag "return_with_loop") (mk_result_return_texpression output) + mk_emeta (Tag "return_with_loop") (mk_result_return_texpression ctx.fun_decl.meta output) -and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression) (ctx : bs_ctx) : +and translate_function_call (call : S.call) (e : S.expression) (ctx : bs_ctx) : texpression = log#ldebug (lazy @@ -2094,9 +2097,9 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression ^ "\n\n- call.generics:\n" ^ ctx_generic_args_to_string ctx call.generics)); (* Translate the function call *) - let generics = ctx_translate_fwd_generic_args meta ctx call.generics in + let generics = ctx_translate_fwd_generic_args ctx call.generics in let args = - let args = List.map (typed_value_to_texpression meta ctx call.ctx) call.args in + let args = List.map (typed_value_to_texpression ctx call.ctx) call.args in let args_mplaces = List.map translate_opt_mplace call.args_places in List.map (fun (arg, mp) -> mk_opt_mplace_texpression mp arg) @@ -2109,11 +2112,11 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression match call.call_id with | S.Fun (fid, call_id) -> (* Regular function call *) - let fid_t = translate_fun_id_or_trait_method_ref meta ctx fid in + let fid_t = translate_fun_id_or_trait_method_ref ctx fid in let func = Fun (FromLlbc (fid_t, None)) in (* Retrieve the effect information about this function (can fail, * takes a state as input, etc.) *) - let effect_info = get_fun_effect_info meta ctx fid None None in + let effect_info = get_fun_effect_info ctx fid None None in (* Depending on the function effects: - add the fuel - add the state input argument @@ -2134,7 +2137,7 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression let sg = Option.get call.sg in let decls_ctx = ctx.decls_ctx in let dsg = - translate_fun_sig_with_regions_hierarchy_to_decomposed meta decls_ctx fid + translate_fun_sig_with_regions_hierarchy_to_decomposed ctx.fun_decl.meta decls_ctx fid call.regions_hierarchy sg (List.map (fun _ -> None) sg.inputs) in @@ -2145,10 +2148,10 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression | None -> (UnknownTrait __FUNCTION__, generics) | Some (all_generics, tr_self) -> let all_generics = - ctx_translate_fwd_generic_args meta ctx all_generics + ctx_translate_fwd_generic_args ctx all_generics in let tr_self = - translate_fwd_trait_instance_id meta ctx.type_ctx.type_infos + translate_fwd_trait_instance_id ctx.fun_decl.meta ctx.type_ctx.type_infos tr_self in (tr_self, all_generics) @@ -2180,7 +2183,7 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression | PeIdent (s, _) -> s | PeImpl _ -> (* We shouldn't get there *) - craise meta "Unexpected") + craise decl.meta "Unexpected") in name ^ "_back" in @@ -2226,7 +2229,7 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression (ctx, dsg.fwd_info.ignore_output, Some back_funs_map, back_funs) in (* Compute the pattern for the destination *) - let ctx, dest = fresh_var_for_symbolic_value meta call.dest ctx in + let ctx, dest = fresh_var_for_symbolic_value call.dest ctx in let dest = mk_typed_pattern_from_var dest dest_mplace in let dest = (* Here there is something subtle: as we might ignore the output @@ -2263,13 +2266,13 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression is_rec = false; } in - let ctx, dest = fresh_var_for_symbolic_value meta call.dest ctx in + let ctx, dest = fresh_var_for_symbolic_value call.dest ctx in let dest = mk_typed_pattern_from_var dest dest_mplace in (ctx, Unop Not, effect_info, args, dest) | S.Unop E.Neg -> ( match args with | [ arg ] -> - let int_ty = ty_as_integer arg.ty in + let int_ty = ty_as_integer ctx.fun_decl.meta arg.ty in (* Note that negation can lead to an overflow and thus fail (it * is thus monadic) *) let effect_info = @@ -2281,10 +2284,10 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression is_rec = false; } in - let ctx, dest = fresh_var_for_symbolic_value meta call.dest ctx in + let ctx, dest = fresh_var_for_symbolic_value call.dest ctx in let dest = mk_typed_pattern_from_var dest dest_mplace in (ctx, Unop (Neg int_ty), effect_info, args, dest) - | _ -> craise meta "Unreachable") + | _ -> craise ctx.fun_decl.meta "Unreachable") | S.Unop (E.Cast cast_kind) -> ( match cast_kind with | CastScalar (src_ty, tgt_ty) -> @@ -2298,19 +2301,19 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression is_rec = false; } in - let ctx, dest = fresh_var_for_symbolic_value meta call.dest ctx in + let ctx, dest = fresh_var_for_symbolic_value call.dest ctx in let dest = mk_typed_pattern_from_var dest dest_mplace in (ctx, Unop (Cast (src_ty, tgt_ty)), effect_info, args, dest) - | CastFnPtr _ -> craise meta "TODO: function casts") + | CastFnPtr _ -> craise ctx.fun_decl.meta "TODO: function casts") | S.Binop binop -> ( match args with | [ arg0; arg1 ] -> - let int_ty0 = ty_as_integer arg0.ty in - let int_ty1 = ty_as_integer arg1.ty in + let int_ty0 = ty_as_integer ctx.fun_decl.meta arg0.ty in + let int_ty1 = ty_as_integer ctx.fun_decl.meta arg1.ty in (match binop with (* The Rust compiler accepts bitshifts for any integer type combination for ty0, ty1 *) | E.Shl | E.Shr -> () - | _ -> assert (int_ty0 = int_ty1)); + | _ -> cassert (int_ty0 = int_ty1) ctx.fun_decl.meta "TODO: error message"); let effect_info = { can_fail = ExpressionsUtils.binop_can_fail binop; @@ -2320,10 +2323,10 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression is_rec = false; } in - let ctx, dest = fresh_var_for_symbolic_value meta call.dest ctx in + let ctx, dest = fresh_var_for_symbolic_value call.dest ctx in let dest = mk_typed_pattern_from_var dest dest_mplace in (ctx, Binop (binop, int_ty0), effect_info, args, dest) - | _ -> craise meta "Unreachable") + | _ -> craise ctx.fun_decl.meta "Unreachable") in let func = { id = FunOrOp fun_id; generics } in let input_tys = (List.map (fun (x : texpression) -> x.ty)) args in @@ -2332,13 +2335,13 @@ and translate_function_call (meta : Meta.meta) (call : S.call) (e : S.expression in let func_ty = mk_arrows input_tys ret_ty in let func = { e = Qualif func; ty = func_ty } in - let call = mk_apps func args in + let call = mk_apps ctx.fun_decl.meta func args in (* Translate the next expression *) - let next_e = translate_expression meta e ctx in + let next_e = translate_expression e ctx in (* Put together *) mk_let effect_info.can_fail dest_v call next_e -and translate_end_abstraction (meta : Meta.meta) (ectx : C.eval_ctx) (abs : V.abs) +and translate_end_abstraction (ectx : C.eval_ctx) (abs : V.abs) (e : S.expression) (ctx : bs_ctx) : texpression = log#ldebug (lazy @@ -2346,15 +2349,15 @@ and translate_end_abstraction (meta : Meta.meta) (ectx : C.eval_ctx) (abs : V.ab ^ V.show_abs_kind abs.kind)); match abs.kind with | V.SynthInput rg_id -> - translate_end_abstraction_synth_input meta ectx abs e ctx rg_id + translate_end_abstraction_synth_input ectx abs e ctx rg_id | V.FunCall (call_id, rg_id) -> - translate_end_abstraction_fun_call meta ectx abs e ctx call_id rg_id - | V.SynthRet rg_id -> translate_end_abstraction_synth_ret meta ectx abs e ctx rg_id + translate_end_abstraction_fun_call ectx abs e ctx call_id rg_id + | V.SynthRet rg_id -> translate_end_abstraction_synth_ret ectx abs e ctx rg_id | V.Loop (loop_id, rg_id, abs_kind) -> - translate_end_abstraction_loop meta ectx abs e ctx loop_id rg_id abs_kind - | V.Identity -> translate_end_abstraction_identity meta ectx abs e ctx + translate_end_abstraction_loop ectx abs e ctx loop_id rg_id abs_kind + | V.Identity -> translate_end_abstraction_identity ectx abs e ctx -and translate_end_abstraction_synth_input (meta : Meta.meta) (ectx : C.eval_ctx) (abs : V.abs) +and translate_end_abstraction_synth_input (ectx : C.eval_ctx) (abs : V.abs) (e : S.expression) (ctx : bs_ctx) (rg_id : T.RegionGroupId.id) : texpression = log#ldebug @@ -2365,7 +2368,7 @@ and translate_end_abstraction_synth_input (meta : Meta.meta) (ectx : C.eval_ctx) ^ T.RegionGroupId.to_string rg_id ^ "\n- loop_id: " ^ Print.option_to_string Pure.LoopId.to_string ctx.loop_id - ^ "\n- eval_ctx:\n" ^ eval_ctx_to_string ectx ^ "\n- abs:\n" + ^ "\n- eval_ctx:\n" ^ eval_ctx_to_string ctx.fun_decl.meta ectx ^ "\n- abs:\n" ^ abs_to_string ctx abs ^ "\n")); (* When we end an input abstraction, this input abstraction gets back @@ -2379,7 +2382,7 @@ and translate_end_abstraction_synth_input (meta : Meta.meta) (ectx : C.eval_ctx) for a parent backward function. *) let bid = Option.get ctx.bid in - assert (rg_id = bid); + cassert (rg_id = bid) ctx.fun_decl.meta "TODO: error message"; (* First, introduce the given back variables. @@ -2404,7 +2407,7 @@ and translate_end_abstraction_synth_input (meta : Meta.meta) (ectx : C.eval_ctx) in (* Get the list of values consumed by the abstraction upon ending *) - let consumed_values = abs_to_consumed meta ctx ectx abs in + let consumed_values = abs_to_consumed ctx ectx abs in log#ldebug (lazy @@ -2426,10 +2429,10 @@ and translate_end_abstraction_synth_input (meta : Meta.meta) (ectx : C.eval_ctx) (* TODO: normalize the types *) if !Config.type_check_pure_code then List.iter - (fun (var, v) -> assert ((var : var).ty = (v : texpression).ty)) + (fun (var, v) -> cassert ((var : var).ty = (v : texpression).ty) ctx.fun_decl.meta "TODO: error message") variables_values; (* Translate the next expression *) - let next_e = translate_expression meta e ctx in + let next_e = translate_expression e ctx in (* Generate the assignemnts *) let monadic = false in List.fold_right @@ -2437,7 +2440,7 @@ and translate_end_abstraction_synth_input (meta : Meta.meta) (ectx : C.eval_ctx) mk_let monadic (mk_typed_pattern_from_var var None) value e) variables_values next_e -and translate_end_abstraction_fun_call (meta : Meta.meta) (ectx : C.eval_ctx) (abs : V.abs) +and translate_end_abstraction_fun_call (ectx : C.eval_ctx) (abs : V.abs) (e : S.expression) (ctx : bs_ctx) (call_id : V.FunCallId.id) (rg_id : T.RegionGroupId.id) : texpression = let call_info = V.FunCallId.Map.find call_id ctx.calls in @@ -2447,12 +2450,12 @@ and translate_end_abstraction_fun_call (meta : Meta.meta) (ectx : C.eval_ctx) (a | S.Fun (fun_id, _) -> fun_id | Unop _ | Binop _ -> (* Those don't have backward functions *) - craise meta "Unreachable" + craise ctx.fun_decl.meta "Unreachable" in let effect_info = get_fun_effect_info ctx fun_id None (Some rg_id) in (* Retrieve the values consumed upon ending the loans inside this * abstraction: those give us the remaining input values *) - let back_inputs = abs_to_consumed meta ctx ectx abs in + let back_inputs = abs_to_consumed ctx ectx abs in (* If the function is stateful: * - add the state input argument * - generate a fresh state variable for the returned state @@ -2472,7 +2475,7 @@ and translate_end_abstraction_fun_call (meta : Meta.meta) (ectx : C.eval_ctx) (a let output_mpl = List.append (List.map translate_opt_mplace call.args_places) [ None ] in - let ctx, outputs = abs_to_given_back meta (Some output_mpl) abs ctx in + let ctx, outputs = abs_to_given_back (Some output_mpl) abs ctx in (* Group the output values together: first the updated inputs *) let output = mk_simpl_tuple_pattern outputs in (* Add the returned state if the function is stateful *) @@ -2484,10 +2487,10 @@ and translate_end_abstraction_fun_call (meta : Meta.meta) (ectx : C.eval_ctx) (a (* Retrieve the function id, and register the function call in the context if necessary.Arith_status *) let ctx, func = - bs_ctx_register_backward_call meta abs call_id rg_id back_inputs ctx + bs_ctx_register_backward_call abs call_id rg_id back_inputs ctx in (* Translate the next expression *) - let next_e = translate_expression meta e ctx in + let next_e = translate_expression e ctx in (* Put everything together *) let inputs = back_inputs in let args_mplaces = List.map (fun _ -> None) inputs in @@ -2512,21 +2515,21 @@ and translate_end_abstraction_fun_call (meta : Meta.meta) (ectx : C.eval_ctx) (a let call = mk_apps func args in mk_let effect_info.can_fail output call next_e -and translate_end_abstraction_identity (meta : Meta.meta) (ectx : C.eval_ctx) (abs : V.abs) +and translate_end_abstraction_identity (ectx : C.eval_ctx) (abs : V.abs) (e : S.expression) (ctx : bs_ctx) : texpression = (* We simply check that the abstraction only contains shared borrows/loans, and translate the next expression *) (* We can do this simply by checking that it consumes and gives back nothing *) - let inputs = abs_to_consumed meta ctx ectx abs in - let ctx, outputs = abs_to_given_back meta None abs ctx in - assert (inputs = []); - assert (outputs = []); + let inputs = abs_to_consumed ctx ectx abs in + let ctx, outputs = abs_to_given_back None abs ctx in + cassert (inputs = []) ctx.fun_decl.meta "TODO: error message"; + cassert (outputs = []) ctx.fun_decl.meta "TODO: error message"; (* Translate the next expression *) - translate_expression meta e ctx + translate_expression e ctx -and translate_end_abstraction_synth_ret (meta : Meta.meta) (ectx : C.eval_ctx) (abs : V.abs) +and translate_end_abstraction_synth_ret (ectx : C.eval_ctx) (abs : V.abs) (e : S.expression) (ctx : bs_ctx) (rg_id : T.RegionGroupId.id) : texpression = (* If we end the abstraction which consumed the return value of the function @@ -2562,13 +2565,13 @@ and translate_end_abstraction_synth_ret (meta : Meta.meta) (ectx : C.eval_ctx) ( let inputs = T.RegionGroupId.Map.find rg_id ctx.backward_inputs_no_state in (* Retrieve the values consumed upon ending the loans inside this * abstraction: as there are no nested borrows, there should be none. *) - let consumed = abs_to_consumed meta ctx ectx abs in - assert (consumed = []); + let consumed = abs_to_consumed ctx ectx abs in + cassert (consumed = []) ctx.fun_decl.meta "Nested borrows are not supported yet TODO: error message"; (* Retrieve the values given back upon ending this abstraction - note that * we don't provide meta-place information, because those assignments will * be inlined anyway... *) log#ldebug (lazy ("abs: " ^ abs_to_string ctx abs)); - let ctx, given_back = abs_to_given_back_no_mp meta abs ctx in + let ctx, given_back = abs_to_given_back_no_mp abs ctx in (* Link the inputs to those given back values - note that this also * checks we have the same number of values, of course *) let given_back_inputs = List.combine given_back inputs in @@ -2581,10 +2584,10 @@ and translate_end_abstraction_synth_ret (meta : Meta.meta) (ectx : C.eval_ctx) ( ^ pure_ty_to_string ctx given_back.ty ^ "\n- sig input ty: " ^ pure_ty_to_string ctx input.ty)); - assert (given_back.ty = input.ty)) + cassert (given_back.ty = input.ty) ctx.fun_decl.meta "TODO: error message") given_back_inputs; (* Translate the next expression *) - let next_e = translate_expression meta e ctx in + let next_e = translate_expression e ctx in (* Generate the assignments *) let monadic = false in List.fold_right @@ -2592,26 +2595,26 @@ and translate_end_abstraction_synth_ret (meta : Meta.meta) (ectx : C.eval_ctx) ( mk_let monadic given_back (mk_texpression_from_var input_var) e) given_back_inputs next_e -and translate_end_abstraction_loop (meta : Meta.meta) (ectx : C.eval_ctx) (abs : V.abs) +and translate_end_abstraction_loop (ectx : C.eval_ctx) (abs : V.abs) (e : S.expression) (ctx : bs_ctx) (loop_id : V.LoopId.id) (rg_id : T.RegionGroupId.id option) (abs_kind : V.loop_abs_kind) : texpression = let vloop_id = loop_id in let loop_id = V.LoopId.Map.find loop_id ctx.loop_ids_map in - assert (loop_id = Option.get ctx.loop_id); + cassert (loop_id = Option.get ctx.loop_id) ctx.fun_decl.meta "TODO: error message"; let rg_id = Option.get rg_id in (* There are two cases depending on the [abs_kind] (whether this is a synth input or a regular loop call) *) match abs_kind with | V.LoopSynthInput -> (* Actually the same case as [SynthInput] *) - translate_end_abstraction_synth_input meta ectx abs e ctx rg_id + translate_end_abstraction_synth_input ectx abs e ctx rg_id | V.LoopCall -> ( (* We need to introduce a call to the backward function corresponding to a forward call which happened earlier *) let fun_id = E.FRegular ctx.fun_decl.def_id in let effect_info = - get_fun_effect_info meta ctx (FunId fun_id) (Some vloop_id) (Some rg_id) + get_fun_effect_info ctx (FunId fun_id) (Some vloop_id) (Some rg_id) in let loop_info = LoopId.Map.find loop_id ctx.loops in (* Retrieve the additional backward inputs. Note that those are actually @@ -2637,7 +2640,7 @@ and translate_end_abstraction_loop (meta : Meta.meta) (ectx : C.eval_ctx) (abs : (* Concatenate all the inputs *) let inputs = List.concat [ back_inputs; back_state ] in (* Retrieve the values given back by this function *) - let ctx, outputs = abs_to_given_back meta None abs ctx in + let ctx, outputs = abs_to_given_back None abs ctx in (* Group the output values together: first the updated inputs *) let output = mk_simpl_tuple_pattern outputs in (* Add the returned state if the function is stateful *) @@ -2647,7 +2650,7 @@ and translate_end_abstraction_loop (meta : Meta.meta) (ectx : C.eval_ctx) (abs : | Some nstate -> mk_simpl_tuple_pattern [ nstate; output ] in (* Translate the next expression *) - let next_e = translate_expression meta e ctx in + let next_e = translate_expression e ctx in (* Put everything together *) let args_mplaces = List.map (fun _ -> None) inputs in let args = @@ -2684,7 +2687,7 @@ and translate_end_abstraction_loop (meta : Meta.meta) (ectx : C.eval_ctx) (abs : *) let next_e = if ctx.inside_loop then - let consumed_values = abs_to_consumed meta ctx ectx abs in + let consumed_values = abs_to_consumed ctx ectx abs in let var_values = List.combine outputs consumed_values in let var_values = List.filter_map @@ -2702,36 +2705,36 @@ and translate_end_abstraction_loop (meta : Meta.meta) (ectx : C.eval_ctx) (abs : (* Create the let-binding *) mk_let effect_info.can_fail output call next_e) -and translate_global_eval (meta : Meta.meta) (gid : A.GlobalDeclId.id) (generics : T.generic_args) +and translate_global_eval (gid : A.GlobalDeclId.id) (generics : T.generic_args) (sval : V.symbolic_value) (e : S.expression) (ctx : bs_ctx) : texpression = - let ctx, var = fresh_var_for_symbolic_value meta sval ctx in + let ctx, var = fresh_var_for_symbolic_value sval ctx in let decl = A.GlobalDeclId.Map.find gid ctx.global_ctx.llbc_global_decls in let generics = ctx_translate_fwd_generic_args ctx generics in let global_expr = { id = Global gid; generics } in (* We use translate_fwd_ty to translate the global type *) - let ty = ctx_translate_fwd_ty meta ctx decl.ty in + let ty = ctx_translate_fwd_ty ctx decl.ty in let gval = { e = Qualif global_expr; ty } in - let e = translate_expression meta e ctx in + let e = translate_expression e ctx in mk_let false (mk_typed_pattern_from_var var None) gval e -and translate_assertion (meta : Meta.meta) (ectx : C.eval_ctx) (v : V.typed_value) +and translate_assertion (ectx : C.eval_ctx) (v : V.typed_value) (e : S.expression) (ctx : bs_ctx) : texpression = - let next_e = translate_expression meta e ctx in + let next_e = translate_expression e ctx in let monadic = true in - let v = typed_value_to_texpression meta ctx ectx v in + let v = typed_value_to_texpression ctx ectx v in let args = [ v ] in let func = { id = FunOrOp (Fun (Pure Assert)); generics = empty_generic_args } in let func_ty = mk_arrow (TLiteral TBool) mk_unit_ty in let func = { e = Qualif func; ty = func_ty } in - let assertion = mk_apps func args in + let assertion = mk_apps ctx.fun_decl.meta func args in mk_let monadic (mk_dummy_pattern mk_unit_ty) assertion next_e -and translate_expansion (meta : Meta.meta) (p : S.mplace option) (sv : V.symbolic_value) +and translate_expansion (p : S.mplace option) (sv : V.symbolic_value) (exp : S.expansion) (ctx : bs_ctx) : texpression = (* Translate the scrutinee *) - let scrutinee = symbolic_value_to_texpression meta ctx sv in + let scrutinee = symbolic_value_to_texpression ctx sv in let scrutinee_mplace = translate_opt_mplace p in (* Translate the branches *) match exp with @@ -2740,12 +2743,12 @@ and translate_expansion (meta : Meta.meta) (p : S.mplace option) (sv : V.symboli | V.SeLiteral _ -> (* We do not *register* symbolic expansions to literal values in the symbolic ADT *) - craise meta "Unreachable" + craise ctx.fun_decl.meta "Unreachable" | SeMutRef (_, nsv) | SeSharedRef (_, nsv) -> (* The (mut/shared) borrow type is extracted to identity: we thus simply introduce an reassignment *) - let ctx, var = fresh_var_for_symbolic_value meta nsv ctx in - let next_e = translate_expression meta e ctx in + let ctx, var = fresh_var_for_symbolic_value nsv ctx in + let next_e = translate_expression e ctx in let monadic = false in mk_let monadic (mk_typed_pattern_from_var var None) @@ -2753,11 +2756,11 @@ and translate_expansion (meta : Meta.meta) (p : S.mplace option) (sv : V.symboli next_e | SeAdt _ -> (* Should be in the [ExpandAdt] case *) - craise meta "Unreachable") + craise ctx.fun_decl.meta "Unreachable") | ExpandAdt branches -> ( (* We don't do the same thing if there is a branching or not *) match branches with - | [] -> craise meta "Unreachable" + | [] -> craise ctx.fun_decl.meta "Unreachable" | [ (variant_id, svl, branch) ] when not (TypesUtils.ty_is_custom_adt sv.V.sv_ty @@ -2769,19 +2772,19 @@ and translate_expansion (meta : Meta.meta) (p : S.mplace option) (sv : V.symboli we *ignore* this branch (and go to the next one) if the ADT is a custom adt, and [always_deconstruct_adts_with_matches] is true. *) - translate_ExpandAdt_one_branch meta sv scrutinee scrutinee_mplace + translate_ExpandAdt_one_branch sv scrutinee scrutinee_mplace variant_id svl branch ctx | branches -> let translate_branch (variant_id : T.VariantId.id option) (svl : V.symbolic_value list) (branch : S.expression) : match_branch = - let ctx, vars = fresh_vars_for_symbolic_values meta svl ctx in + let ctx, vars = fresh_vars_for_symbolic_values svl ctx in let vars = List.map (fun x -> mk_typed_pattern_from_var x None) vars in let pat_ty = scrutinee.ty in let pat = mk_adt_pattern pat_ty variant_id vars in - let branch = translate_expression meta branch ctx in + let branch = translate_expression branch ctx in { pat; branch } in let branches = @@ -2796,14 +2799,14 @@ and translate_expansion (meta : Meta.meta) (p : S.mplace option) (sv : V.symboli let branch = List.hd branches in let ty = branch.branch.ty in (* Sanity check *) - assert (List.for_all (fun br -> br.branch.ty = ty) branches); + cassert (List.for_all (fun br -> br.branch.ty = ty) branches) ctx.fun_decl.meta "There should be at least one branch"; (* Return *) { e; ty }) | ExpandBool (true_e, false_e) -> (* We don't need to update the context: we don't introduce any new values/variables *) - let true_e = translate_expression meta true_e ctx in - let false_e = translate_expression meta false_e ctx in + let true_e = translate_expression true_e ctx in + let false_e = translate_expression false_e ctx in let e = Switch ( mk_opt_mplace_texpression scrutinee_mplace scrutinee, @@ -2816,19 +2819,19 @@ and translate_expansion (meta : Meta.meta) (p : S.mplace option) (sv : V.symboli ^ pure_ty_to_string ctx true_e.ty ^ "\n\nfalse_e.ty: " ^ pure_ty_to_string ctx false_e.ty)); - if !Config.fail_hard then assert (ty = false_e.ty); + if !Config.fail_hard then cassert (ty = false_e.ty) ctx.fun_decl.meta "TODO: error message"; (* TODO: remove if ? *) { e; ty } | ExpandInt (int_ty, branches, otherwise) -> let translate_branch ((v, branch_e) : V.scalar_value * S.expression) : match_branch = (* We don't need to update the context: we don't introduce any new values/variables *) - let branch = translate_expression meta branch_e ctx in + let branch = translate_expression branch_e ctx in let pat = mk_typed_pattern_from_literal (VScalar v) in { pat; branch } in let branches = List.map translate_branch branches in - let otherwise = translate_expression meta otherwise ctx in + let otherwise = translate_expression otherwise ctx in let pat_ty = TLiteral (TInteger int_ty) in let otherwise_pat : typed_pattern = { value = PatDummy; ty = pat_ty } in let otherwise : match_branch = @@ -2841,8 +2844,8 @@ and translate_expansion (meta : Meta.meta) (p : S.mplace option) (sv : V.symboli Match all_branches ) in let ty = otherwise.branch.ty in - assert ( - List.for_all (fun (br : match_branch) -> br.branch.ty = ty) branches); + cassert ( + List.for_all (fun (br : match_branch) -> br.branch.ty = ty) branches) ctx.fun_decl.meta "TODO: error message"; { e; ty } (* Translate and [ExpandAdt] when there is no branching (i.e., one branch). @@ -2868,15 +2871,15 @@ and translate_expansion (meta : Meta.meta) (p : S.mplace option) (sv : V.symboli as inductives, in which case it is not always possible to use a notation for the field projections. *) -and translate_ExpandAdt_one_branch (meta : Meta.meta) (sv : V.symbolic_value) +and translate_ExpandAdt_one_branch (sv : V.symbolic_value) (scrutinee : texpression) (scrutinee_mplace : mplace option) (variant_id : variant_id option) (svl : V.symbolic_value list) (branch : S.expression) (ctx : bs_ctx) : texpression = (* TODO: always introduce a match, and use micro-passes to turn the the match into a let? *) let type_id, _ = TypesUtils.ty_as_adt sv.V.sv_ty in - let ctx, vars = fresh_vars_for_symbolic_values meta svl ctx in - let branch = translate_expression meta branch ctx in + let ctx, vars = fresh_vars_for_symbolic_values svl ctx in + let branch = translate_expression branch ctx in match type_id with | TAdtId adt_id -> (* Detect if this is an enumeration or not *) @@ -2917,14 +2920,14 @@ and translate_ExpandAdt_one_branch (meta : Meta.meta) (sv : V.symbolic_value) * field. * We use the [dest] variable in order not to have to recompute * the type of the result of the projection... *) - let adt_id, generics = ty_as_adt scrutinee.ty in + let adt_id, generics = ty_as_adt ctx.fun_decl.meta scrutinee.ty in let gen_field_proj (field_id : FieldId.id) (dest : var) : texpression = let proj_kind = { adt_id; field_id } in let qualif = { id = Proj proj_kind; generics } in let proj_e = Qualif qualif in let proj_ty = mk_arrow scrutinee.ty dest.ty in let proj = { e = proj_e; ty = proj_ty } in - mk_app proj scrutinee + mk_app ctx.fun_decl.meta proj scrutinee in let id_var_pairs = FieldId.mapi (fun fid v -> (fid, v)) vars in let monadic = false in @@ -2943,7 +2946,7 @@ and translate_ExpandAdt_one_branch (meta : Meta.meta) (sv : V.symbolic_value) | TAssumed TBox -> (* There should be exactly one variable *) let var = - match vars with [ v ] -> v | _ -> craise meta "Unreachable" + match vars with [ v ] -> v | _ -> craise ctx.fun_decl.meta "Unreachable" in (* We simply introduce an assignment - the box type is the * identity when extracted ([box a = a]) *) @@ -2957,9 +2960,9 @@ and translate_ExpandAdt_one_branch (meta : Meta.meta) (sv : V.symbolic_value) * through the functions provided by the API (note that we don't * know how to expand values like vectors or arrays, because they have a variable number * of fields!) *) - craise meta "Attempt to expand a non-expandable value" + craise ctx.fun_decl.meta "Attempt to expand a non-expandable value" -and translate_intro_symbolic (meta : Meta.meta) (ectx : C.eval_ctx) (p : S.mplace option) +and translate_intro_symbolic (ectx : C.eval_ctx) (p : S.mplace option) (sv : V.symbolic_value) (v : S.value_aggregate) (e : S.expression) (ctx : bs_ctx) : texpression = log#ldebug @@ -2969,10 +2972,10 @@ and translate_intro_symbolic (meta : Meta.meta) (ectx : C.eval_ctx) (p : S.mplac let mplace = translate_opt_mplace p in (* Introduce a fresh variable for the symbolic value. *) - let ctx, var = fresh_var_for_symbolic_value meta sv ctx in + let ctx, var = fresh_var_for_symbolic_value sv ctx in (* Translate the next expression *) - let next_e = translate_expression meta e ctx in + let next_e = translate_expression e ctx in (* Translate the value: there are several cases, depending on whether this is a "regular" let-binding, an array aggregate, a const generic or @@ -2980,12 +2983,12 @@ and translate_intro_symbolic (meta : Meta.meta) (ectx : C.eval_ctx) (p : S.mplac *) let v = match v with - | VaSingleValue v -> typed_value_to_texpression meta ctx ectx v + | VaSingleValue v -> typed_value_to_texpression ctx ectx v | VaArray values -> (* We use a struct update to encode the array aggregate, in order to preserve the structure and allow generating code of the shape `[x0, ...., xn]` *) - let values = List.map (typed_value_to_texpression meta ctx ectx) values in + let values = List.map (typed_value_to_texpression ctx ectx) values in let values = FieldId.mapi (fun fid v -> (fid, v)) values in let su : struct_update = { struct_id = TAssumed TArray; init = None; updates = values } @@ -2994,7 +2997,7 @@ and translate_intro_symbolic (meta : Meta.meta) (ectx : C.eval_ctx) (p : S.mplac | VaCgValue cg_id -> { e = CVar cg_id; ty = var.ty } | VaTraitConstValue (trait_ref, const_name) -> let type_infos = ctx.type_ctx.type_infos in - let trait_ref = translate_fwd_trait_ref type_infos trait_ref in + let trait_ref = translate_fwd_trait_ref ctx.fun_decl.meta type_infos trait_ref in let qualif_id = TraitConst (trait_ref, const_name) in let qualif = { id = qualif_id; generics = empty_generic_args } in { e = Qualif qualif; ty = var.ty } @@ -3005,7 +3008,7 @@ and translate_intro_symbolic (meta : Meta.meta) (ectx : C.eval_ctx) (p : S.mplac let var = mk_typed_pattern_from_var var mplace in mk_let monadic var v next_e -and translate_forward_end (meta : Meta.meta) (ectx : C.eval_ctx) +and translate_forward_end (ectx : C.eval_ctx) (loop_input_values : V.typed_value S.symbolic_value_id_map option) (fwd_e : S.expression) (back_e : S.expression S.region_group_id_map) (ctx : bs_ctx) : texpression = @@ -3062,7 +3065,7 @@ and translate_forward_end (meta : Meta.meta) (ectx : C.eval_ctx) in (ctx, e, finish) in - let e = translate_expression meta e ctx in + let e = translate_expression e ctx in finish e in @@ -3135,7 +3138,7 @@ and translate_forward_end (meta : Meta.meta) (ectx : C.eval_ctx) else pure_fwd_var :: back_vars in let vars = List.map mk_texpression_from_var vars in - let ret = mk_simpl_tuple_texpression vars in + let ret = mk_simpl_tuple_texpression ctx.fun_decl.meta vars in (* Introduce a fresh input state variable for the forward expression *) let _ctx, state_var, state_pat = @@ -3146,8 +3149,8 @@ and translate_forward_end (meta : Meta.meta) (ectx : C.eval_ctx) in let state_var = List.map mk_texpression_from_var state_var in - let ret = mk_simpl_tuple_texpression (state_var @ [ ret ]) in - let ret = mk_result_return_texpression ret in + let ret = mk_simpl_tuple_texpression ctx.fun_decl.meta (state_var @ [ ret ]) in + let ret = mk_result_return_texpression ctx.fun_decl.meta ret in (* Introduce all the let-bindings *) @@ -3216,13 +3219,13 @@ and translate_forward_end (meta : Meta.meta) (ectx : C.eval_ctx) loop_info.input_svl in let args = - List.map (typed_value_to_texpression meta ctx ectx) loop_input_values + List.map (typed_value_to_texpression ctx ectx) loop_input_values in let org_args = args in (* Lookup the effect info for the loop function *) let fid = E.FRegular ctx.fun_decl.def_id in - let effect_info = get_fun_effect_info meta ctx (FunId fid) None ctx.bid in + let effect_info = get_fun_effect_info ctx (FunId fid) None ctx.bid in (* Introduce a fresh output value for the forward function *) let ctx, fwd_output, output_pat = @@ -3320,7 +3323,7 @@ and translate_forward_end (meta : Meta.meta) (ectx : C.eval_ctx) in let func_ty = mk_arrows input_tys ret_ty in let func = { e = Qualif func; ty = func_ty } in - let call = mk_apps func args in + let call = mk_apps ctx.fun_decl.meta func args in call in @@ -3342,7 +3345,7 @@ and translate_forward_end (meta : Meta.meta) (ectx : C.eval_ctx) *) mk_emeta_symbolic_assignments loop_info.input_vars org_args e -and translate_loop (meta : Meta.meta) (loop : S.loop) (ctx : bs_ctx) : texpression = +and translate_loop (loop : S.loop) (ctx : bs_ctx) : texpression = let loop_id = V.LoopId.Map.find loop.loop_id ctx.loop_ids_map in (* Translate the loop inputs - some inputs are symbolic values already @@ -3369,16 +3372,16 @@ and translate_loop (meta : Meta.meta) (loop : S.loop) (ctx : bs_ctx) : texpressi (Print.list_to_string (ty_to_string ctx)) loop.rg_to_given_back_tys ^ "\n")); - let ctx, _ = fresh_vars_for_symbolic_values meta svl ctx in + let ctx, _ = fresh_vars_for_symbolic_values svl ctx in ctx in (* Sanity check: all the non-fresh symbolic values are in the context *) - assert ( + cassert ( List.for_all (fun (sv : V.symbolic_value) -> V.SymbolicValueId.Map.mem sv.sv_id ctx.sv_to_var) - loop.input_svalues); + loop.input_svalues) ctx.fun_decl.meta "All the non-fresh symbolic values should be in the context"; (* Translate the loop inputs *) let inputs = @@ -3398,8 +3401,8 @@ and translate_loop (meta : Meta.meta) (loop : S.loop) (ctx : bs_ctx) : texpressi (* The types shouldn't contain borrows - we can translate them as forward types *) List.map (fun ty -> - assert (not (TypesUtils.ty_has_borrows !ctx.type_ctx.type_infos ty)); - ctx_translate_fwd_ty meta !ctx ty) + cassert (not (TypesUtils.ty_has_borrows !ctx.type_ctx.type_infos ty)) !ctx.fun_decl.meta "The types shouldn't contain borrows"; + ctx_translate_fwd_ty !ctx ty) tys) loop.rg_to_given_back_tys in @@ -3477,7 +3480,7 @@ and translate_loop (meta : Meta.meta) (loop : S.loop) (ctx : bs_ctx) : texpressi (* Add the loop information in the context *) let ctx = - assert (not (LoopId.Map.mem loop_id ctx.loops)); + cassert (not (LoopId.Map.mem loop_id ctx.loops)) ctx.fun_decl.meta "The loop information should not already be in the context TODO: error message"; (* Note that we will retrieve the input values later in the [ForwardEnd] (and will introduce the outputs at that moment, together with the actual @@ -3526,7 +3529,7 @@ and translate_loop (meta : Meta.meta) (loop : S.loop) (ctx : bs_ctx) : texpressi (* Update the context to translate the function end *) let ctx_end = { ctx with loop_id = Some loop_id } in - let fun_end = translate_expression meta loop.end_expr ctx_end in + let fun_end = translate_expression loop.end_expr ctx_end in (* Update the context for the loop body *) let ctx_loop = { ctx_end with inside_loop = true } in @@ -3537,7 +3540,7 @@ and translate_loop (meta : Meta.meta) (loop : S.loop) (ctx : bs_ctx) : texpressi in (* Translate the loop body *) - let loop_body = translate_expression meta loop.loop_expr ctx_loop in + let loop_body = translate_expression loop.loop_expr ctx_loop in (* Create the loop node and return *) let loop = @@ -3558,14 +3561,14 @@ and translate_loop (meta : Meta.meta) (loop : S.loop) (ctx : bs_ctx) : texpressi let ty = fun_end.ty in { e = loop; ty } -and translate_emeta (metadata : Meta.meta) (meta : S.emeta) (e : S.expression) (ctx : bs_ctx) : +and translate_emeta (meta : S.emeta) (e : S.expression) (ctx : bs_ctx) : texpression = - let next_e = translate_expression metadata e ctx in + let next_e = translate_expression e ctx in let meta = match meta with | S.Assignment (ectx, lp, rv, rp) -> let lp = translate_mplace lp in - let rv = typed_value_to_texpression metadata ctx ectx rv in + let rv = typed_value_to_texpression ctx ectx rv in let rp = translate_opt_mplace rp in Some (Assignment (lp, rv, rp)) | S.Snapshot ectx -> @@ -3586,14 +3589,14 @@ and translate_emeta (metadata : Meta.meta) (meta : S.emeta) (e : S.expression) ( | None -> next_e (** Wrap a function body in a match over the fuel to control termination. *) -let wrap_in_match_fuel (fuel0 : VarId.id) (fuel : VarId.id) (body : texpression) +let wrap_in_match_fuel (meta : Meta.meta) (fuel0 : VarId.id) (fuel : VarId.id) (body : texpression) : texpression = let fuel0_var : var = mk_fuel_var fuel0 in let fuel0 = mk_texpression_from_var fuel0_var in let nfuel_var : var = mk_fuel_var fuel in let nfuel_pat = mk_typed_pattern_from_var nfuel_var None in let fail_branch = - mk_result_fail_texpression_with_error_id error_out_of_fuel_id body.ty + mk_result_fail_texpression_with_error_id meta error_out_of_fuel_id body.ty in match !Config.backend with | FStar -> @@ -3615,7 +3618,7 @@ let wrap_in_match_fuel (fuel0 : VarId.id) (fuel : VarId.id) (body : texpression) in let func_ty = mk_arrow mk_fuel_ty mk_bool_ty in let func = { e = Qualif func; ty = func_ty } in - mk_app func fuel0 + mk_app meta func fuel0 in (* Create the expression: [decrease fuel0] *) let decrease_fuel = @@ -3627,7 +3630,7 @@ let wrap_in_match_fuel (fuel0 : VarId.id) (fuel : VarId.id) (body : texpression) in let func_ty = mk_arrow mk_fuel_ty mk_fuel_ty in let func = { e = Qualif func; ty = func_ty } in - mk_app func fuel0 + mk_app meta func fuel0 in (* Create the success branch *) @@ -3664,7 +3667,7 @@ let wrap_in_match_fuel (fuel0 : VarId.id) (fuel : VarId.id) (body : texpression) (* We should have checked the command line arguments before *) raise (Failure "Unexpected") -let translate_fun_decl (meta : Meta.meta) (ctx : bs_ctx) (body : S.expression option) : fun_decl = +let translate_fun_decl (ctx : bs_ctx) (body : S.expression option) : fun_decl = (* Translate *) let def = ctx.fun_decl in assert (ctx.bid = None); @@ -3679,24 +3682,24 @@ let translate_fun_decl (meta : Meta.meta) (ctx : bs_ctx) (body : S.expression op let llbc_name = def.name in let name = name_to_string ctx llbc_name in (* Translate the signature *) - let signature = translate_fun_sig_from_decomposed ctx.sg in + let signature = translate_fun_sig_from_decomposed def.meta ctx.sg in (* Translate the body, if there is *) let body = match body with | None -> None | Some body -> let effect_info = - get_fun_effect_info meta ctx (FunId (FRegular def_id)) None None + get_fun_effect_info ctx (FunId (FRegular def_id)) None None in - let body = translate_expression meta body ctx in + let body = translate_expression body ctx in (* Add a match over the fuel, if necessary *) let body = if function_decreases_fuel effect_info then - wrap_in_match_fuel ctx.fuel0 ctx.fuel body + wrap_in_match_fuel def.meta ctx.fuel0 ctx.fuel body else body in (* Sanity check *) - type_check_texpression meta ctx body; + type_check_texpression ctx body; (* Introduce the fuel parameter, if necessary *) let fuel = if function_uses_fuel effect_info then @@ -3733,10 +3736,10 @@ let translate_fun_decl (meta : Meta.meta) (ctx : bs_ctx) (body : S.expression op (List.map (pure_ty_to_string ctx) signature.inputs))); (* TODO: we need to normalize the types *) if !Config.type_check_pure_code then - assert ( + cassert ( List.for_all (fun (var, ty) -> (var : var).ty = ty) - (List.combine inputs signature.inputs)); + (List.combine inputs signature.inputs)) def.meta "TODO: error message"; Some { inputs; inputs_lvs; body } in @@ -3771,11 +3774,11 @@ let translate_fun_decl (meta : Meta.meta) (ctx : bs_ctx) (body : S.expression op (* return *) def -let translate_type_decls (meta : Meta.meta) (ctx : Contexts.decls_ctx) : type_decl list = - List.map (translate_type_decl meta ctx) +let translate_type_decls (ctx : Contexts.decls_ctx) : type_decl list = + List.map (translate_type_decl ctx) (TypeDeclId.Map.values ctx.type_ctx.type_decls) -let translate_trait_decl (metadata : Meta.meta) (ctx : Contexts.decls_ctx) (trait_decl : A.trait_decl) +let translate_trait_decl (ctx : Contexts.decls_ctx) (trait_decl : A.trait_decl) : trait_decl = let { def_id; @@ -3798,20 +3801,20 @@ let translate_trait_decl (metadata : Meta.meta) (ctx : Contexts.decls_ctx) (trai (Print.Contexts.decls_ctx_to_fmt_env ctx) llbc_name in - let generics = translate_generic_params metadata llbc_generics in - let preds = translate_predicates metadata preds in - let parent_clauses = List.map (translate_trait_clause metadata) llbc_parent_clauses in + let generics = translate_generic_params trait_decl.meta llbc_generics in + let preds = translate_predicates trait_decl.meta preds in + let parent_clauses = List.map (translate_trait_clause trait_decl.meta) llbc_parent_clauses in let consts = List.map - (fun (name, (ty, id)) -> (name, (translate_fwd_ty metadata type_infos ty, id))) + (fun (name, (ty, id)) -> (name, (translate_fwd_ty trait_decl.meta type_infos ty, id))) consts in let types = List.map (fun (name, (trait_clauses, ty)) -> ( name, - ( List.map (translate_trait_clause metadata) trait_clauses, - Option.map (translate_fwd_ty metadata type_infos) ty ) )) + ( List.map (translate_trait_clause trait_decl.meta) trait_clauses, + Option.map (translate_fwd_ty trait_decl.meta type_infos) ty ) )) types in { @@ -3831,7 +3834,7 @@ let translate_trait_decl (metadata : Meta.meta) (ctx : Contexts.decls_ctx) (trai provided_methods; } -let translate_trait_impl (metadata : Meta.meta) (ctx : Contexts.decls_ctx) (trait_impl : A.trait_impl) +let translate_trait_impl (ctx : Contexts.decls_ctx) (trait_impl : A.trait_impl) : trait_impl = let { A.def_id; @@ -3851,27 +3854,27 @@ let translate_trait_impl (metadata : Meta.meta) (ctx : Contexts.decls_ctx) (trai in let type_infos = ctx.type_ctx.type_infos in let impl_trait = - translate_trait_decl_ref metadata (translate_fwd_ty metadata type_infos) llbc_impl_trait + translate_trait_decl_ref trait_impl.meta (translate_fwd_ty trait_impl.meta type_infos) llbc_impl_trait in let name = Print.Types.name_to_string (Print.Contexts.decls_ctx_to_fmt_env ctx) llbc_name in - let generics = translate_generic_params metadata llbc_generics in - let preds = translate_predicates metadata preds in - let parent_trait_refs = List.map (translate_strait_ref metadata) parent_trait_refs in + let generics = translate_generic_params trait_impl.meta llbc_generics in + let preds = translate_predicates trait_impl.meta preds in + let parent_trait_refs = List.map (translate_strait_ref trait_impl.meta) parent_trait_refs in let consts = List.map - (fun (name, (ty, id)) -> (name, (translate_fwd_ty metadata type_infos ty, id))) + (fun (name, (ty, id)) -> (name, (translate_fwd_ty trait_impl.meta type_infos ty, id))) consts in let types = List.map (fun (name, (trait_refs, ty)) -> ( name, - ( List.map (translate_fwd_trait_ref metadata type_infos) trait_refs, - translate_fwd_ty metadata type_infos ty ) )) + ( List.map (translate_fwd_trait_ref trait_impl.meta type_infos) trait_refs, + translate_fwd_ty trait_impl.meta type_infos ty ) )) types in { diff --git a/compiler/Translate.ml b/compiler/Translate.ml index 43d2fbb0..2ee1324b 100644 --- a/compiler/Translate.ml +++ b/compiler/Translate.ml @@ -20,7 +20,7 @@ type symbolic_fun_translation = symbolic_value list * SA.expression (** Execute the symbolic interpreter on a function to generate a list of symbolic ASTs, for the forward function and the backward functions. *) -let translate_function_to_symbolics (meta : Meta.meta) (trans_ctx : trans_ctx) (fdef : fun_decl) : +let translate_function_to_symbolics (trans_ctx : trans_ctx) (fdef : fun_decl) : symbolic_fun_translation option = (* Debug *) log#ldebug @@ -32,7 +32,7 @@ let translate_function_to_symbolics (meta : Meta.meta) (trans_ctx : trans_ctx) ( | Some _ -> (* Evaluate *) let synthesize = true in - let inputs, symb = evaluate_function_symbolic meta synthesize trans_ctx fdef in + let inputs, symb = evaluate_function_symbolic synthesize trans_ctx fdef in Some (inputs, Option.get symb) (** Translate a function, by generating its forward and backward translations. @@ -41,7 +41,7 @@ let translate_function_to_symbolics (meta : Meta.meta) (trans_ctx : trans_ctx) ( of backward functions, we also provide names for the outputs. TODO: maybe we should introduce a record for this. *) -let translate_function_to_pure (meta : Meta.meta) (trans_ctx : trans_ctx) +let translate_function_to_pure (trans_ctx : trans_ctx) (pure_type_decls : Pure.type_decl Pure.TypeDeclId.Map.t) (fun_dsigs : Pure.decomposed_fun_sig FunDeclId.Map.t) (fdef : fun_decl) : pure_fun_translation_no_loops = @@ -50,7 +50,7 @@ let translate_function_to_pure (meta : Meta.meta) (trans_ctx : trans_ctx) (lazy ("translate_function_to_pure: " ^ name_to_string trans_ctx fdef.name)); (* Compute the symbolic ASTs, if the function is transparent *) - let symbolic_trans = translate_function_to_symbolics meta trans_ctx fdef in + let symbolic_trans = translate_function_to_symbolics trans_ctx fdef in (* Convert the symbolic ASTs to pure ASTs: *) @@ -176,7 +176,7 @@ let translate_function_to_pure (meta : Meta.meta) (trans_ctx : trans_ctx) SymbolicToPure.fresh_named_vars_for_symbolic_values input_svs ctx in { ctx with forward_inputs } - | _ -> craise meta "Unreachable" + | _ -> craise fdef.meta "Unreachable" in (* Add the backward inputs *) @@ -195,7 +195,7 @@ let translate_function_to_pure (meta : Meta.meta) (trans_ctx : trans_ctx) | Some (_, ast) -> SymbolicToPure.translate_fun_decl ctx (Some ast) (* TODO: factor out the return type *) -let translate_crate_to_pure (meta : Meta.meta) (crate : crate) : +let translate_crate_to_pure (crate : crate) : trans_ctx * Pure.type_decl list * pure_fun_translation list @@ -208,7 +208,7 @@ let translate_crate_to_pure (meta : Meta.meta) (crate : crate) : let trans_ctx = compute_contexts crate in (* Translate all the type definitions *) - let type_decls = SymbolicToPure.translate_type_decls meta trans_ctx in + let type_decls = SymbolicToPure.translate_type_decls trans_ctx in (* Compute the type definition map *) let type_decls_map = @@ -222,7 +222,7 @@ let translate_crate_to_pure (meta : Meta.meta) (crate : crate) : (List.map (fun (fdef : LlbcAst.fun_decl) -> ( fdef.def_id, - SymbolicToPure.translate_fun_sig_from_decl_to_decomposed meta trans_ctx + SymbolicToPure.translate_fun_sig_from_decl_to_decomposed trans_ctx fdef )) (FunDeclId.Map.values crate.fun_decls)) in @@ -230,21 +230,21 @@ let translate_crate_to_pure (meta : Meta.meta) (crate : crate) : (* Translate all the *transparent* functions *) let pure_translations = List.map - (translate_function_to_pure meta trans_ctx type_decls_map fun_dsigs) + (translate_function_to_pure trans_ctx type_decls_map fun_dsigs) (FunDeclId.Map.values crate.fun_decls) in (* Translate the trait declarations *) let trait_decls = List.map - (SymbolicToPure.translate_trait_decl meta trans_ctx) + (SymbolicToPure.translate_trait_decl trans_ctx) (TraitDeclId.Map.values trans_ctx.trait_decls_ctx.trait_decls) in (* Translate the trait implementations *) let trait_impls = List.map - (SymbolicToPure.translate_trait_impl meta trans_ctx) + (SymbolicToPure.translate_trait_impl trans_ctx) (TraitImplId.Map.values trans_ctx.trait_impls_ctx.trait_impls) in @@ -354,7 +354,7 @@ let export_type (fmt : Format.formatter) (config : gen_config) (ctx : gen_ctx) *) let export_types_group (meta : Meta.meta) (fmt : Format.formatter) (config : gen_config) (ctx : gen_ctx) (is_rec : bool) (ids : Pure.TypeDeclId.id list) : unit = - cassert (ids <> []) meta "TODO: Error message"; + assert (ids <> []) (* meta "TODO: Error message" *); let export_type = export_type fmt config ctx in let ids_set = Pure.TypeDeclId.Set.of_list ids in let export_type_decl kind id = export_type ids_set kind id true false in @@ -396,11 +396,11 @@ let export_types_group (meta : Meta.meta) (fmt : Format.formatter) (config : gen if List.exists (fun b -> b) builtin then (* Sanity check *) - cassert (List.for_all (fun b -> b) builtin) meta "TODO: Error message" + assert (List.for_all (fun b -> b) builtin) (* meta "TODO: Error message" *) else if List.exists dont_extract defs then (* Check if we have to ignore declarations *) (* Sanity check *) - cassert (List.for_all dont_extract defs) meta "TODO: Error message" + assert (List.for_all dont_extract defs) (* meta "TODO: Error message" *) else ( (* Extract the type declarations. @@ -442,13 +442,13 @@ let export_types_group (meta : Meta.meta) (fmt : Format.formatter) (config : gen TODO: check correct behavior with opaque globals. *) -let export_global (meta : Meta.meta) (fmt : Format.formatter) (config : gen_config) (ctx : gen_ctx) +let export_global (fmt : Format.formatter) (config : gen_config) (ctx : gen_ctx) (id : GlobalDeclId.id) : unit = let global_decls = ctx.trans_ctx.global_ctx.global_decls in let global = GlobalDeclId.Map.find id global_decls in let trans = FunDeclId.Map.find global.body ctx.trans_funs in - assert (trans.fwd.loops = []); - assert (trans.backs = []); + cassert (trans.fwd.loops = []) global.meta "TODO: Error message"; + cassert (trans.backs = []) global.meta "TODO: Error message"; let body = trans.fwd.f in let is_opaque = Option.is_none body.Pure.body in @@ -658,7 +658,7 @@ let export_trait_decl (fmt : Format.formatter) (_config : gen_config) let open ExtractBuiltin in if match_name_find_opt ctx.trans_ctx trait_decl.llbc_name - (builtin_trait_decls_map ()) + (builtin_trait_decls_map trait_decl.meta ()) = None then ( let ctx = { ctx with trait_decl_id = Some trait_decl.def_id } in @@ -702,7 +702,7 @@ let extract_definitions (meta : Meta.meta) (fmt : Format.formatter) (config : ge the [Arguments] information in Coq). *) let export_functions_group = export_functions_group meta fmt config ctx in - let export_global = export_global meta fmt config ctx in + let export_global = export_global fmt config ctx in let export_types_group = export_types_group meta fmt config ctx in let export_trait_decl_group id = export_trait_decl fmt config ctx id true false @@ -716,7 +716,7 @@ let extract_definitions (meta : Meta.meta) (fmt : Format.formatter) (config : ge let kind = if config.interface then ExtractBase.Declared else ExtractBase.Assumed in - Extract.extract_state_type fmt ctx kind + Extract.extract_state_type meta fmt ctx kind in let export_decl_group (dg : declaration_group) : unit = @@ -905,17 +905,17 @@ let extract_file (meta : Meta.meta) (config : gen_config) (ctx : gen_ctx) (fi : close_out out (** Translate a crate and write the synthesized code to an output file. *) -let translate_crate (meta : Meta.meta) (filename : string) (dest_dir : string) (crate : crate) : +let translate_crate (filename : string) (dest_dir : string) (crate : crate) : unit = (* Translate the module to the pure AST *) let trans_ctx, trans_types, trans_funs, trans_trait_decls, trans_trait_impls = - translate_crate_to_pure meta crate + translate_crate_to_pure crate in (* Initialize the names map by registering the keywords used in the language, as well as some primitive names ("u32", etc.). We insert the names of the local declarations later. *) - let names_maps = Extract.initialize_names_maps () in + let names_maps = Extract.initialize_names_maps () in (*TODO*) (* We need to compute which functions are recursive, in order to know * whether we should generate a decrease clause or not. *) @@ -1038,7 +1038,7 @@ let translate_crate (meta : Meta.meta) (filename : string) (dest_dir : string) ( match Filename.chop_suffix_opt ~suffix:".llbc" filename with | None -> (* Note that we already checked the suffix upon opening the file *) - craise meta "Unreachable" + raise (Failure "Unreachable") (* TODO check *) | Some filename -> (* Retrieve the file basename *) let basename = Filename.basename filename in @@ -1080,7 +1080,7 @@ let translate_crate (meta : Meta.meta) (filename : string) (dest_dir : string) ( let ( ^^ ) = Filename.concat in if !Config.split_files then mkdir_if (dest_dir ^^ crate_name); if needs_clauses_module then ( - cassert !Config.split_files meta "TODO: Error message"; + assert !Config.split_files (* meta "TODO: Error message META?" *); mkdir_if (dest_dir ^^ crate_name ^^ "Clauses"))); (* Copy the "Primitives" file, if necessary *) diff --git a/compiler/TypesAnalysis.ml b/compiler/TypesAnalysis.ml index 12c20262..c4fcdb4a 100644 --- a/compiler/TypesAnalysis.ml +++ b/compiler/TypesAnalysis.ml @@ -1,5 +1,6 @@ open Types open LlbcAst +open Errors type subtype_info = { under_borrow : bool; (** Are we inside a borrow? *) @@ -288,7 +289,7 @@ let analyze_type_decl (updated : bool ref) (infos : type_infos) (List.map (fun v -> List.map (fun f -> f.field_ty) v.fields) variants) - | Opaque -> raise (Failure "unreachable") + | Opaque -> craise def.meta "unreachable" in (* Explore the types and accumulate information *) let type_decl_info = TypeDeclId.Map.find def.def_id infos in diff --git a/compiler/ValuesUtils.ml b/compiler/ValuesUtils.ml index 2c7d213f..51c9e8cc 100644 --- a/compiler/ValuesUtils.ml +++ b/compiler/ValuesUtils.ml @@ -2,6 +2,7 @@ open Utils open TypesUtils open Types open Values +open Errors include Charon.ValuesUtils (** Utility exception *) @@ -10,34 +11,34 @@ exception FoundSymbolicValue of symbolic_value let mk_unit_value : typed_value = { value = VAdt { variant_id = None; field_values = [] }; ty = mk_unit_ty } -let mk_typed_value (ty : ty) (value : value) : typed_value = - assert (ty_is_ety ty); +let mk_typed_value (meta : Meta.meta) (ty : ty) (value : value) : typed_value = + cassert (ty_is_ety ty) meta "TODO: error message"; { value; ty } -let mk_typed_avalue (ty : ty) (value : avalue) : typed_avalue = - assert (ty_is_rty ty); +let mk_typed_avalue (meta : Meta.meta) (ty : ty) (value : avalue) : typed_avalue = + cassert (ty_is_rty ty) meta "TODO: error message"; { value; ty } -let mk_bottom (ty : ty) : typed_value = - assert (ty_is_ety ty); +let mk_bottom (meta : Meta.meta) (ty : ty) : typed_value = + cassert (ty_is_ety ty) meta "TODO: error message"; { value = VBottom; ty } -let mk_abottom (ty : ty) : typed_avalue = - assert (ty_is_rty ty); +let mk_abottom (meta : Meta.meta) (ty : ty) : typed_avalue = + cassert (ty_is_rty ty) meta "TODO: error message"; { value = ABottom; ty } -let mk_aignored (ty : ty) : typed_avalue = - assert (ty_is_rty ty); +let mk_aignored (meta : Meta.meta) (ty : ty) : typed_avalue = + cassert (ty_is_rty ty) meta "TODO: error message"; { value = AIgnored; ty } -let value_as_symbolic (v : value) : symbolic_value = - match v with VSymbolic v -> v | _ -> raise (Failure "Unexpected") +let value_as_symbolic (meta : Meta.meta) (v : value) : symbolic_value = + match v with VSymbolic v -> v | _ -> craise meta "Unexpected" (** Box a value *) -let mk_box_value (v : typed_value) : typed_value = +let mk_box_value (meta : Meta.meta) (v : typed_value) : typed_value = let box_ty = mk_box_ty v.ty in let box_v = VAdt { variant_id = None; field_values = [ v ] } in - mk_typed_value box_ty box_v + mk_typed_value meta box_ty box_v let is_bottom (v : value) : bool = match v with VBottom -> true | _ -> false @@ -47,13 +48,13 @@ let is_aignored (v : avalue) : bool = let is_symbolic (v : value) : bool = match v with VSymbolic _ -> true | _ -> false -let as_symbolic (v : value) : symbolic_value = - match v with VSymbolic s -> s | _ -> raise (Failure "Unexpected") +let as_symbolic (meta : Meta.meta) (v : value) : symbolic_value = + match v with VSymbolic s -> s | _ -> craise meta "Unexpected" -let as_mut_borrow (v : typed_value) : BorrowId.id * typed_value = +let as_mut_borrow (meta : Meta.meta) (v : typed_value) : BorrowId.id * typed_value = match v.value with | VBorrow (VMutBorrow (bid, bv)) -> (bid, bv) - | _ -> raise (Failure "Unexpected") + | _ -> craise meta "Unexpected" let is_unit (v : typed_value) : bool = ty_is_unit v.ty |