src/Pure/Isar/code.ML
author wenzelm
Wed Jun 02 11:09:26 2010 +0200 (2010-06-02 ago)
changeset 37251 72c7e636067b
parent 36615 88756a5a92fc
child 37425 b5492f611129
permissions -rw-r--r--
normalize and postprocess proof body in a separate future, taking care of platforms without multithreading (greately improves parallelization in general without the overhead of promised proofs, cf. usedir -q 0);
     1 (*  Title:      Pure/Isar/code.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Abstract executable ingredients of theory.  Management of data
     5 dependent on executable ingredients as synchronized cache; purged
     6 on any change of underlying executable ingredients.
     7 *)
     8 
     9 signature CODE =
    10 sig
    11   (*constants*)
    12   val check_const: theory -> term -> string
    13   val read_bare_const: theory -> string -> string * typ
    14   val read_const: theory -> string -> string
    15   val string_of_const: theory -> string -> string
    16   val cert_signature: theory -> typ -> typ
    17   val read_signature: theory -> string -> typ
    18   val const_typ: theory -> string -> typ
    19   val subst_signatures: theory -> term -> term
    20   val args_number: theory -> string -> int
    21 
    22   (*constructor sets*)
    23   val constrset_of_consts: theory -> (string * typ) list
    24     -> string * ((string * sort) list * (string * typ list) list)
    25 
    26   (*code equations and certificates*)
    27   val mk_eqn: theory -> thm * bool -> thm * bool
    28   val mk_eqn_warning: theory -> thm -> (thm * bool) option
    29   val mk_eqn_liberal: theory -> thm -> (thm * bool) option
    30   val assert_eqn: theory -> thm * bool -> thm * bool
    31   val const_typ_eqn: theory -> thm -> string * typ
    32   val expand_eta: theory -> int -> thm -> thm
    33   type cert
    34   val empty_cert: theory -> string -> cert
    35   val cert_of_eqns: theory -> string -> (thm * bool) list -> cert
    36   val constrain_cert: theory -> sort list -> cert -> cert
    37   val typargs_deps_of_cert: theory -> cert -> (string * sort) list * (string * typ list) list
    38   val equations_of_cert: theory -> cert -> ((string * sort) list * typ)
    39     * (((term * string option) list * (term * string option)) * (thm option * bool)) list
    40   val bare_thms_of_cert: theory -> cert -> thm list
    41   val pretty_cert: theory -> cert -> Pretty.T list
    42 
    43   (*executable code*)
    44   val add_type: string -> theory -> theory
    45   val add_type_cmd: string -> theory -> theory
    46   val add_signature: string * typ -> theory -> theory
    47   val add_signature_cmd: string * string -> theory -> theory
    48   val add_datatype: (string * typ) list -> theory -> theory
    49   val add_datatype_cmd: string list -> theory -> theory
    50   val datatype_interpretation:
    51     (string * ((string * sort) list * (string * typ list) list)
    52       -> theory -> theory) -> theory -> theory
    53   val add_abstype: thm -> theory -> theory
    54   val abstype_interpretation:
    55     (string * ((string * sort) list * ((string * typ) * (string * thm)))
    56       -> theory -> theory) -> theory -> theory
    57   val add_eqn: thm -> theory -> theory
    58   val add_nbe_eqn: thm -> theory -> theory
    59   val add_default_eqn: thm -> theory -> theory
    60   val add_default_eqn_attribute: attribute
    61   val add_default_eqn_attrib: Attrib.src
    62   val del_eqn: thm -> theory -> theory
    63   val del_eqns: string -> theory -> theory
    64   val add_case: thm -> theory -> theory
    65   val add_undefined: string -> theory -> theory
    66   val get_type: theory -> string -> ((string * sort) list * (string * typ list) list)
    67   val get_type_of_constr_or_abstr: theory -> string -> (string * bool) option
    68   val is_constr: theory -> string -> bool
    69   val is_abstr: theory -> string -> bool
    70   val get_cert: theory -> ((thm * bool) list -> (thm * bool) list) -> string -> cert
    71   val get_case_scheme: theory -> string -> (int * (int * string list)) option
    72   val undefineds: theory -> string list
    73   val print_codesetup: theory -> unit
    74 
    75   (*infrastructure*)
    76   val set_code_target_attr: (string -> thm -> theory -> theory) -> theory -> theory
    77   val purge_data: theory -> theory
    78 end;
    79 
    80 signature CODE_DATA_ARGS =
    81 sig
    82   type T
    83   val empty: T
    84 end;
    85 
    86 signature CODE_DATA =
    87 sig
    88   type T
    89   val change: theory -> (T -> T) -> T
    90   val change_yield: theory -> (T -> 'a * T) -> 'a * T
    91 end;
    92 
    93 signature PRIVATE_CODE =
    94 sig
    95   include CODE
    96   val declare_data: Object.T -> serial
    97   val change_data: serial * ('a -> Object.T) * (Object.T -> 'a)
    98     -> theory -> ('a -> 'a) -> 'a
    99   val change_yield_data: serial * ('a -> Object.T) * (Object.T -> 'a)
   100     -> theory -> ('a -> 'b * 'a) -> 'b * 'a
   101 end;
   102 
   103 structure Code : PRIVATE_CODE =
   104 struct
   105 
   106 (** auxiliary **)
   107 
   108 (* printing *)
   109 
   110 fun string_of_typ thy = setmp_CRITICAL show_sorts true (Syntax.string_of_typ_global thy);
   111 
   112 fun string_of_const thy c = case AxClass.inst_of_param thy c
   113  of SOME (c, tyco) => Sign.extern_const thy c ^ " " ^ enclose "[" "]" (Sign.extern_type thy tyco)
   114   | NONE => Sign.extern_const thy c;
   115 
   116 
   117 (* constants *)
   118 
   119 fun typ_equiv tys = Type.raw_instance tys andalso Type.raw_instance (swap tys);
   120 
   121 fun check_bare_const thy t = case try dest_Const t
   122  of SOME c_ty => c_ty
   123   | NONE => error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
   124 
   125 fun check_const thy = AxClass.unoverload_const thy o check_bare_const thy;
   126 
   127 fun read_bare_const thy = check_bare_const thy o Syntax.read_term_global thy;
   128 
   129 fun read_const thy = AxClass.unoverload_const thy o read_bare_const thy;
   130 
   131 
   132 (** data store **)
   133 
   134 (* datatypes *)
   135 
   136 datatype typ_spec = Constructors of (string * typ list) list
   137   | Abstractor of (string * typ) * (string * thm);
   138 
   139 fun constructors_of (Constructors cos) = (cos, false)
   140   | constructors_of (Abstractor ((co, ty), _)) = ([(co, [ty])], true);
   141 
   142 
   143 (* functions *)
   144 
   145 datatype fun_spec = Default of (thm * bool) list
   146   | Eqns of (thm * bool) list
   147   | Proj of term * string
   148   | Abstr of thm * string;
   149 
   150 val empty_fun_spec = Default [];
   151 
   152 fun is_default (Default _) = true
   153   | is_default _ = false;
   154 
   155 fun associated_abstype (Abstr (_, tyco)) = SOME tyco
   156   | associated_abstype _ = NONE;
   157 
   158 
   159 (* executable code data *)
   160 
   161 datatype spec = Spec of {
   162   history_concluded: bool,
   163   signatures: int Symtab.table * typ Symtab.table,
   164   functions: ((bool * fun_spec) * (serial * fun_spec) list) Symtab.table
   165     (*with explicit history*),
   166   types: ((serial * ((string * sort) list * typ_spec)) list) Symtab.table
   167     (*with explicit history*),
   168   cases: (int * (int * string list)) Symtab.table * unit Symtab.table
   169 };
   170 
   171 fun make_spec (history_concluded, ((signatures, functions), (types, cases))) =
   172   Spec { history_concluded = history_concluded,
   173     signatures = signatures, functions = functions, types = types, cases = cases };
   174 fun map_spec f (Spec { history_concluded = history_concluded, signatures = signatures,
   175   functions = functions, types = types, cases = cases }) =
   176   make_spec (f (history_concluded, ((signatures, functions), (types, cases))));
   177 fun merge_spec (Spec { history_concluded = _, signatures = (tycos1, sigs1), functions = functions1,
   178     types = types1, cases = (cases1, undefs1) },
   179   Spec { history_concluded = _, signatures = (tycos2, sigs2), functions = functions2,
   180     types = types2, cases = (cases2, undefs2) }) =
   181   let
   182     val signatures = (Symtab.merge (op =) (tycos1, tycos2),
   183       Symtab.merge typ_equiv (sigs1, sigs2));
   184     fun merge_functions ((_, history1), (_, history2)) =
   185       let
   186         val raw_history = AList.merge (op = : serial * serial -> bool)
   187           (K true) (history1, history2);
   188         val filtered_history = filter_out (is_default o snd) raw_history;
   189         val history = if null filtered_history
   190           then raw_history else filtered_history;
   191       in ((false, (snd o hd) history), history) end;
   192     val functions = Symtab.join (K merge_functions) (functions1, functions2);
   193     val types = Symtab.join (K (AList.merge (op =) (K true))) (types1, types2);
   194     val cases = (Symtab.merge (K true) (cases1, cases2),
   195       Symtab.merge (K true) (undefs1, undefs2));
   196   in make_spec (false, ((signatures, functions), (types, cases))) end;
   197 
   198 fun history_concluded (Spec { history_concluded, ... }) = history_concluded;
   199 fun the_signatures (Spec { signatures, ... }) = signatures;
   200 fun the_functions (Spec { functions, ... }) = functions;
   201 fun the_types (Spec { types, ... }) = types;
   202 fun the_cases (Spec { cases, ... }) = cases;
   203 val map_history_concluded = map_spec o apfst;
   204 val map_signatures = map_spec o apsnd o apfst o apfst;
   205 val map_functions = map_spec o apsnd o apfst o apsnd;
   206 val map_typs = map_spec o apsnd o apsnd o apfst;
   207 val map_cases = map_spec o apsnd o apsnd o apsnd;
   208 
   209 
   210 (* data slots dependent on executable code *)
   211 
   212 (*private copy avoids potential conflict of table exceptions*)
   213 structure Datatab = Table(type key = int val ord = int_ord);
   214 
   215 local
   216 
   217 type kind = { empty: Object.T };
   218 
   219 val kinds = Unsynchronized.ref (Datatab.empty: kind Datatab.table);
   220 
   221 fun invoke f k = case Datatab.lookup (! kinds) k
   222  of SOME kind => f kind
   223   | NONE => sys_error "Invalid code data identifier";
   224 
   225 in
   226 
   227 fun declare_data empty =
   228   let
   229     val k = serial ();
   230     val kind = { empty = empty };
   231     val _ = CRITICAL (fn () => Unsynchronized.change kinds (Datatab.update (k, kind)));
   232   in k end;
   233 
   234 fun invoke_init k = invoke (fn kind => #empty kind) k;
   235 
   236 end; (*local*)
   237 
   238 
   239 (* theory store *)
   240 
   241 local
   242 
   243 type data = Object.T Datatab.table;
   244 fun empty_dataref () = Synchronized.var "code data" (NONE : (data * theory_ref) option);
   245 
   246 structure Code_Data = Theory_Data
   247 (
   248   type T = spec * (data * theory_ref) option Synchronized.var;
   249   val empty = (make_spec (false, (((Symtab.empty, Symtab.empty), Symtab.empty),
   250     (Symtab.empty, (Symtab.empty, Symtab.empty)))), empty_dataref ());
   251   val extend = I
   252   fun merge ((spec1, _), (spec2, _)) =
   253     (merge_spec (spec1, spec2), empty_dataref ());
   254 );
   255 
   256 in
   257 
   258 
   259 (* access to executable code *)
   260 
   261 val the_exec = fst o Code_Data.get;
   262 
   263 fun map_exec_purge f = Code_Data.map (fn (exec, _) => (f exec, empty_dataref ()));
   264 
   265 val purge_data = (Code_Data.map o apsnd) (fn _ => empty_dataref ());
   266 
   267 fun change_fun_spec delete c f = (map_exec_purge o map_functions
   268   o (if delete then Symtab.map_entry c else Symtab.map_default (c, ((false, empty_fun_spec), [])))
   269     o apfst) (fn (_, spec) => (true, f spec));
   270 
   271 
   272 (* tackling equation history *)
   273 
   274 fun continue_history thy = if (history_concluded o the_exec) thy
   275   then thy
   276     |> (Code_Data.map o apfst o map_history_concluded) (K false)
   277     |> SOME
   278   else NONE;
   279 
   280 fun conclude_history thy = if (history_concluded o the_exec) thy
   281   then NONE
   282   else thy
   283     |> (Code_Data.map o apfst)
   284         ((map_functions o Symtab.map) (fn ((changed, current), history) =>
   285           ((false, current),
   286             if changed then (serial (), current) :: history else history))
   287         #> map_history_concluded (K true))
   288     |> SOME;
   289 
   290 val _ = Context.>> (Context.map_theory (Theory.at_begin continue_history #> Theory.at_end conclude_history));
   291 
   292 
   293 (* access to data dependent on abstract executable code *)
   294 
   295 fun change_yield_data (kind, mk, dest) theory f =
   296   let
   297     val dataref = (snd o Code_Data.get) theory;
   298     val (datatab, thy_ref) = case Synchronized.value dataref
   299      of SOME (datatab, thy_ref) => if Theory.eq_thy (theory, Theory.deref thy_ref)
   300           then (datatab, thy_ref)
   301           else (Datatab.empty, Theory.check_thy theory)
   302       | NONE => (Datatab.empty, Theory.check_thy theory)
   303     val data = case Datatab.lookup datatab kind
   304      of SOME data => data
   305       | NONE => invoke_init kind;
   306     val result as (x, data') = f (dest data);
   307     val _ = Synchronized.change dataref
   308       ((K o SOME) (Datatab.update (kind, mk data') datatab, thy_ref));
   309   in result end;
   310 
   311 fun change_data ops theory f = change_yield_data ops theory (f #> pair ()) |> snd;
   312 
   313 end; (*local*)
   314 
   315 
   316 (** foundation **)
   317 
   318 (* constants *)
   319 
   320 fun arity_number thy tyco = case Symtab.lookup ((fst o the_signatures o the_exec) thy) tyco
   321  of SOME n => n
   322   | NONE => Sign.arity_number thy tyco;
   323 
   324 fun build_tsig thy =
   325   let
   326     val (tycos, _) = (the_signatures o the_exec) thy;
   327     val decls = (#types o Type.rep_tsig o Sign.tsig_of) thy
   328       |> snd 
   329       |> Symtab.fold (fn (tyco, n) =>
   330           Symtab.update (tyco, Type.LogicalType n)) tycos;
   331   in
   332     Type.empty_tsig
   333     |> Symtab.fold (fn (tyco, Type.LogicalType n) => Type.add_type Name_Space.default_naming
   334         (Binding.qualified_name tyco, n) | _ => I) decls
   335   end;
   336 
   337 fun cert_signature thy = Logic.varifyT_global o Type.cert_typ (build_tsig thy) o Type.no_tvars;
   338 
   339 fun read_signature thy = cert_signature thy o Type.strip_sorts
   340   o Syntax.parse_typ (ProofContext.init_global thy);
   341 
   342 fun expand_signature thy = Type.cert_typ_mode Type.mode_syntax (Sign.tsig_of thy);
   343 
   344 fun lookup_typ thy = Symtab.lookup ((snd o the_signatures o the_exec) thy);
   345 
   346 fun const_typ thy c = case lookup_typ thy c
   347  of SOME ty => ty
   348   | NONE => (Type.strip_sorts o Sign.the_const_type thy) c;
   349 
   350 fun subst_signature thy c ty =
   351   let
   352     fun mk_subst (Type (tyco, tys1)) (ty2 as Type (tyco2, tys2)) =
   353           fold2 mk_subst tys1 tys2
   354       | mk_subst ty (TVar (v, sort)) = Vartab.update (v, ([], ty))
   355   in case lookup_typ thy c
   356    of SOME ty' => Envir.subst_type (mk_subst ty (expand_signature thy ty') Vartab.empty) ty'
   357     | NONE => ty
   358   end;
   359 
   360 fun subst_signatures thy = map_aterms (fn Const (c, ty) => Const (c, subst_signature thy c ty) | t => t);
   361 
   362 fun args_number thy = length o fst o strip_type o const_typ thy;
   363 
   364 
   365 (* datatypes *)
   366 
   367 fun no_constr thy s (c, ty) = error ("Not a datatype constructor:\n" ^ string_of_const thy c
   368   ^ " :: " ^ string_of_typ thy ty ^ "\n" ^ enclose "(" ")" s);
   369 
   370 fun ty_sorts thy (c, raw_ty) =
   371   let
   372     val _ = Thm.cterm_of thy (Const (c, raw_ty));
   373     val ty = subst_signature thy c raw_ty;
   374     val ty_decl = (Logic.unvarifyT_global o const_typ thy) c;
   375     fun last_typ c_ty ty =
   376       let
   377         val tfrees = Term.add_tfreesT ty [];
   378         val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) ty
   379           handle TYPE _ => no_constr thy "bad type" c_ty
   380         val _ = if tyco = "fun" then no_constr thy "bad type" c_ty else ();
   381         val _ = if has_duplicates (eq_fst (op =)) vs
   382           then no_constr thy "duplicate type variables in datatype" c_ty else ();
   383         val _ = if length tfrees <> length vs
   384           then no_constr thy "type variables missing in datatype" c_ty else ();
   385       in (tyco, vs) end;
   386     val (tyco, _) = last_typ (c, ty) ty_decl;
   387     val (_, vs) = last_typ (c, ty) ty;
   388   in ((tyco, map snd vs), (c, (map fst vs, ty))) end;
   389 
   390 fun constrset_of_consts thy cs =
   391   let
   392     val _ = map (fn (c, _) => if (is_some o AxClass.class_of_param thy) c
   393       then error ("Is a class parameter: " ^ string_of_const thy c) else ()) cs;
   394     fun add ((tyco', sorts'), c) ((tyco, sorts), cs) =
   395       let
   396         val _ = if (tyco' : string) <> tyco
   397           then error "Different type constructors in constructor set"
   398           else ();
   399         val sorts'' = map2 (curry (Sorts.inter_sort (Sign.classes_of thy))) sorts' sorts
   400       in ((tyco, sorts), c :: cs) end;
   401     fun inst vs' (c, (vs, ty)) =
   402       let
   403         val the_v = the o AList.lookup (op =) (vs ~~ vs');
   404         val ty' = map_atyps (fn TFree (v, _) => TFree (the_v v)) ty;
   405       in (c, (fst o strip_type) ty') end;
   406     val c' :: cs' = map (ty_sorts thy) cs;
   407     val ((tyco, sorts), cs'') = fold add cs' (apsnd single c');
   408     val vs = Name.names Name.context Name.aT sorts;
   409     val cs''' = map (inst vs) cs'';
   410   in (tyco, (vs, rev cs''')) end;
   411 
   412 fun get_type_entry thy tyco = case these (Symtab.lookup ((the_types o the_exec) thy) tyco)
   413  of (_, entry) :: _ => SOME entry
   414   | _ => NONE;
   415 
   416 fun get_type_spec thy tyco = case get_type_entry thy tyco
   417  of SOME (vs, spec) => apfst (pair vs) (constructors_of spec)
   418   | NONE => arity_number thy tyco
   419       |> Name.invents Name.context Name.aT
   420       |> map (rpair [])
   421       |> rpair []
   422       |> rpair false;
   423 
   424 fun get_abstype_spec thy tyco = case get_type_entry thy tyco
   425  of SOME (vs, Abstractor spec) => (vs, spec)
   426   | _ => error ("Not an abstract type: " ^ tyco);
   427  
   428 fun get_type thy = fst o get_type_spec thy;
   429 
   430 fun get_type_of_constr_or_abstr thy c =
   431   case (snd o strip_type o const_typ thy) c
   432    of Type (tyco, _) => let val ((vs, cos), abstract) = get_type_spec thy tyco
   433         in if member (op =) (map fst cos) c then SOME (tyco, abstract) else NONE end
   434     | _ => NONE;
   435 
   436 fun is_constr thy c = case get_type_of_constr_or_abstr thy c
   437  of SOME (_, false) => true
   438    | _ => false;
   439 
   440 fun is_abstr thy c = case get_type_of_constr_or_abstr thy c
   441  of SOME (_, true) => true
   442    | _ => false;
   443 
   444 
   445 (* bare code equations *)
   446 
   447 (* convention for variables:
   448     ?x ?'a   for free-floating theorems (e.g. in the data store)
   449     ?x  'a   for certificates
   450      x  'a   for final representation of equations
   451 *)
   452 
   453 exception BAD_THM of string;
   454 fun bad_thm msg = raise BAD_THM msg;
   455 fun error_thm f thm = f thm handle BAD_THM msg => error msg;
   456 fun warning_thm f thm = SOME (f thm) handle BAD_THM msg => (warning msg; NONE)
   457 fun try_thm f thm = SOME (f thm) handle BAD_THM _ => NONE;
   458 
   459 fun is_linear thm =
   460   let val (_, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm
   461   in not (has_duplicates (op =) ((fold o fold_aterms)
   462     (fn Var (v, _) => cons v | _ => I) args [])) end;
   463 
   464 fun check_decl_ty thy (c, ty) =
   465   let
   466     val ty_decl = Sign.the_const_type thy c;
   467   in if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty) then ()
   468     else bad_thm ("Type\n" ^ string_of_typ thy ty
   469       ^ "\nof constant " ^ quote c
   470       ^ "\nis incompatible with declared type\n"
   471       ^ string_of_typ thy ty_decl)
   472   end; 
   473 
   474 fun check_eqn thy { allow_nonlinear, allow_consts, allow_pats } thm (lhs, rhs) =
   475   let
   476     fun bad s = bad_thm (s ^ ":\n" ^ Display.string_of_thm_global thy thm);
   477     fun vars_of t = fold_aterms (fn Var (v, _) => insert (op =) v
   478       | Free _ => bad "Illegal free variable in equation"
   479       | _ => I) t [];
   480     fun tvars_of t = fold_term_types (fn _ =>
   481       fold_atyps (fn TVar (v, _) => insert (op =) v
   482         | TFree _ => bad "Illegal free type variable in equation")) t [];
   483     val lhs_vs = vars_of lhs;
   484     val rhs_vs = vars_of rhs;
   485     val lhs_tvs = tvars_of lhs;
   486     val rhs_tvs = tvars_of rhs;
   487     val _ = if null (subtract (op =) lhs_vs rhs_vs)
   488       then ()
   489       else bad "Free variables on right hand side of equation";
   490     val _ = if null (subtract (op =) lhs_tvs rhs_tvs)
   491       then ()
   492       else bad "Free type variables on right hand side of equation";
   493     val (head, args) = strip_comb lhs;
   494     val (c, ty) = case head
   495      of Const (c_ty as (_, ty)) => (AxClass.unoverload_const thy c_ty, ty)
   496       | _ => bad "Equation not headed by constant";
   497     fun check _ (Abs _) = bad "Abstraction on left hand side of equation"
   498       | check 0 (Var _) = ()
   499       | check _ (Var _) = bad "Variable with application on left hand side of equation"
   500       | check n (t1 $ t2) = (check (n+1) t1; check 0 t2)
   501       | check n (Const (c_ty as (c, ty))) =
   502           if allow_pats then let
   503             val c' = AxClass.unoverload_const thy c_ty
   504           in if n = (length o fst o strip_type o subst_signature thy c') ty
   505             then if allow_consts orelse is_constr thy c'
   506               then ()
   507               else bad (quote c ^ " is not a constructor, on left hand side of equation")
   508             else bad ("Partially applied constant " ^ quote c ^ " on left hand side of equation")
   509           end else bad ("Pattern not allowed here, but constant " ^ quote c ^ " encountered on left hand side")
   510     val _ = map (check 0) args;
   511     val _ = if allow_nonlinear orelse is_linear thm then ()
   512       else bad "Duplicate variables on left hand side of equation";
   513     val _ = if (is_none o AxClass.class_of_param thy) c then ()
   514       else bad "Overloaded constant as head in equation";
   515     val _ = if not (is_constr thy c) then ()
   516       else bad "Constructor as head in equation";
   517     val _ = if not (is_abstr thy c) then ()
   518       else bad "Abstractor as head in equation";
   519     val _ = check_decl_ty thy (c, ty);
   520   in () end;
   521 
   522 fun gen_assert_eqn thy check_patterns (thm, proper) =
   523   let
   524     fun bad s = bad_thm (s ^ ":\n" ^ Display.string_of_thm_global thy thm);
   525     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm
   526       handle TERM _ => bad "Not an equation"
   527            | THM _ => bad "Not a proper equation";
   528     val _ = check_eqn thy { allow_nonlinear = not proper,
   529       allow_consts = not (proper andalso check_patterns), allow_pats = true } thm (lhs, rhs);
   530   in (thm, proper) end;
   531 
   532 fun assert_abs_eqn thy some_tyco thm =
   533   let
   534     fun bad s = bad_thm (s ^ ":\n" ^ Display.string_of_thm_global thy thm);
   535     val (full_lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm
   536       handle TERM _ => bad "Not an equation"
   537            | THM _ => bad "Not a proper equation";
   538     val (rep, lhs) = dest_comb full_lhs
   539       handle TERM _ => bad "Not an abstract equation";
   540     val (rep_const, ty) = dest_Const rep;
   541     val (tyco, sorts) = ((apsnd o map) (snd o dest_TVar) o dest_Type o domain_type) ty
   542       handle TERM _ => bad "Not an abstract equation";
   543     val _ = case some_tyco of SOME tyco' => if tyco = tyco' then ()
   544           else bad ("Abstract type mismatch:" ^ quote tyco ^ " vs. " ^ quote tyco')
   545       | NONE => ();
   546     val (vs', (_, (rep', _))) = get_abstype_spec thy tyco;
   547     val _ = if rep_const = rep' then ()
   548       else bad ("Projection mismatch: " ^ quote rep_const ^ " vs. " ^ quote rep');
   549     val _ = check_eqn thy { allow_nonlinear = false,
   550       allow_consts = false, allow_pats = false } thm (lhs, rhs);
   551     val _ = if forall (Sign.subsort thy) (sorts ~~ map snd  vs') then ()
   552       else error ("Sort constraints on type arguments are weaker than in abstype certificate.")
   553   in (thm, tyco) end;
   554 
   555 fun assert_eqn thy = error_thm (gen_assert_eqn thy true);
   556 
   557 fun meta_rewrite thy = Local_Defs.meta_rewrite_rule (ProofContext.init_global thy);
   558 
   559 fun mk_eqn thy = error_thm (gen_assert_eqn thy false) o
   560   apfst (meta_rewrite thy);
   561 
   562 fun mk_eqn_warning thy = Option.map (fn (thm, _) => (thm, is_linear thm))
   563   o warning_thm (gen_assert_eqn thy false) o rpair false o meta_rewrite thy;
   564 
   565 fun mk_eqn_liberal thy = Option.map (fn (thm, _) => (thm, is_linear thm))
   566   o try_thm (gen_assert_eqn thy false) o rpair false o meta_rewrite thy;
   567 
   568 fun mk_abs_eqn thy = error_thm (assert_abs_eqn thy NONE) o meta_rewrite thy;
   569 
   570 val head_eqn = dest_Const o fst o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
   571 
   572 fun const_typ_eqn thy thm =
   573   let
   574     val (c, ty) = head_eqn thm;
   575     val c' = AxClass.unoverload_const thy (c, ty);
   576       (*permissive wrt. to overloaded constants!*)
   577   in (c', ty) end;
   578 
   579 fun const_eqn thy = fst o const_typ_eqn thy;
   580 
   581 fun const_abs_eqn thy = AxClass.unoverload_const thy o dest_Const o fst o strip_comb o snd
   582   o dest_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
   583 
   584 fun logical_typscheme thy (c, ty) =
   585   (map dest_TFree (Sign.const_typargs thy (c, ty)), Type.strip_sorts ty);
   586 
   587 fun typscheme thy (c, ty) = logical_typscheme thy (c, subst_signature thy c ty);
   588 
   589 fun mk_proj tyco vs ty abs rep =
   590   let
   591     val ty_abs = Type (tyco, map TFree vs);
   592     val xarg = Var (("x", 0), ty);
   593   in Logic.mk_equals (Const (rep, ty_abs --> ty) $ (Const (abs, ty --> ty_abs) $ xarg), xarg) end;
   594 
   595 
   596 (* technical transformations of code equations *)
   597 
   598 fun expand_eta thy k thm =
   599   let
   600     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm;
   601     val (_, args) = strip_comb lhs;
   602     val l = if k = ~1
   603       then (length o fst o strip_abs) rhs
   604       else Int.max (0, k - length args);
   605     val (raw_vars, _) = Term.strip_abs_eta l rhs;
   606     val vars = burrow_fst (Name.variant_list (map (fst o fst) (Term.add_vars lhs [])))
   607       raw_vars;
   608     fun expand (v, ty) thm = Drule.fun_cong_rule thm
   609       (Thm.cterm_of thy (Var ((v, 0), ty)));
   610   in
   611     thm
   612     |> fold expand vars
   613     |> Conv.fconv_rule Drule.beta_eta_conversion
   614   end;
   615 
   616 fun same_arity thy thms =
   617   let
   618     val num_args_of = length o snd o strip_comb o fst o Logic.dest_equals;
   619     val k = fold (Integer.max o num_args_of o Thm.prop_of) thms 0;
   620   in map (expand_eta thy k) thms end;
   621 
   622 fun mk_desymbolization pre post mk vs =
   623   let
   624     val names = map (pre o fst o fst) vs
   625       |> map (Name.desymbolize false)
   626       |> Name.variant_list []
   627       |> map post;
   628   in map_filter (fn (((v, i), x), v') =>
   629     if v = v' andalso i = 0 then NONE
   630     else SOME (((v, i), x), mk ((v', 0), x))) (vs ~~ names)
   631   end;
   632 
   633 fun desymbolize_tvars thy thms =
   634   let
   635     val tvs = fold (Term.add_tvars o Thm.prop_of) thms [];
   636     val tvar_subst = mk_desymbolization (unprefix "'") (prefix "'") TVar tvs;
   637   in map (Thm.certify_instantiate (tvar_subst, [])) thms end;
   638 
   639 fun desymbolize_vars thy thm =
   640   let
   641     val vs = Term.add_vars (Thm.prop_of thm) [];
   642     val var_subst = mk_desymbolization I I Var vs;
   643   in Thm.certify_instantiate ([], var_subst) thm end;
   644 
   645 fun canonize_thms thy = desymbolize_tvars thy #> same_arity thy #> map (desymbolize_vars thy);
   646 
   647 
   648 (* abstype certificates *)
   649 
   650 fun check_abstype_cert thy proto_thm =
   651   let
   652     val thm = (AxClass.unoverload thy o meta_rewrite thy) proto_thm;
   653     fun bad s = bad_thm (s ^ ":\n" ^ Display.string_of_thm_global thy thm);
   654     val (lhs, rhs) = Logic.dest_equals (Thm.plain_prop_of thm)
   655       handle TERM _ => bad "Not an equation"
   656            | THM _ => bad "Not a proper equation";
   657     val ((abs, raw_ty), ((rep, rep_ty), param)) = (apsnd (apfst dest_Const o dest_comb)
   658         o apfst dest_Const o dest_comb) lhs
   659       handle TERM _ => bad "Not an abstype certificate";
   660     val _ = pairself (fn c => if (is_some o AxClass.class_of_param thy) c
   661       then error ("Is a class parameter: " ^ string_of_const thy c) else ()) (abs, rep);
   662     val _ = check_decl_ty thy (abs, raw_ty);
   663     val _ = check_decl_ty thy (rep, rep_ty);
   664     val var = (fst o dest_Var) param
   665       handle TERM _ => bad "Not an abstype certificate";
   666     val _ = if param = rhs then () else bad "Not an abstype certificate";
   667     val ((tyco, sorts), (abs, (vs, ty'))) = ty_sorts thy (abs, Logic.unvarifyT_global raw_ty);
   668     val ty = domain_type ty';
   669     val ty_abs = range_type ty';
   670   in (tyco, (vs ~~ sorts, ((abs, ty), (rep, thm)))) end;
   671 
   672 
   673 (* code equation certificates *)
   674 
   675 fun build_head thy (c, ty) =
   676   Thm.cterm_of thy (Logic.mk_equals (Free ("HEAD", ty), Const (c, ty)));
   677 
   678 fun get_head thy cert_thm =
   679   let
   680     val [head] = (#hyps o Thm.crep_thm) cert_thm;
   681     val (_, Const (c, ty)) = (Logic.dest_equals o Thm.term_of) head;
   682   in (typscheme thy (c, ty), head) end;
   683 
   684 fun typscheme_projection thy =
   685   typscheme thy o dest_Const o fst o dest_comb o fst o Logic.dest_equals;
   686 
   687 fun typscheme_abs thy =
   688   typscheme thy o dest_Const o fst o strip_comb o snd o dest_comb o fst o Logic.dest_equals o Thm.prop_of;
   689 
   690 fun constrain_thm thy vs sorts thm =
   691   let
   692     val mapping = map2 (fn (v, sort) => fn sort' =>
   693       (v, Sorts.inter_sort (Sign.classes_of thy) (sort, sort'))) vs sorts;
   694     val inst = map2 (fn (v, sort) => fn (_, sort') =>
   695       (((v, 0), sort), TFree (v, sort'))) vs mapping;
   696     val subst = (map_types o map_atyps)
   697       (fn TFree (v, _) => TFree (v, the (AList.lookup (op =) mapping v)));
   698   in
   699     thm
   700     |> Thm.varifyT_global
   701     |> Thm.certify_instantiate (inst, [])
   702     |> pair subst
   703   end;
   704 
   705 fun concretify_abs thy tyco abs_thm =
   706   let
   707     val (vs, ((c, _), (_, cert))) = get_abstype_spec thy tyco;
   708     val lhs = (fst o Logic.dest_equals o Thm.prop_of) abs_thm
   709     val ty = fastype_of lhs;
   710     val ty_abs = (fastype_of o snd o dest_comb) lhs;
   711     val abs = Thm.cterm_of thy (Const (c, ty --> ty_abs));
   712     val raw_concrete_thm = Drule.transitive_thm OF [Thm.symmetric cert, Thm.combination (Thm.reflexive abs) abs_thm];
   713   in (c, (Thm.varifyT_global o zero_var_indexes) raw_concrete_thm) end;
   714 
   715 fun add_rhss_of_eqn thy t =
   716   let
   717     val (args, rhs) = (apfst (snd o strip_comb) o Logic.dest_equals o subst_signatures thy) t;
   718     fun add_const (Const (c, ty)) = insert (op =) (c, Sign.const_typargs thy (c, ty))
   719       | add_const _ = I
   720   in fold_aterms add_const t end;
   721 
   722 fun dest_eqn thy =
   723   apfst (snd o strip_comb) o Logic.dest_equals o subst_signatures thy o Logic.unvarify_global;
   724 
   725 abstype cert = Equations of thm * bool list
   726   | Projection of term * string
   727   | Abstract of thm * string
   728 with
   729 
   730 fun empty_cert thy c = 
   731   let
   732     val raw_ty = const_typ thy c;
   733     val tvars = Term.add_tvar_namesT raw_ty [];
   734     val tvars' = case AxClass.class_of_param thy c
   735      of SOME class => [TFree (Name.aT, [class])]
   736       | NONE => Name.invent_list [] Name.aT (length tvars)
   737           |> map (fn v => TFree (v, []));
   738     val ty = typ_subst_TVars (tvars ~~ tvars') raw_ty;
   739     val chead = build_head thy (c, ty);
   740   in Equations (Thm.weaken chead Drule.dummy_thm, []) end;
   741 
   742 fun cert_of_eqns thy c [] = empty_cert thy c
   743   | cert_of_eqns thy c raw_eqns = 
   744       let
   745         val eqns = burrow_fst (canonize_thms thy) raw_eqns;
   746         val _ = map (assert_eqn thy) eqns;
   747         val (thms, propers) = split_list eqns;
   748         val _ = map (fn thm => if c = const_eqn thy thm then ()
   749           else error ("Wrong head of code equation,\nexpected constant "
   750             ^ string_of_const thy c ^ "\n" ^ Display.string_of_thm_global thy thm)) thms;
   751         fun tvars_of T = rev (Term.add_tvarsT T []);
   752         val vss = map (tvars_of o snd o head_eqn) thms;
   753         fun inter_sorts vs =
   754           fold (curry (Sorts.inter_sort (Sign.classes_of thy)) o snd) vs [];
   755         val sorts = map_transpose inter_sorts vss;
   756         val vts = Name.names Name.context Name.aT sorts;
   757         val thms as thm :: _ =
   758           map2 (fn vs => Thm.certify_instantiate (vs ~~ map TFree vts, [])) vss thms;
   759         val head_thm = Thm.symmetric (Thm.assume (build_head thy (head_eqn (hd thms))));
   760         fun head_conv ct = if can Thm.dest_comb ct
   761           then Conv.fun_conv head_conv ct
   762           else Conv.rewr_conv head_thm ct;
   763         val rewrite_head = Conv.fconv_rule (Conv.arg1_conv head_conv);
   764         val cert_thm = Conjunction.intr_balanced (map rewrite_head thms);
   765       in Equations (cert_thm, propers) end;
   766 
   767 fun cert_of_proj thy c tyco =
   768   let
   769     val (vs, ((abs, ty), (rep, cert))) = get_abstype_spec thy tyco;
   770     val _ = if c = rep then () else
   771       error ("Wrong head of projection,\nexpected constant " ^ string_of_const thy rep);
   772   in Projection (mk_proj tyco vs ty abs rep, tyco) end;
   773 
   774 fun cert_of_abs thy tyco c raw_abs_thm =
   775   let
   776     val abs_thm = singleton (canonize_thms thy) raw_abs_thm;
   777     val _ = assert_abs_eqn thy (SOME tyco) abs_thm;
   778     val _ = if c = const_abs_eqn thy abs_thm then ()
   779       else error ("Wrong head of abstract code equation,\nexpected constant "
   780         ^ string_of_const thy c ^ "\n" ^ Display.string_of_thm_global thy abs_thm);
   781   in Abstract (Thm.legacy_freezeT abs_thm, tyco) end;
   782 
   783 fun constrain_cert thy sorts (Equations (cert_thm, propers)) =
   784       let
   785         val ((vs, _), head) = get_head thy cert_thm;
   786         val (subst, cert_thm') = cert_thm
   787           |> Thm.implies_intr head
   788           |> constrain_thm thy vs sorts;
   789         val head' = Thm.term_of head
   790           |> subst
   791           |> Thm.cterm_of thy;
   792         val cert_thm'' = cert_thm'
   793           |> Thm.elim_implies (Thm.assume head');
   794       in Equations (cert_thm'', propers) end
   795   | constrain_cert thy _ (cert as Projection _) =
   796       cert
   797   | constrain_cert thy sorts (Abstract (abs_thm, tyco)) =
   798       Abstract (snd (constrain_thm thy (fst (typscheme_abs thy abs_thm)) sorts abs_thm), tyco);
   799 
   800 fun typscheme_of_cert thy (Equations (cert_thm, _)) =
   801       fst (get_head thy cert_thm)
   802   | typscheme_of_cert thy (Projection (proj, _)) =
   803       typscheme_projection thy proj
   804   | typscheme_of_cert thy (Abstract (abs_thm, _)) =
   805       typscheme_abs thy abs_thm;
   806 
   807 fun typargs_deps_of_cert thy (Equations (cert_thm, propers)) =
   808       let
   809         val vs = (fst o fst) (get_head thy cert_thm);
   810         val equations = if null propers then [] else
   811           Thm.prop_of cert_thm
   812           |> Logic.dest_conjunction_balanced (length propers);
   813       in (vs, fold (add_rhss_of_eqn thy) equations []) end
   814   | typargs_deps_of_cert thy (Projection (t, tyco)) =
   815       (fst (typscheme_projection thy t), add_rhss_of_eqn thy t [])
   816   | typargs_deps_of_cert thy (Abstract (abs_thm, tyco)) =
   817       let
   818         val vs = fst (typscheme_abs thy abs_thm);
   819         val (_, concrete_thm) = concretify_abs thy tyco abs_thm;
   820       in (vs, add_rhss_of_eqn thy (map_types Logic.unvarifyT_global (Thm.prop_of concrete_thm)) []) end;
   821 
   822 fun equations_of_cert thy (cert as Equations (cert_thm, propers)) =
   823       let
   824         val tyscm = typscheme_of_cert thy cert;
   825         val thms = if null propers then [] else
   826           cert_thm
   827           |> Local_Defs.expand [snd (get_head thy cert_thm)]
   828           |> Thm.varifyT_global
   829           |> Conjunction.elim_balanced (length propers);
   830         fun abstractions (args, rhs) = (map (rpair NONE) args, (rhs, NONE));
   831       in (tyscm, map (abstractions o dest_eqn thy o Thm.prop_of) thms ~~ (map SOME thms ~~ propers)) end
   832   | equations_of_cert thy (Projection (t, tyco)) =
   833       let
   834         val (_, ((abs, _), _)) = get_abstype_spec thy tyco;
   835         val tyscm = typscheme_projection thy t;
   836         val t' = map_types Logic.varifyT_global t;
   837         fun abstractions (args, rhs) = (map (rpair (SOME abs)) args, (rhs, NONE));
   838       in (tyscm, [((abstractions o dest_eqn thy) t', (NONE, true))]) end
   839   | equations_of_cert thy (Abstract (abs_thm, tyco)) =
   840       let
   841         val tyscm = typscheme_abs thy abs_thm;
   842         val (abs, concrete_thm) = concretify_abs thy tyco abs_thm;
   843         fun abstractions (args, rhs) = (map (rpair NONE) args, (rhs, (SOME abs)));
   844       in
   845         (tyscm, [((abstractions o dest_eqn thy o Thm.prop_of) concrete_thm,
   846           (SOME (Thm.varifyT_global abs_thm), true))])
   847       end;
   848 
   849 fun pretty_cert thy (cert as Equations _) =
   850       (map_filter (Option.map (Display.pretty_thm_global thy o AxClass.overload thy) o fst o snd)
   851          o snd o equations_of_cert thy) cert
   852   | pretty_cert thy (Projection (t, _)) =
   853       [Syntax.pretty_term_global thy (map_types Logic.varifyT_global t)]
   854   | pretty_cert thy (Abstract (abs_thm, tyco)) =
   855       [(Display.pretty_thm_global thy o AxClass.overload thy o Thm.varifyT_global) abs_thm];
   856 
   857 fun bare_thms_of_cert thy (cert as Equations _) =
   858       (map_filter (fn (_, (some_thm, proper)) => if proper then some_thm else NONE)
   859         o snd o equations_of_cert thy) cert
   860   | bare_thms_of_cert thy (Projection _) = []
   861   | bare_thms_of_cert thy (Abstract (abs_thm, tyco)) =
   862       [Thm.varifyT_global (snd (concretify_abs thy tyco abs_thm))];
   863 
   864 end;
   865 
   866 
   867 (* code certificate access *)
   868 
   869 fun retrieve_raw thy c =
   870   Symtab.lookup ((the_functions o the_exec) thy) c
   871   |> Option.map (snd o fst)
   872   |> the_default (Default [])
   873 
   874 fun get_cert thy f c = case retrieve_raw thy c
   875  of Default eqns => eqns
   876       |> (map o apfst) (Thm.transfer thy)
   877       |> f
   878       |> (map o apfst) (AxClass.unoverload thy)
   879       |> cert_of_eqns thy c
   880   | Eqns eqns => eqns
   881       |> (map o apfst) (Thm.transfer thy)
   882       |> f
   883       |> (map o apfst) (AxClass.unoverload thy)
   884       |> cert_of_eqns thy c
   885   | Proj (_, tyco) =>
   886       cert_of_proj thy c tyco
   887   | Abstr (abs_thm, tyco) => abs_thm
   888       |> Thm.transfer thy
   889       |> AxClass.unoverload thy
   890       |> cert_of_abs thy tyco c;
   891 
   892 
   893 (* cases *)
   894 
   895 fun case_certificate thm =
   896   let
   897     val ((head, raw_case_expr), cases) = (apfst Logic.dest_equals
   898       o apsnd Logic.dest_conjunctions o Logic.dest_implies o Thm.plain_prop_of) thm;
   899     val _ = case head of Free _ => true
   900       | Var _ => true
   901       | _ => raise TERM ("case_cert", []);
   902     val ([(case_var, _)], case_expr) = Term.strip_abs_eta 1 raw_case_expr;
   903     val (Const (case_const, _), raw_params) = strip_comb case_expr;
   904     val n = find_index (fn Free (v, _) => v = case_var | _ => false) raw_params;
   905     val _ = if n = ~1 then raise TERM ("case_cert", []) else ();
   906     val params = map (fst o dest_Var) (nth_drop n raw_params);
   907     fun dest_case t =
   908       let
   909         val (head' $ t_co, rhs) = Logic.dest_equals t;
   910         val _ = if head' = head then () else raise TERM ("case_cert", []);
   911         val (Const (co, _), args) = strip_comb t_co;
   912         val (Var (param, _), args') = strip_comb rhs;
   913         val _ = if args' = args then () else raise TERM ("case_cert", []);
   914       in (param, co) end;
   915     fun analyze_cases cases =
   916       let
   917         val co_list = fold (AList.update (op =) o dest_case) cases [];
   918       in map (the o AList.lookup (op =) co_list) params end;
   919     fun analyze_let t =
   920       let
   921         val (head' $ arg, Var (param', _) $ arg') = Logic.dest_equals t;
   922         val _ = if head' = head then () else raise TERM ("case_cert", []);
   923         val _ = if arg' = arg then () else raise TERM ("case_cert", []);
   924         val _ = if [param'] = params then () else raise TERM ("case_cert", []);
   925       in [] end;
   926     fun analyze (cases as [let_case]) =
   927           (analyze_cases cases handle Bind => analyze_let let_case)
   928       | analyze cases = analyze_cases cases;
   929   in (case_const, (n, analyze cases)) end;
   930 
   931 fun case_cert thm = case_certificate thm
   932   handle Bind => error "bad case certificate"
   933        | TERM _ => error "bad case certificate";
   934 
   935 fun get_case_scheme thy = Symtab.lookup ((fst o the_cases o the_exec) thy);
   936 
   937 val undefineds = Symtab.keys o snd o the_cases o the_exec;
   938 
   939 
   940 (* diagnostic *)
   941 
   942 fun print_codesetup thy =
   943   let
   944     val ctxt = ProofContext.init_global thy;
   945     val exec = the_exec thy;
   946     fun pretty_equations const thms =
   947       (Pretty.block o Pretty.fbreaks) (
   948         Pretty.str (string_of_const thy const) :: map (Display.pretty_thm ctxt) thms
   949       );
   950     fun pretty_function (const, Default eqns) = pretty_equations const (map fst eqns)
   951       | pretty_function (const, Eqns eqns) = pretty_equations const (map fst eqns)
   952       | pretty_function (const, Proj (proj, _)) = Pretty.block
   953           [Pretty.str (string_of_const thy const), Pretty.fbrk, Syntax.pretty_term ctxt proj]
   954       | pretty_function (const, Abstr (thm, _)) = pretty_equations const [thm];
   955     fun pretty_typ (tyco, vs) = Pretty.str
   956       (string_of_typ thy (Type (tyco, map TFree vs)));
   957     fun pretty_typspec (typ, (cos, abstract)) = if null cos
   958       then pretty_typ typ
   959       else (Pretty.block o Pretty.breaks) (
   960         pretty_typ typ
   961         :: Pretty.str "="
   962         :: (if abstract then [Pretty.str "(abstract)"] else [])
   963         @ separate (Pretty.str "|") (map (fn (c, []) => Pretty.str (string_of_const thy c)
   964              | (c, tys) =>
   965                  (Pretty.block o Pretty.breaks)
   966                     (Pretty.str (string_of_const thy c)
   967                       :: Pretty.str "of"
   968                       :: map (Pretty.quote o Syntax.pretty_typ_global thy) tys)) cos)
   969       );
   970     fun pretty_case (const, (_, (_, []))) = Pretty.str (string_of_const thy const)
   971       | pretty_case (const, (_, (_, cos))) = (Pretty.block o Pretty.breaks) [
   972           Pretty.str (string_of_const thy const), Pretty.str "with",
   973           (Pretty.block o Pretty.commas o map (Pretty.str o string_of_const thy)) cos];
   974     val functions = the_functions exec
   975       |> Symtab.dest
   976       |> (map o apsnd) (snd o fst)
   977       |> sort (string_ord o pairself fst);
   978     val datatypes = the_types exec
   979       |> Symtab.dest
   980       |> map (fn (tyco, (_, (vs, spec)) :: _) =>
   981           ((tyco, vs), constructors_of spec))
   982       |> sort (string_ord o pairself (fst o fst));
   983     val cases = Symtab.dest ((fst o the_cases o the_exec) thy);
   984     val undefineds = Symtab.keys ((snd o the_cases o the_exec) thy);
   985   in
   986     (Pretty.writeln o Pretty.chunks) [
   987       Pretty.block (
   988         Pretty.str "code equations:" :: Pretty.fbrk
   989         :: (Pretty.fbreaks o map pretty_function) functions
   990       ),
   991       Pretty.block (
   992         Pretty.str "datatypes:" :: Pretty.fbrk
   993         :: (Pretty.fbreaks o map pretty_typspec) datatypes
   994       ),
   995       Pretty.block (
   996         Pretty.str "cases:" :: Pretty.fbrk
   997         :: (Pretty.fbreaks o map pretty_case) cases
   998       ),
   999       Pretty.block (
  1000         Pretty.str "undefined:" :: Pretty.fbrk
  1001         :: (Pretty.commas o map (Pretty.str o string_of_const thy)) undefineds
  1002       )
  1003     ]
  1004   end;
  1005 
  1006 
  1007 (** declaring executable ingredients **)
  1008 
  1009 (* constant signatures *)
  1010 
  1011 fun add_type tyco thy =
  1012   case Symtab.lookup ((snd o #types o Type.rep_tsig o Sign.tsig_of) thy) tyco
  1013    of SOME (Type.Abbreviation (vs, _, _)) =>
  1014           (map_exec_purge o map_signatures o apfst)
  1015             (Symtab.update (tyco, length vs)) thy
  1016     | _ => error ("No such type abbreviation: " ^ quote tyco);
  1017 
  1018 fun add_type_cmd s thy = add_type (Sign.intern_type thy s) thy;
  1019 
  1020 fun gen_add_signature prep_const prep_signature (raw_c, raw_ty) thy =
  1021   let
  1022     val c = prep_const thy raw_c;
  1023     val ty = prep_signature thy raw_ty;
  1024     val ty' = expand_signature thy ty;
  1025     val ty'' = Sign.the_const_type thy c;
  1026     val _ = if typ_equiv (ty', ty'') then () else
  1027       error ("Illegal constant signature: " ^ Syntax.string_of_typ_global thy ty);
  1028   in
  1029     thy
  1030     |> (map_exec_purge o map_signatures o apsnd) (Symtab.update (c, ty))
  1031   end;
  1032 
  1033 val add_signature = gen_add_signature (K I) cert_signature;
  1034 val add_signature_cmd = gen_add_signature read_const read_signature;
  1035 
  1036 
  1037 (* code equations *)
  1038 
  1039 fun gen_add_eqn default (raw_thm, proper) thy =
  1040   let
  1041     val thm = Thm.close_derivation raw_thm;
  1042     val c = const_eqn thy thm;
  1043     fun add_eqn' true (Default eqns) = Default (eqns @ [(thm, proper)])
  1044       | add_eqn' _ (Eqns eqns) =
  1045           let
  1046             val args_of = snd o strip_comb o map_types Type.strip_sorts
  1047               o fst o Logic.dest_equals o Thm.plain_prop_of;
  1048             val args = args_of thm;
  1049             val incr_idx = Logic.incr_indexes ([], Thm.maxidx_of thm + 1);
  1050             fun matches_args args' = length args <= length args' andalso
  1051               Pattern.matchess thy (args, (map incr_idx o take (length args)) args');
  1052             fun drop (thm', proper') = if (proper orelse not proper')
  1053               andalso matches_args (args_of thm') then 
  1054                 (warning ("Code generator: dropping redundant code equation\n" ^
  1055                     Display.string_of_thm_global thy thm'); true)
  1056               else false;
  1057           in Eqns ((thm, proper) :: filter_out drop eqns) end
  1058       | add_eqn' false _ = Eqns [(thm, proper)];
  1059   in change_fun_spec false c (add_eqn' default) thy end;
  1060 
  1061 fun add_eqn thm thy =
  1062   gen_add_eqn false (mk_eqn thy (thm, true)) thy;
  1063 
  1064 fun add_warning_eqn thm thy =
  1065   case mk_eqn_warning thy thm
  1066    of SOME eqn => gen_add_eqn false eqn thy
  1067     | NONE => thy;
  1068 
  1069 fun add_default_eqn thm thy =
  1070   case mk_eqn_liberal thy thm
  1071    of SOME eqn => gen_add_eqn true eqn thy
  1072     | NONE => thy;
  1073 
  1074 fun add_nbe_eqn thm thy =
  1075   gen_add_eqn false (mk_eqn thy (thm, false)) thy;
  1076 
  1077 val add_default_eqn_attribute = Thm.declaration_attribute
  1078   (fn thm => Context.mapping (add_default_eqn thm) I);
  1079 val add_default_eqn_attrib = Attrib.internal (K add_default_eqn_attribute);
  1080 
  1081 fun add_abs_eqn raw_thm thy =
  1082   let
  1083     val (abs_thm, tyco) = (apfst Thm.close_derivation o mk_abs_eqn thy) raw_thm;
  1084     val c = const_abs_eqn thy abs_thm;
  1085   in change_fun_spec false c (K (Abstr (abs_thm, tyco))) thy end;
  1086 
  1087 fun del_eqn thm thy = case mk_eqn_liberal thy thm
  1088  of SOME (thm, _) => let
  1089         fun del_eqn' (Default eqns) = empty_fun_spec
  1090           | del_eqn' (Eqns eqns) =
  1091               Eqns (filter_out (fn (thm', _) => Thm.eq_thm_prop (thm, thm')) eqns)
  1092           | del_eqn' spec = spec
  1093       in change_fun_spec true (const_eqn thy thm) del_eqn' thy end
  1094   | NONE => thy;
  1095 
  1096 fun del_eqns c = change_fun_spec true c (K empty_fun_spec);
  1097 
  1098 
  1099 (* cases *)
  1100 
  1101 fun add_case thm thy =
  1102   let
  1103     val (c, (k, case_pats)) = case_cert thm;
  1104     val _ = case filter_out (is_constr thy) case_pats
  1105      of [] => ()
  1106       | cs => error ("Non-constructor(s) in case certificate: " ^ commas (map quote cs));
  1107     val entry = (1 + Int.max (1, length case_pats), (k, case_pats))
  1108   in (map_exec_purge o map_cases o apfst) (Symtab.update (c, entry)) thy end;
  1109 
  1110 fun add_undefined c thy =
  1111   (map_exec_purge o map_cases o apsnd) (Symtab.update (c, ())) thy;
  1112 
  1113 
  1114 (* types *)
  1115 
  1116 fun register_type (tyco, vs_spec) thy =
  1117   let
  1118     val (old_constrs, some_old_proj) =
  1119       case these (Symtab.lookup ((the_types o the_exec) thy) tyco)
  1120        of (_, (_, Constructors cos)) :: _ => (map fst cos, NONE)
  1121         | (_, (_, Abstractor ((co, _), (proj, _)))) :: _ => ([co], SOME proj)
  1122         | [] => ([], NONE)
  1123     val outdated_funs = case some_old_proj
  1124      of NONE => old_constrs
  1125       | SOME old_proj => Symtab.fold
  1126           (fn (c, ((_, spec), _)) =>
  1127             if member (op =) (the_list (associated_abstype spec)) tyco
  1128             then insert (op =) c else I)
  1129             ((the_functions o the_exec) thy) (old_proj :: old_constrs);
  1130     fun drop_outdated_cases cases = fold Symtab.delete_safe
  1131       (Symtab.fold (fn (c, (_, (_, cos))) =>
  1132         if exists (member (op =) old_constrs) cos
  1133           then insert (op =) c else I) cases []) cases;
  1134   in
  1135     thy
  1136     |> fold del_eqns outdated_funs
  1137     |> map_exec_purge
  1138         ((map_typs o Symtab.map_default (tyco, [])) (cons (serial (), vs_spec))
  1139         #> (map_cases o apfst) drop_outdated_cases)
  1140   end;
  1141 
  1142 fun unoverload_const_typ thy (c, ty) = (AxClass.unoverload_const thy (c, ty), ty);
  1143 
  1144 structure Datatype_Interpretation =
  1145   Interpretation(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
  1146 
  1147 fun datatype_interpretation f = Datatype_Interpretation.interpretation
  1148   (fn (tyco, _) => fn thy => f (tyco, get_type thy tyco) thy);
  1149 
  1150 fun add_datatype proto_constrs thy =
  1151   let
  1152     val constrs = map (unoverload_const_typ thy) proto_constrs;
  1153     val (tyco, (vs, cos)) = constrset_of_consts thy constrs;
  1154   in
  1155     thy
  1156     |> fold (del_eqns o fst) constrs
  1157     |> register_type (tyco, (vs, Constructors cos))
  1158     |> Datatype_Interpretation.data (tyco, serial ())
  1159   end;
  1160 
  1161 fun add_datatype_cmd raw_constrs thy =
  1162   add_datatype (map (read_bare_const thy) raw_constrs) thy;
  1163 
  1164 structure Abstype_Interpretation =
  1165   Interpretation(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
  1166 
  1167 fun abstype_interpretation f = Abstype_Interpretation.interpretation
  1168   (fn (tyco, _) => fn thy => f (tyco, get_abstype_spec thy tyco) thy);
  1169 
  1170 fun add_abstype proto_thm thy =
  1171   let
  1172     val (tyco, (vs, (abs_ty as (abs, ty), (rep, cert)))) =
  1173       error_thm (check_abstype_cert thy) proto_thm;
  1174   in
  1175     thy
  1176     |> del_eqns abs
  1177     |> register_type (tyco, (vs, Abstractor (abs_ty, (rep, cert))))
  1178     |> change_fun_spec false rep ((K o Proj)
  1179         (map_types Logic.varifyT_global (mk_proj tyco vs ty abs rep), tyco))
  1180     |> Abstype_Interpretation.data (tyco, serial ())
  1181   end;
  1182 
  1183 
  1184 (** infrastructure **)
  1185 
  1186 (* c.f. src/HOL/Tools/recfun_codegen.ML *)
  1187 
  1188 structure Code_Target_Attr = Theory_Data
  1189 (
  1190   type T = (string -> thm -> theory -> theory) option;
  1191   val empty = NONE;
  1192   val extend = I;
  1193   fun merge (f1, f2) = if is_some f1 then f1 else f2;
  1194 );
  1195 
  1196 fun set_code_target_attr f = Code_Target_Attr.map (K (SOME f));
  1197 
  1198 fun code_target_attr prefix thm thy =
  1199   let
  1200     val attr = the_default ((K o K) I) (Code_Target_Attr.get thy);
  1201   in thy |> add_warning_eqn thm |> attr prefix thm end;
  1202 
  1203 
  1204 (* setup *)
  1205 
  1206 val _ = Context.>> (Context.map_theory
  1207   (let
  1208     fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
  1209     val code_attribute_parser =
  1210       Args.del |-- Scan.succeed (mk_attribute del_eqn)
  1211       || Args.$$$ "nbe" |-- Scan.succeed (mk_attribute add_nbe_eqn)
  1212       || Args.$$$ "abstype" |-- Scan.succeed (mk_attribute add_abstype)
  1213       || Args.$$$ "abstract" |-- Scan.succeed (mk_attribute add_abs_eqn)
  1214       || (Args.$$$ "target" |-- Args.colon |-- Args.name >>
  1215            (mk_attribute o code_target_attr))
  1216       || Scan.succeed (mk_attribute add_warning_eqn);
  1217   in
  1218     Datatype_Interpretation.init
  1219     #> Attrib.setup (Binding.name "code") (Scan.lift code_attribute_parser)
  1220         "declare theorems for code generation"
  1221   end));
  1222 
  1223 end; (*struct*)
  1224 
  1225 
  1226 (* type-safe interfaces for data dependent on executable code *)
  1227 
  1228 functor Code_Data(Data: CODE_DATA_ARGS): CODE_DATA =
  1229 struct
  1230 
  1231 type T = Data.T;
  1232 exception Data of T;
  1233 fun dest (Data x) = x
  1234 
  1235 val kind = Code.declare_data (Data Data.empty);
  1236 
  1237 val data_op = (kind, Data, dest);
  1238 
  1239 val change = Code.change_data data_op;
  1240 fun change_yield thy = Code.change_yield_data data_op thy;
  1241 
  1242 end;
  1243 
  1244 structure Code : CODE = struct open Code; end;