src/HOL/SPARK/Tools/spark_vcs.ML
author wenzelm
Sat, 17 Dec 2011 12:10:37 +0100
changeset 46777 0aaeb5520f2f
parent 46712 43a5b86bc102
child 47438 8421b6cf2a33
permissions -rw-r--r--
tuned signature;
     1 (*  Title:      HOL/SPARK/Tools/spark_vcs.ML
     2     Author:     Stefan Berghofer
     3     Copyright:  secunet Security Networks AG
     4 
     5 Store for verification conditions generated by SPARK/Ada.
     6 *)
     7 
     8 signature SPARK_VCS =
     9 sig
    10   val set_vcs: Fdl_Parser.decls -> Fdl_Parser.rules ->
    11     (string * string) * Fdl_Parser.vcs -> Path.T -> string -> theory -> theory
    12   val add_proof_fun: (typ option -> 'a -> term) ->
    13     string * ((string list * string) option * 'a) ->
    14     theory -> theory
    15   val add_type: string * typ -> theory -> theory
    16   val lookup_vc: theory -> string -> (Element.context_i list *
    17     (string * thm list option * Element.context_i * Element.statement_i)) option
    18   val get_vcs: theory ->
    19     Element.context_i list * (binding * thm) list * (string *
    20     (string * thm list option * Element.context_i * Element.statement_i)) list
    21   val mark_proved: string -> thm list -> theory -> theory
    22   val close: theory -> theory
    23   val is_closed: theory -> bool
    24 end;
    25 
    26 structure SPARK_VCs: SPARK_VCS =
    27 struct
    28 
    29 open Fdl_Parser;
    30 
    31 
    32 (** theory data **)
    33 
    34 fun err_unfinished () = error "An unfinished SPARK environment is still open."
    35 
    36 val strip_number = pairself implode o take_suffix Fdl_Lexer.is_digit o raw_explode;
    37 
    38 val name_ord = prod_ord string_ord (option_ord int_ord) o
    39   pairself (strip_number ##> Int.fromString);
    40 
    41 structure VCtab = Table(type key = string val ord = name_ord);
    42 
    43 structure VCs = Theory_Data
    44 (
    45   type T =
    46     {pfuns: ((string list * string) option * term) Symtab.table,
    47      type_map: typ Symtab.table,
    48      env:
    49        {ctxt: Element.context_i list,
    50         defs: (binding * thm) list,
    51         types: fdl_type tab,
    52         funs: (string list * string) tab,
    53         ids: (term * string) Symtab.table * Name.context,
    54         proving: bool,
    55         vcs: (string * thm list option *
    56           (string * expr) list * (string * expr) list) VCtab.table,
    57         path: Path.T,
    58         prefix: string} option}
    59   val empty : T = {pfuns = Symtab.empty, type_map = Symtab.empty, env = NONE}
    60   val extend = I
    61   fun merge ({pfuns = pfuns1, type_map = type_map1, env = NONE},
    62         {pfuns = pfuns2, type_map = type_map2, env = NONE}) =
    63         {pfuns = Symtab.merge (eq_pair (op =) (op aconv)) (pfuns1, pfuns2),
    64          type_map = Symtab.merge (op =) (type_map1, type_map2),
    65          env = NONE}
    66     | merge _ = err_unfinished ()
    67 )
    68 
    69 
    70 (** utilities **)
    71 
    72 val to_lower = raw_explode #> map Symbol.to_ascii_lower #> implode;
    73 
    74 val lcase_eq = (op =) o pairself (to_lower o Long_Name.base_name);
    75 
    76 fun lookup_prfx "" tab s = Symtab.lookup tab s
    77   | lookup_prfx prfx tab s = (case Symtab.lookup tab s of
    78         NONE => Symtab.lookup tab (prfx ^ "__" ^ s)
    79       | x => x);
    80 
    81 fun strip_prfx s =
    82   let
    83     fun strip ys [] = ("", implode ys)
    84       | strip ys ("_" :: "_" :: xs) = (implode (rev xs), implode ys)
    85       | strip ys (x :: xs) = strip (x :: ys) xs
    86   in strip [] (rev (raw_explode s)) end;
    87 
    88 fun mk_unop s t =
    89   let val T = fastype_of t
    90   in Const (s, T --> T) $ t end;
    91 
    92 fun mk_times (t, u) =
    93   let
    94     val setT = fastype_of t;
    95     val T = HOLogic.dest_setT setT;
    96     val U = HOLogic.dest_setT (fastype_of u)
    97   in
    98     Const (@{const_name Sigma}, setT --> (T --> HOLogic.mk_setT U) -->
    99       HOLogic.mk_setT (HOLogic.mk_prodT (T, U))) $ t $ Abs ("", T, u)
   100   end;
   101 
   102 fun get_type thy prfx ty =
   103   let val {type_map, ...} = VCs.get thy
   104   in lookup_prfx prfx type_map ty end;
   105 
   106 fun mk_type _ _ "integer" = HOLogic.intT
   107   | mk_type _ _ "boolean" = HOLogic.boolT
   108   | mk_type thy prfx ty =
   109       (case get_type thy prfx ty of
   110          NONE =>
   111            Syntax.check_typ (Proof_Context.init_global thy)
   112              (Type (Sign.full_name thy (Binding.name ty), []))
   113        | SOME T => T);
   114 
   115 val booleanN = "boolean";
   116 val integerN = "integer";
   117 
   118 fun define_overloaded (def_name, eq) lthy =
   119   let
   120     val ((c, _), rhs) = eq |> Syntax.check_term lthy |>
   121       Logic.dest_equals |>> dest_Free;
   122     val ((_, (_, thm)), lthy') = Local_Theory.define
   123       ((Binding.name c, NoSyn), ((Binding.name def_name, []), rhs)) lthy
   124     val ctxt_thy = Proof_Context.init_global (Proof_Context.theory_of lthy');
   125     val thm' = singleton (Proof_Context.export lthy' ctxt_thy) thm
   126   in (thm', lthy') end;
   127 
   128 fun strip_underscores s =
   129   strip_underscores (unsuffix "_" s) handle Fail _ => s;
   130 
   131 fun strip_tilde s =
   132   unsuffix "~" s ^ "_init" handle Fail _ => s;
   133 
   134 val mangle_name = strip_underscores #> strip_tilde;
   135 
   136 fun mk_variables thy prfx xs ty (tab, ctxt) =
   137   let
   138     val T = mk_type thy prfx ty;
   139     val (ys, ctxt') = fold_map Name.variant (map mangle_name xs) ctxt;
   140     val zs = map (Free o rpair T) ys;
   141   in (zs, (fold (Symtab.update o apsnd (rpair ty)) (xs ~~ zs) tab, ctxt')) end;
   142 
   143 fun get_record_info thy T = (case Record.dest_recTs T of
   144     [(tyname, [@{typ unit}])] =>
   145       Record.get_info thy (Long_Name.qualifier tyname)
   146   | _ => NONE);
   147 
   148 fun find_field fname = find_first (curry lcase_eq fname o fst);
   149 
   150 fun find_field' fname = get_first (fn (flds, fldty) =>
   151   if member (op =) flds fname then SOME fldty else NONE);
   152 
   153 fun assoc_ty_err thy T s msg =
   154   error ("Type " ^ Syntax.string_of_typ_global thy T ^
   155     " associated with SPARK type " ^ s ^ "\n" ^ msg);
   156 
   157 
   158 (** generate properties of enumeration types **)
   159 
   160 fun add_enum_type tyname tyname' thy =
   161   let
   162     val {case_name, ...} = the (Datatype.get_info thy tyname');
   163     val cs = map Const (the (Datatype.get_constrs thy tyname'));
   164     val k = length cs;
   165     val T = Type (tyname', []);
   166     val p = Const (@{const_name pos}, T --> HOLogic.intT);
   167     val v = Const (@{const_name val}, HOLogic.intT --> T);
   168     val card = Const (@{const_name card},
   169       HOLogic.mk_setT T --> HOLogic.natT) $ HOLogic.mk_UNIV T;
   170 
   171     fun mk_binrel_def s f = Logic.mk_equals
   172       (Const (s, T --> T --> HOLogic.boolT),
   173        Abs ("x", T, Abs ("y", T,
   174          Const (s, HOLogic.intT --> HOLogic.intT --> HOLogic.boolT) $
   175            (f $ Bound 1) $ (f $ Bound 0))));
   176 
   177     val (((def1, def2), def3), lthy) = thy |>
   178 
   179       Class.instantiation ([tyname'], [], @{sort spark_enum}) |>
   180 
   181       define_overloaded ("pos_" ^ tyname ^ "_def", Logic.mk_equals
   182         (p,
   183          list_comb (Const (case_name, replicate k HOLogic.intT @
   184              [T] ---> HOLogic.intT),
   185            map (HOLogic.mk_number HOLogic.intT) (0 upto k - 1)))) ||>>
   186 
   187       define_overloaded ("less_eq_" ^ tyname ^ "_def",
   188         mk_binrel_def @{const_name less_eq} p) ||>>
   189       define_overloaded ("less_" ^ tyname ^ "_def",
   190         mk_binrel_def @{const_name less} p);
   191 
   192     val UNIV_eq = Goal.prove lthy [] []
   193       (HOLogic.mk_Trueprop (HOLogic.mk_eq
   194          (HOLogic.mk_UNIV T, HOLogic.mk_set T cs)))
   195       (fn _ =>
   196          rtac @{thm subset_antisym} 1 THEN
   197          rtac @{thm subsetI} 1 THEN
   198          Datatype_Aux.exh_tac (K (#exhaust (Datatype.the_info
   199            (Proof_Context.theory_of lthy) tyname'))) 1 THEN
   200          ALLGOALS (asm_full_simp_tac (simpset_of lthy)));
   201 
   202     val finite_UNIV = Goal.prove lthy [] []
   203       (HOLogic.mk_Trueprop (Const (@{const_name finite},
   204          HOLogic.mk_setT T --> HOLogic.boolT) $ HOLogic.mk_UNIV T))
   205       (fn _ => simp_tac (simpset_of lthy addsimps [UNIV_eq]) 1);
   206 
   207     val card_UNIV = Goal.prove lthy [] []
   208       (HOLogic.mk_Trueprop (HOLogic.mk_eq
   209          (card, HOLogic.mk_number HOLogic.natT k)))
   210       (fn _ => simp_tac (simpset_of lthy addsimps [UNIV_eq]) 1);
   211 
   212     val range_pos = Goal.prove lthy [] []
   213       (HOLogic.mk_Trueprop (HOLogic.mk_eq
   214          (Const (@{const_name image}, (T --> HOLogic.intT) -->
   215             HOLogic.mk_setT T --> HOLogic.mk_setT HOLogic.intT) $
   216               p $ HOLogic.mk_UNIV T,
   217           Const (@{const_name atLeastLessThan}, HOLogic.intT -->
   218             HOLogic.intT --> HOLogic.mk_setT HOLogic.intT) $
   219               HOLogic.mk_number HOLogic.intT 0 $
   220               (@{term int} $ card))))
   221       (fn _ =>
   222          simp_tac (simpset_of lthy addsimps [card_UNIV]) 1 THEN
   223          simp_tac (simpset_of lthy addsimps [UNIV_eq, def1]) 1 THEN
   224          rtac @{thm subset_antisym} 1 THEN
   225          simp_tac (simpset_of lthy) 1 THEN
   226          rtac @{thm subsetI} 1 THEN
   227          asm_full_simp_tac (simpset_of lthy addsimps @{thms interval_expand}
   228            delsimps @{thms atLeastLessThan_iff}) 1);
   229 
   230     val lthy' =
   231       Class.prove_instantiation_instance (fn _ =>
   232         Class.intro_classes_tac [] THEN
   233         rtac finite_UNIV 1 THEN
   234         rtac range_pos 1 THEN
   235         simp_tac (HOL_basic_ss addsimps [def3]) 1 THEN
   236         simp_tac (HOL_basic_ss addsimps [def2]) 1) lthy;
   237 
   238     val (pos_eqs, val_eqs) = split_list (map_index (fn (i, c) =>
   239       let
   240         val n = HOLogic.mk_number HOLogic.intT i;
   241         val th = Goal.prove lthy' [] []
   242           (HOLogic.mk_Trueprop (HOLogic.mk_eq (p $ c, n)))
   243           (fn _ => simp_tac (simpset_of lthy' addsimps [def1]) 1);
   244         val th' = Goal.prove lthy' [] []
   245           (HOLogic.mk_Trueprop (HOLogic.mk_eq (v $ n, c)))
   246           (fn _ =>
   247              rtac (@{thm inj_pos} RS @{thm injD}) 1 THEN
   248              simp_tac (simpset_of lthy' addsimps
   249                [@{thm pos_val}, range_pos, card_UNIV, th]) 1)
   250       in (th, th') end) cs);
   251 
   252     val first_el = Goal.prove lthy' [] []
   253       (HOLogic.mk_Trueprop (HOLogic.mk_eq
   254          (Const (@{const_name first_el}, T), hd cs)))
   255       (fn _ => simp_tac (simpset_of lthy' addsimps
   256          [@{thm first_el_def}, hd val_eqs]) 1);
   257 
   258     val last_el = Goal.prove lthy' [] []
   259       (HOLogic.mk_Trueprop (HOLogic.mk_eq
   260          (Const (@{const_name last_el}, T), List.last cs)))
   261       (fn _ => simp_tac (simpset_of lthy' addsimps
   262          [@{thm last_el_def}, List.last val_eqs, card_UNIV]) 1);
   263   in
   264     lthy' |>
   265     Local_Theory.note
   266       ((Binding.name (tyname ^ "_card"), @{attributes [simp]}), [card_UNIV]) ||>>
   267     Local_Theory.note
   268       ((Binding.name (tyname ^ "_pos"), @{attributes [simp]}), pos_eqs) ||>>
   269     Local_Theory.note
   270       ((Binding.name (tyname ^ "_val"), @{attributes [simp]}), val_eqs) ||>>
   271     Local_Theory.note
   272       ((Binding.name (tyname ^ "_first_el"), @{attributes [simp]}), [first_el]) ||>>
   273     Local_Theory.note
   274       ((Binding.name (tyname ^ "_last_el"), @{attributes [simp]}), [last_el]) |> snd |>
   275     Local_Theory.exit_global
   276   end;
   277 
   278 
   279 fun check_no_assoc thy prfx s = case get_type thy prfx s of
   280     NONE => ()
   281   | SOME _ => error ("Cannot associate a type with " ^ s ^
   282       "\nsince it is no record or enumeration type");
   283 
   284 fun check_enum [] [] = NONE 
   285   | check_enum els [] = SOME ("has no element(s) " ^ commas els)
   286   | check_enum [] cs = SOME ("has extra element(s) " ^
   287       commas (map (Long_Name.base_name o fst) cs))
   288   | check_enum (el :: els) ((cname, _) :: cs) =
   289       if lcase_eq (el, cname) then check_enum els cs
   290       else SOME ("either has no element " ^ el ^
   291         " or it is at the wrong position");
   292 
   293 fun add_type_def prfx (s, Basic_Type ty) (ids, thy) =
   294       (check_no_assoc thy prfx s;
   295        (ids,
   296         Typedecl.abbrev_global (Binding.name s, [], NoSyn)
   297           (mk_type thy prfx ty) thy |> snd))
   298 
   299   | add_type_def prfx (s, Enum_Type els) ((tab, ctxt), thy) =
   300       let
   301         val (thy', tyname) = (case get_type thy prfx s of
   302             NONE =>
   303               let
   304                 val tyb = Binding.name s;
   305                 val tyname = Sign.full_name thy tyb
   306               in
   307                 (thy |>
   308                  Datatype.add_datatype {strict = true, quiet = true}
   309                    [((tyb, [], NoSyn), map (fn s => (Binding.name s, [], NoSyn)) els)] |> snd |>
   310                  add_enum_type s tyname,
   311                  tyname)
   312               end
   313           | SOME (T as Type (tyname, [])) =>
   314               (case Datatype.get_constrs thy tyname of
   315                  NONE => assoc_ty_err thy T s "is not a datatype"
   316                | SOME cs =>
   317                    let
   318                      val (prfx', _) = strip_prfx s;
   319                      val els' =
   320                        if prfx' = "" then els
   321                        else map (unprefix (prfx' ^ "__")) els
   322                          handle Fail _ => error ("Bad enumeration type " ^ s)
   323                    in
   324                      case check_enum els' cs of
   325                        NONE => (thy, tyname)
   326                      | SOME msg => assoc_ty_err thy T s msg
   327                    end));
   328         val cs = map Const (the (Datatype.get_constrs thy' tyname));
   329       in
   330         ((fold (Symtab.update_new o apsnd (rpair s)) (els ~~ cs) tab,
   331           fold Name.declare els ctxt),
   332          thy')
   333       end
   334 
   335   | add_type_def prfx (s, Array_Type (argtys, resty)) (ids, thy) =
   336       (check_no_assoc thy prfx s;
   337        (ids,
   338         Typedecl.abbrev_global (Binding.name s, [], NoSyn)
   339           (foldr1 HOLogic.mk_prodT (map (mk_type thy prfx) argtys) -->
   340              mk_type thy prfx resty) thy |> snd))
   341 
   342   | add_type_def prfx (s, Record_Type fldtys) (ids, thy) =
   343       (ids,
   344        let val fldTs = maps (fn (flds, ty) =>
   345          map (rpair (mk_type thy prfx ty)) flds) fldtys
   346        in case get_type thy prfx s of
   347            NONE =>
   348              Record.add_record ([], Binding.name s) NONE
   349                (map (fn (fld, T) => (Binding.name fld, T, NoSyn)) fldTs) thy
   350          | SOME rT =>
   351              (case get_record_info thy rT of
   352                 NONE => assoc_ty_err thy rT s "is not a record type"
   353               | SOME {fields, ...} =>
   354                   (case subtract (lcase_eq o pairself fst) fldTs fields of
   355                      [] => ()
   356                    | flds => assoc_ty_err thy rT s ("has extra field(s) " ^
   357                        commas (map (Long_Name.base_name o fst) flds));
   358                    map (fn (fld, T) =>
   359                      case AList.lookup lcase_eq fields fld of
   360                        NONE => assoc_ty_err thy rT s ("has no field " ^ fld)
   361                      | SOME U => T = U orelse assoc_ty_err thy rT s
   362                          ("has field " ^
   363                           fld ^ " whose type\n" ^
   364                           Syntax.string_of_typ_global thy U ^
   365                           "\ndoes not match declared type\n" ^
   366                           Syntax.string_of_typ_global thy T)) fldTs;
   367                    thy))
   368        end)
   369 
   370   | add_type_def prfx (s, Pending_Type) (ids, thy) =
   371       (ids,
   372        case get_type thy prfx s of
   373          SOME _ => thy
   374        | NONE => Typedecl.typedecl_global
   375            (Binding.name s, [], NoSyn) thy |> snd);
   376 
   377 
   378 fun term_of_expr thy prfx types pfuns =
   379   let
   380     fun tm_of vs (Funct ("->", [e, e'])) =
   381           (HOLogic.mk_imp (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
   382 
   383       | tm_of vs (Funct ("<->", [e, e'])) =
   384           (HOLogic.mk_eq (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
   385 
   386       | tm_of vs (Funct ("or", [e, e'])) =
   387           (HOLogic.mk_disj (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
   388 
   389       | tm_of vs (Funct ("and", [e, e'])) =
   390           (HOLogic.mk_conj (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
   391 
   392       | tm_of vs (Funct ("not", [e])) =
   393           (HOLogic.mk_not (fst (tm_of vs e)), booleanN)
   394 
   395       | tm_of vs (Funct ("=", [e, e'])) =
   396           (HOLogic.mk_eq (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
   397 
   398       | tm_of vs (Funct ("<>", [e, e'])) = (HOLogic.mk_not
   399           (HOLogic.mk_eq (fst (tm_of vs e), fst (tm_of vs e'))), booleanN)
   400 
   401       | tm_of vs (Funct ("<", [e, e'])) = (HOLogic.mk_binrel @{const_name less}
   402           (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
   403 
   404       | tm_of vs (Funct (">", [e, e'])) = (HOLogic.mk_binrel @{const_name less}
   405           (fst (tm_of vs e'), fst (tm_of vs e)), booleanN)
   406 
   407       | tm_of vs (Funct ("<=", [e, e'])) = (HOLogic.mk_binrel @{const_name less_eq}
   408           (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
   409 
   410       | tm_of vs (Funct (">=", [e, e'])) = (HOLogic.mk_binrel @{const_name less_eq}
   411           (fst (tm_of vs e'), fst (tm_of vs e)), booleanN)
   412 
   413       | tm_of vs (Funct ("+", [e, e'])) = (HOLogic.mk_binop @{const_name plus}
   414           (fst (tm_of vs e), fst (tm_of vs e')), integerN)
   415 
   416       | tm_of vs (Funct ("-", [e, e'])) = (HOLogic.mk_binop @{const_name minus}
   417           (fst (tm_of vs e), fst (tm_of vs e')), integerN)
   418 
   419       | tm_of vs (Funct ("*", [e, e'])) = (HOLogic.mk_binop @{const_name times}
   420           (fst (tm_of vs e), fst (tm_of vs e')), integerN)
   421 
   422       | tm_of vs (Funct ("/", [e, e'])) = (HOLogic.mk_binop @{const_name divide}
   423           (fst (tm_of vs e), fst (tm_of vs e')), integerN)
   424 
   425       | tm_of vs (Funct ("div", [e, e'])) = (HOLogic.mk_binop @{const_name sdiv}
   426           (fst (tm_of vs e), fst (tm_of vs e')), integerN)
   427 
   428       | tm_of vs (Funct ("mod", [e, e'])) = (HOLogic.mk_binop @{const_name mod}
   429           (fst (tm_of vs e), fst (tm_of vs e')), integerN)
   430 
   431       | tm_of vs (Funct ("-", [e])) =
   432           (mk_unop @{const_name uminus} (fst (tm_of vs e)), integerN)
   433 
   434       | tm_of vs (Funct ("**", [e, e'])) =
   435           (Const (@{const_name power}, HOLogic.intT --> HOLogic.natT -->
   436              HOLogic.intT) $ fst (tm_of vs e) $
   437                (@{const nat} $ fst (tm_of vs e')), integerN)
   438 
   439       | tm_of (tab, _) (Ident s) =
   440           (case Symtab.lookup tab s of
   441              SOME t_ty => t_ty
   442            | NONE => (case lookup_prfx prfx pfuns s of
   443                SOME (SOME ([], resty), t) => (t, resty)
   444              | _ => error ("Undeclared identifier " ^ s)))
   445 
   446       | tm_of _ (Number i) = (HOLogic.mk_number HOLogic.intT i, integerN)
   447 
   448       | tm_of vs (Quantifier (s, xs, ty, e)) =
   449           let
   450             val (ys, vs') = mk_variables thy prfx xs ty vs;
   451             val q = (case s of
   452                 "for_all" => HOLogic.mk_all
   453               | "for_some" => HOLogic.mk_exists)
   454           in
   455             (fold_rev (fn Free (x, T) => fn t => q (x, T, t))
   456                ys (fst (tm_of vs' e)),
   457              booleanN)
   458           end
   459 
   460       | tm_of vs (Funct (s, es)) =
   461 
   462           (* record field selection *)
   463           (case try (unprefix "fld_") s of
   464              SOME fname => (case es of
   465                [e] =>
   466                  let
   467                    val (t, rcdty) = tm_of vs e;
   468                    val rT = mk_type thy prfx rcdty
   469                  in case (get_record_info thy rT, lookup types rcdty) of
   470                      (SOME {fields, ...}, SOME (Record_Type fldtys)) =>
   471                        (case (find_field fname fields,
   472                             find_field' fname fldtys) of
   473                           (SOME (fname', fT), SOME fldty) =>
   474                             (Const (fname', rT --> fT) $ t, fldty)
   475                         | _ => error ("Record " ^ rcdty ^
   476                             " has no field named " ^ fname))
   477                    | _ => error (rcdty ^ " is not a record type")
   478                  end
   479              | _ => error ("Function " ^ s ^ " expects one argument"))
   480            | NONE =>
   481 
   482           (* record field update *)
   483           (case try (unprefix "upf_") s of
   484              SOME fname => (case es of
   485                [e, e'] =>
   486                  let
   487                    val (t, rcdty) = tm_of vs e;
   488                    val rT = mk_type thy prfx rcdty;
   489                    val (u, fldty) = tm_of vs e';
   490                    val fT = mk_type thy prfx fldty
   491                  in case get_record_info thy rT of
   492                      SOME {fields, ...} =>
   493                        (case find_field fname fields of
   494                           SOME (fname', fU) =>
   495                             if fT = fU then
   496                               (Const (fname' ^ "_update",
   497                                  (fT --> fT) --> rT --> rT) $
   498                                    Abs ("x", fT, u) $ t,
   499                                rcdty)
   500                             else error ("Type\n" ^
   501                               Syntax.string_of_typ_global thy fT ^
   502                               "\ndoes not match type\n" ^
   503                               Syntax.string_of_typ_global thy fU ^
   504                               "\nof field " ^ fname)
   505                         | NONE => error ("Record " ^ rcdty ^
   506                             " has no field named " ^ fname))
   507                    | _ => error (rcdty ^ " is not a record type")
   508                  end
   509              | _ => error ("Function " ^ s ^ " expects two arguments"))
   510            | NONE =>
   511 
   512           (* enumeration type to integer *)
   513           (case try (unsuffix "__pos") s of
   514              SOME tyname => (case es of
   515                [e] => (Const (@{const_name pos},
   516                    mk_type thy prfx tyname --> HOLogic.intT) $ fst (tm_of vs e),
   517                  integerN)
   518              | _ => error ("Function " ^ s ^ " expects one argument"))
   519            | NONE =>
   520 
   521           (* integer to enumeration type *)
   522           (case try (unsuffix "__val") s of
   523              SOME tyname => (case es of
   524                [e] => (Const (@{const_name val},
   525                    HOLogic.intT --> mk_type thy prfx tyname) $ fst (tm_of vs e),
   526                  tyname)
   527              | _ => error ("Function " ^ s ^ " expects one argument"))
   528            | NONE =>
   529 
   530           (* successor / predecessor of enumeration type element *)
   531           if s = "succ" orelse s = "pred" then (case es of
   532               [e] =>
   533                 let
   534                   val (t, tyname) = tm_of vs e;
   535                   val T = mk_type thy prfx tyname
   536                 in (Const
   537                   (if s = "succ" then @{const_name succ}
   538                    else @{const_name pred}, T --> T) $ t, tyname)
   539                 end
   540             | _ => error ("Function " ^ s ^ " expects one argument"))
   541 
   542           (* user-defined proof function *)
   543           else
   544             (case lookup_prfx prfx pfuns s of
   545                SOME (SOME (_, resty), t) =>
   546                  (list_comb (t, map (fst o tm_of vs) es), resty)
   547              | _ => error ("Undeclared proof function " ^ s))))))
   548 
   549       | tm_of vs (Element (e, es)) =
   550           let val (t, ty) = tm_of vs e
   551           in case lookup types ty of
   552               SOME (Array_Type (_, elty)) =>
   553                 (t $ foldr1 HOLogic.mk_prod (map (fst o tm_of vs) es), elty)
   554             | _ => error (ty ^ " is not an array type")
   555           end
   556 
   557       | tm_of vs (Update (e, es, e')) =
   558           let val (t, ty) = tm_of vs e
   559           in case lookup types ty of
   560               SOME (Array_Type (idxtys, elty)) =>
   561                 let
   562                   val T = foldr1 HOLogic.mk_prodT
   563                     (map (mk_type thy prfx) idxtys);
   564                   val U = mk_type thy prfx elty;
   565                   val fT = T --> U
   566                 in
   567                   (Const (@{const_name fun_upd}, fT --> T --> U --> fT) $
   568                      t $ foldr1 HOLogic.mk_prod (map (fst o tm_of vs) es) $
   569                        fst (tm_of vs e'),
   570                    ty)
   571                 end
   572             | _ => error (ty ^ " is not an array type")
   573           end
   574 
   575       | tm_of vs (Record (s, flds)) =
   576           let
   577             val T = mk_type thy prfx s;
   578             val {extension = (ext_name, _), fields, ...} =
   579               (case get_record_info thy T of
   580                  NONE => error (s ^ " is not a record type")
   581                | SOME info => info);
   582             val flds' = map (apsnd (tm_of vs)) flds;
   583             val fnames = map (Long_Name.base_name o fst) fields;
   584             val fnames' = map fst flds;
   585             val (fvals, ftys) = split_list (map (fn s' =>
   586               case AList.lookup lcase_eq flds' s' of
   587                 SOME fval_ty => fval_ty
   588               | NONE => error ("Field " ^ s' ^ " missing in record " ^ s))
   589                   fnames);
   590             val _ = (case subtract lcase_eq fnames fnames' of
   591                 [] => ()
   592               | xs => error ("Extra field(s) " ^ commas xs ^
   593                   " in record " ^ s));
   594             val _ = (case duplicates (op =) fnames' of
   595                 [] => ()
   596               | xs => error ("Duplicate field(s) " ^ commas xs ^
   597                   " in record " ^ s))
   598           in
   599             (list_comb
   600                (Const (ext_name,
   601                   map (mk_type thy prfx) ftys @ [HOLogic.unitT] ---> T),
   602                 fvals @ [HOLogic.unit]),
   603              s)
   604           end
   605 
   606       | tm_of vs (Array (s, default, assocs)) =
   607           (case lookup types s of
   608              SOME (Array_Type (idxtys, elty)) =>
   609                let
   610                  val Ts = map (mk_type thy prfx) idxtys;
   611                  val T = foldr1 HOLogic.mk_prodT Ts;
   612                  val U = mk_type thy prfx elty;
   613                  fun mk_idx' T (e, NONE) = HOLogic.mk_set T [fst (tm_of vs e)]
   614                    | mk_idx' T (e, SOME e') = Const (@{const_name atLeastAtMost},
   615                        T --> T --> HOLogic.mk_setT T) $
   616                          fst (tm_of vs e) $ fst (tm_of vs e');
   617                  fun mk_idx idx =
   618                    if length Ts <> length idx then
   619                      error ("Arity mismatch in construction of array " ^ s)
   620                    else foldr1 mk_times (map2 mk_idx' Ts idx);
   621                  fun mk_upd (idxs, e) t =
   622                    if length idxs = 1 andalso forall (is_none o snd) (hd idxs)
   623                    then
   624                      Const (@{const_name fun_upd}, (T --> U) -->
   625                          T --> U --> T --> U) $ t $
   626                        foldl1 HOLogic.mk_prod
   627                          (map (fst o tm_of vs o fst) (hd idxs)) $
   628                        fst (tm_of vs e)
   629                    else
   630                      Const (@{const_name fun_upds}, (T --> U) -->
   631                          HOLogic.mk_setT T --> U --> T --> U) $ t $
   632                        foldl1 (HOLogic.mk_binop @{const_name sup})
   633                          (map mk_idx idxs) $
   634                        fst (tm_of vs e)
   635                in
   636                  (fold mk_upd assocs
   637                     (case default of
   638                        SOME e => Abs ("x", T, fst (tm_of vs e))
   639                      | NONE => Const (@{const_name undefined}, T --> U)),
   640                   s)
   641                end
   642            | _ => error (s ^ " is not an array type"))
   643 
   644   in tm_of end;
   645 
   646 
   647 fun term_of_rule thy prfx types pfuns ids rule =
   648   let val tm_of = fst o term_of_expr thy prfx types pfuns ids
   649   in case rule of
   650       Inference_Rule (es, e) => Logic.list_implies
   651         (map (HOLogic.mk_Trueprop o tm_of) es, HOLogic.mk_Trueprop (tm_of e))
   652     | Substitution_Rule (es, e, e') => Logic.list_implies
   653         (map (HOLogic.mk_Trueprop o tm_of) es,
   654          HOLogic.mk_Trueprop (HOLogic.mk_eq (tm_of e, tm_of e')))
   655   end;
   656 
   657 
   658 val builtin = Symtab.make (map (rpair ())
   659   ["->", "<->", "or", "and", "not", "=", "<>", "<", ">", "<=", ">=",
   660    "+", "-", "*", "/", "div", "mod", "**"]);
   661 
   662 fun complex_expr (Number _) = false
   663   | complex_expr (Ident _) = false 
   664   | complex_expr (Funct (s, es)) =
   665       not (Symtab.defined builtin s) orelse exists complex_expr es
   666   | complex_expr (Quantifier (_, _, _, e)) = complex_expr e
   667   | complex_expr _ = true;
   668 
   669 fun complex_rule (Inference_Rule (es, e)) =
   670       complex_expr e orelse exists complex_expr es
   671   | complex_rule (Substitution_Rule (es, e, e')) =
   672       complex_expr e orelse complex_expr e' orelse
   673       exists complex_expr es;
   674 
   675 val is_pfun =
   676   Symtab.defined builtin orf
   677   can (unprefix "fld_") orf can (unprefix "upf_") orf
   678   can (unsuffix "__pos") orf can (unsuffix "__val") orf
   679   equal "succ" orf equal "pred";
   680 
   681 fun fold_opt f = the_default I o Option.map f;
   682 fun fold_pair f g (x, y) = f x #> g y;
   683 
   684 fun fold_expr f g (Funct (s, es)) = f s #> fold (fold_expr f g) es
   685   | fold_expr f g (Ident s) = g s
   686   | fold_expr f g (Number _) = I
   687   | fold_expr f g (Quantifier (_, _, _, e)) = fold_expr f g e
   688   | fold_expr f g (Element (e, es)) =
   689       fold_expr f g e #> fold (fold_expr f g) es
   690   | fold_expr f g (Update (e, es, e')) =
   691       fold_expr f g e #> fold (fold_expr f g) es #> fold_expr f g e'
   692   | fold_expr f g (Record (_, flds)) = fold (fold_expr f g o snd) flds
   693   | fold_expr f g (Array (_, default, assocs)) =
   694       fold_opt (fold_expr f g) default #>
   695       fold (fold_pair
   696         (fold (fold (fold_pair
   697           (fold_expr f g) (fold_opt (fold_expr f g)))))
   698         (fold_expr f g)) assocs;
   699 
   700 fun add_expr_pfuns funs = fold_expr
   701   (fn s => if is_pfun s then I else insert (op =) s)
   702   (fn s => if is_none (lookup funs s) then I else insert (op =) s);
   703 
   704 val add_expr_idents = fold_expr (K I) (insert (op =));
   705 
   706 fun pfun_type thy prfx (argtys, resty) =
   707   map (mk_type thy prfx) argtys ---> mk_type thy prfx resty;
   708 
   709 fun check_pfun_type thy prfx s t optty1 optty2 =
   710   let
   711     val T = fastype_of t;
   712     fun check ty =
   713       let val U = pfun_type thy prfx ty
   714       in
   715         T = U orelse
   716         error ("Type\n" ^
   717           Syntax.string_of_typ_global thy T ^
   718           "\nof function " ^
   719           Syntax.string_of_term_global thy t ^
   720           " associated with proof function " ^ s ^
   721           "\ndoes not match declared type\n" ^
   722           Syntax.string_of_typ_global thy U)
   723       end
   724   in (Option.map check optty1; Option.map check optty2; ()) end;
   725 
   726 fun upd_option x y = if is_some x then x else y;
   727 
   728 fun check_pfuns_types thy prfx funs =
   729   Symtab.map (fn s => fn (optty, t) =>
   730    let val optty' = lookup funs
   731      (if prfx = "" then s
   732       else unprefix (prfx ^ "__") s handle Fail _ => s)
   733    in
   734      (check_pfun_type thy prfx s t optty optty';
   735       (NONE |> upd_option optty |> upd_option optty', t))
   736    end);
   737 
   738 
   739 (** the VC store **)
   740 
   741 fun err_vcs names = error (Pretty.string_of
   742   (Pretty.big_list "The following verification conditions have not been proved:"
   743     (map Pretty.str names)))
   744 
   745 fun set_env (env as {funs, prefix, ...}) thy = VCs.map (fn
   746     {pfuns, type_map, env = NONE} =>
   747       {pfuns = check_pfuns_types thy prefix funs pfuns,
   748        type_map = type_map,
   749        env = SOME env}
   750   | _ => err_unfinished ()) thy;
   751 
   752 fun mk_pat s = (case Int.fromString s of
   753     SOME i => [HOLogic.mk_Trueprop (Var (("C", i), HOLogic.boolT))]
   754   | NONE => error ("Bad conclusion identifier: C" ^ s));
   755 
   756 fun mk_vc thy prfx types pfuns ids (tr, proved, ps, cs) =
   757   let val prop_of =
   758     HOLogic.mk_Trueprop o fst o term_of_expr thy prfx types pfuns ids
   759   in
   760     (tr, proved,
   761      Element.Assumes (map (fn (s', e) =>
   762        ((Binding.name ("H" ^ s'), []), [(prop_of e, [])])) ps),
   763      Element.Shows (map (fn (s', e) =>
   764        (Attrib.empty_binding, [(prop_of e, mk_pat s')])) cs))
   765   end;
   766 
   767 fun fold_vcs f vcs =
   768   VCtab.fold (fn (_, (_, _, ps, cs)) => fold f ps #> fold f cs) vcs;
   769 
   770 fun pfuns_of_vcs prfx funs pfuns vcs =
   771   fold_vcs (add_expr_pfuns funs o snd) vcs [] |>
   772   filter (is_none o lookup_prfx prfx pfuns);
   773 
   774 fun declare_missing_pfuns thy prfx funs pfuns vcs (tab, ctxt) =
   775   let
   776     val (fs, (tys, Ts)) =
   777       pfuns_of_vcs prfx funs pfuns vcs |>
   778       map_filter (fn s => lookup funs s |>
   779         Option.map (fn ty => (s, (SOME ty, pfun_type thy prfx ty)))) |>
   780       split_list ||> split_list;
   781     val (fs', ctxt') = fold_map Name.variant fs ctxt
   782   in
   783     (fold Symtab.update_new (fs ~~ (tys ~~ map Free (fs' ~~ Ts))) pfuns,
   784      Element.Fixes (map2 (fn s => fn T =>
   785        (Binding.name s, SOME T, NoSyn)) fs' Ts),
   786      (tab, ctxt'))
   787   end;
   788 
   789 fun add_proof_fun prep (s, (optty, raw_t)) thy =
   790   VCs.map (fn
   791       {env = SOME {proving = true, ...}, ...} => err_unfinished ()
   792     | {pfuns, type_map, env} =>
   793         let
   794           val (optty', prfx) = (case env of
   795               SOME {funs, prefix, ...} => (lookup funs s, prefix)
   796             | NONE => (NONE, ""));
   797           val optty'' = NONE |> upd_option optty |> upd_option optty';
   798           val t = prep (Option.map (pfun_type thy prfx) optty'') raw_t;
   799           val _ = (case fold_aterms (fn u =>
   800               if is_Var u orelse is_Free u then insert (op =) u else I) t [] of
   801               [] => ()
   802             | ts => error ("Term\n" ^ Syntax.string_of_term_global thy t ^
   803                 "\nto be associated with proof function " ^ s ^
   804                 " contains free variable(s) " ^
   805                 commas (map (Syntax.string_of_term_global thy) ts)));
   806         in
   807           (check_pfun_type thy prfx s t optty optty';
   808            if is_some optty'' orelse is_none env then
   809              {pfuns = Symtab.update_new (s, (optty'', t)) pfuns,
   810               type_map = type_map,
   811               env = env}
   812                handle Symtab.DUP _ => error ("Proof function " ^ s ^
   813                  " already associated with function")
   814            else error ("Undeclared proof function " ^ s))
   815         end) thy;
   816 
   817 fun add_type (s, T as Type (tyname, Ts)) thy =
   818       thy |>
   819       VCs.map (fn
   820           {env = SOME _, ...} => err_unfinished ()
   821         | {pfuns, type_map, env} =>
   822             {pfuns = pfuns,
   823              type_map = Symtab.update_new (s, T) type_map,
   824              env = env}
   825               handle Symtab.DUP _ => error ("SPARK type " ^ s ^
   826                 " already associated with type")) |>
   827       (fn thy' =>
   828          case Datatype.get_constrs thy' tyname of
   829            NONE => thy'
   830          | SOME cs =>
   831              if null Ts then
   832                (map
   833                   (fn (_, Type (_, [])) => ()
   834                     | (cname, _) => assoc_ty_err thy T s
   835                         ("has illegal constructor " ^
   836                          Long_Name.base_name cname)) cs;
   837                 add_enum_type s tyname thy')
   838              else assoc_ty_err thy T s "is illegal")
   839   | add_type (s, T) thy = assoc_ty_err thy T s "is illegal";
   840 
   841 val is_closed = is_none o #env o VCs.get;
   842 
   843 fun lookup_vc thy name =
   844   (case VCs.get thy of
   845     {env = SOME {vcs, types, funs, ids, ctxt, prefix, ...}, pfuns, ...} =>
   846       (case VCtab.lookup vcs name of
   847          SOME vc =>
   848            let val (pfuns', ctxt', ids') =
   849              declare_missing_pfuns thy prefix funs pfuns vcs ids
   850            in SOME (ctxt @ [ctxt'], mk_vc thy prefix types pfuns' ids' vc) end
   851        | NONE => NONE)
   852   | _ => NONE);
   853 
   854 fun get_vcs thy = (case VCs.get thy of
   855     {env = SOME {vcs, types, funs, ids, ctxt, defs, prefix, ...}, pfuns, ...} =>
   856       let val (pfuns', ctxt', ids') =
   857         declare_missing_pfuns thy prefix funs pfuns vcs ids
   858       in
   859         (ctxt @ [ctxt'], defs,
   860          VCtab.dest vcs |>
   861          map (apsnd (mk_vc thy prefix types pfuns' ids')))
   862       end
   863   | _ => ([], [], []));
   864 
   865 fun mark_proved name thms = VCs.map (fn
   866     {pfuns, type_map,
   867      env = SOME {ctxt, defs, types, funs, ids, vcs, path, prefix, ...}} =>
   868       {pfuns = pfuns,
   869        type_map = type_map,
   870        env = SOME {ctxt = ctxt, defs = defs,
   871          types = types, funs = funs, ids = ids,
   872          proving = true,
   873          vcs = VCtab.map_entry name (fn (trace, _, ps, cs) =>
   874            (trace, SOME thms, ps, cs)) vcs,
   875          path = path,
   876          prefix = prefix}}
   877   | x => x);
   878 
   879 fun close thy =
   880   thy |>
   881   VCs.map (fn
   882       {pfuns, type_map, env = SOME {vcs, path, ...}} =>
   883         (case VCtab.fold_rev (fn vc as (_, (_, p, _, _)) =>
   884              (if is_some p then apfst else apsnd) (cons vc)) vcs ([], []) of
   885            (proved, []) =>
   886              (Thm.join_proofs (maps (the o #2 o snd) proved);
   887               File.write (Path.ext "prv" path)
   888                 (implode (map (fn (s, _) => snd (strip_number s) ^
   889                    " -- proved by " ^ Distribution.version ^ "\n") proved));
   890               {pfuns = pfuns, type_map = type_map, env = NONE})
   891          | (_, unproved) => err_vcs (map fst unproved))
   892     | _ => error "No SPARK environment is currently open") |>
   893   Sign.parent_path;
   894 
   895 
   896 (** set up verification conditions **)
   897 
   898 fun partition_opt f =
   899   let
   900     fun part ys zs [] = (rev ys, rev zs)
   901       | part ys zs (x :: xs) = (case f x of
   902             SOME y => part (y :: ys) zs xs
   903           | NONE => part ys (x :: zs) xs)
   904   in part [] [] end;
   905 
   906 fun dest_def (id, (Substitution_Rule ([], Ident s, rhs))) = SOME (id, (s, rhs))
   907   | dest_def _ = NONE;
   908 
   909 fun mk_rulename (s, i) = Binding.name (s ^ string_of_int i);
   910 
   911 fun add_const prfx (s, ty) ((tab, ctxt), thy) =
   912   let
   913     val T = mk_type thy prfx ty;
   914     val b = Binding.name s;
   915     val c = Const (Sign.full_name thy b, T)
   916   in
   917     (c,
   918      ((Symtab.update (s, (c, ty)) tab, Name.declare s ctxt),
   919       Sign.add_consts_i [(b, T, NoSyn)] thy))
   920   end;
   921 
   922 fun add_def prfx types pfuns consts (id, (s, e)) (ids as (tab, ctxt), thy) =
   923   (case lookup consts s of
   924      SOME ty =>
   925        let
   926          val (t, ty') = term_of_expr thy prfx types pfuns ids e;
   927          val T = mk_type thy prfx ty;
   928          val T' = mk_type thy prfx ty';
   929          val _ = T = T' orelse
   930            error ("Declared type " ^ ty ^ " of " ^ s ^
   931              "\ndoes not match type " ^ ty' ^ " in definition");
   932          val id' = mk_rulename id;
   933          val lthy = Named_Target.theory_init thy;
   934          val ((t', (_, th)), lthy') = Specification.definition
   935            (NONE, ((id', []), HOLogic.mk_Trueprop (HOLogic.mk_eq
   936              (Free (s, T), t)))) lthy;
   937          val phi = Proof_Context.export_morphism lthy' lthy
   938        in
   939          ((id', Morphism.thm phi th),
   940           ((Symtab.update (s, (Morphism.term phi t', ty)) tab,
   941             Name.declare s ctxt),
   942            Local_Theory.exit_global lthy'))
   943        end
   944    | NONE => error ("Undeclared constant " ^ s));
   945 
   946 fun add_var prfx (s, ty) (ids, thy) =
   947   let val ([Free p], ids') = mk_variables thy prfx [s] ty ids
   948   in (p, (ids', thy)) end;
   949 
   950 fun add_init_vars prfx vcs (ids_thy as ((tab, _), _)) =
   951   fold_map (add_var prfx)
   952     (map_filter
   953        (fn s => case try (unsuffix "~") s of
   954           SOME s' => (case Symtab.lookup tab s' of
   955             SOME (_, ty) => SOME (s, ty)
   956           | NONE => error ("Undeclared identifier " ^ s'))
   957         | NONE => NONE)
   958        (fold_vcs (add_expr_idents o snd) vcs []))
   959     ids_thy;
   960 
   961 fun is_trivial_vc ([], [(_, Ident "true")]) = true
   962   | is_trivial_vc _ = false;
   963 
   964 fun rulenames rules = commas
   965   (map (fn ((s, i), _) => s ^ "(" ^ string_of_int i ^ ")") rules);
   966 
   967 (* sort definitions according to their dependency *)
   968 fun sort_defs _ _ _ _ [] sdefs = rev sdefs
   969   | sort_defs prfx funs pfuns consts defs sdefs =
   970       (case find_first (fn (_, (_, e)) =>
   971          forall (is_some o lookup_prfx prfx pfuns)
   972            (add_expr_pfuns funs e []) andalso
   973          forall (fn id =>
   974            member (fn (s, (_, (s', _))) => s = s') sdefs id orelse
   975            consts id)
   976              (add_expr_idents e [])) defs of
   977          SOME d => sort_defs prfx funs pfuns consts
   978            (remove (op =) d defs) (d :: sdefs)
   979        | NONE => error ("Bad definitions: " ^ rulenames defs));
   980 
   981 fun set_vcs ({types, vars, consts, funs} : decls)
   982       (rules, _) ((_, ident), vcs) path prfx thy =
   983   let
   984     val {pfuns, ...} = VCs.get thy;
   985     val (defs, rules') = partition_opt dest_def rules;
   986     val consts' =
   987       subtract (fn ((_, (s, _)), (s', _)) => s = s') defs (items consts);
   988     (* ignore all complex rules in rls files *)
   989     val (rules'', other_rules) =
   990       List.partition (complex_rule o snd) rules';
   991     val _ = if null rules'' then ()
   992       else warning ("Ignoring rules: " ^ rulenames rules'');
   993 
   994     val vcs' = VCtab.make (maps (fn (tr, vcs) =>
   995       map (fn (s, (ps, cs)) => (s, (tr, NONE, ps, cs)))
   996         (filter_out (is_trivial_vc o snd) vcs)) vcs);
   997 
   998     val _ = (case filter_out (is_some o lookup funs)
   999         (pfuns_of_vcs prfx funs pfuns vcs') of
  1000         [] => ()
  1001       | fs => error ("Undeclared proof function(s) " ^ commas fs));
  1002 
  1003     val (((defs', vars''), ivars), (ids, thy')) =
  1004       ((Symtab.empty |>
  1005         Symtab.update ("false", (@{term False}, booleanN)) |>
  1006         Symtab.update ("true", (@{term True}, booleanN)),
  1007         Name.context),
  1008        thy |> Sign.add_path (Long_Name.base_name ident)) |>
  1009       fold (add_type_def prfx) (items types) |>
  1010       fold (snd oo add_const prfx) consts' |> (fn ids_thy as ((tab, _), _) =>
  1011         ids_thy |>
  1012         fold_map (add_def prfx types pfuns consts)
  1013           (sort_defs prfx funs pfuns (Symtab.defined tab) defs []) ||>>
  1014         fold_map (add_var prfx) (items vars) ||>>
  1015         add_init_vars prfx vcs');
  1016 
  1017     val ctxt =
  1018       [Element.Fixes (map (fn (s, T) =>
  1019          (Binding.name s, SOME T, NoSyn)) (vars'' @ ivars)),
  1020        Element.Assumes (map (fn (id, rl) =>
  1021          ((mk_rulename id, []),
  1022           [(term_of_rule thy' prfx types pfuns ids rl, [])]))
  1023            other_rules),
  1024        Element.Notes ("", [((Binding.name "defns", []), map (rpair [] o single o snd) defs')])]
  1025           
  1026   in
  1027     set_env {ctxt = ctxt, defs = defs', types = types, funs = funs,
  1028       ids = ids, proving = false, vcs = vcs', path = path, prefix = prfx} thy'
  1029   end;
  1030 
  1031 end;