src/Pure/Isar/proof_context.ML
author wenzelm
Fri Apr 07 17:36:25 2000 +0200 (2000-04-07 ago)
changeset 8681 957a5fe9b212
parent 8637 e86e49aa1631
child 8807 0046be1769f9
permissions -rw-r--r--
apply etc.: comments;
     1 (*  Title:      Pure/Isar/proof_context.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 Proof context information.
     6 *)
     7 
     8 signature PROOF_CONTEXT =
     9 sig
    10   type context
    11   exception CONTEXT of string * context
    12   val theory_of: context -> theory
    13   val sign_of: context -> Sign.sg
    14   val prems_of: context -> thm list
    15   val show_hyps: bool ref
    16   val pretty_thm: thm -> Pretty.T
    17   val verbose: bool ref
    18   val print_binds: context -> unit
    19   val print_thms: context -> unit
    20   val print_cases: context -> unit
    21   val pretty_prems: context -> Pretty.T list
    22   val pretty_context: context -> Pretty.T list
    23   val print_proof_data: theory -> unit
    24   val init: theory -> context
    25   val assumptions: context -> (cterm * ((int -> tactic) * (int -> tactic))) list
    26   val fixed_names: context -> string list
    27   val read_typ: context -> string -> typ
    28   val cert_typ: context -> typ -> typ
    29   val cert_skolem: context -> string -> string
    30   val read_termTs: context -> (string * typ) list -> term list * (indexname * typ) list
    31   val read_term: context -> string -> term
    32   val read_prop: context -> string -> term
    33   val read_termT_pats: context -> (string * typ) list -> term list
    34   val read_term_pats: typ -> context -> string list -> term list
    35   val read_prop_pats: context -> string list -> term list
    36   val cert_term: context -> term -> term
    37   val cert_prop: context -> term -> term
    38   val cert_term_pats: typ -> context -> term list -> term list
    39   val cert_prop_pats: context -> term list -> term list
    40   val declare_term: term -> context -> context
    41   val declare_terms: term list -> context -> context
    42   val warn_extra_tfrees: context -> context -> context
    43   val generalizeT: context -> context -> typ -> typ
    44   val generalize: context -> context -> term -> term
    45   val find_free: term -> string -> term option 
    46   val export_wrt: context -> context option
    47     -> (thm -> thm) * ((int -> tactic) * (int -> tactic)) list
    48   val auto_bind_goal: term -> context -> context
    49   val auto_bind_facts: string -> term list -> context -> context
    50   val match_bind: bool -> (string list * string) list -> context -> context
    51   val match_bind_i: bool -> (term list * term) list -> context -> context
    52   val read_propp: context * (string * (string list * string list))
    53     -> context * (term * (term list * term list))
    54   val cert_propp: context * (term * (term list * term list))
    55     -> context * (term * (term list * term list))
    56   val bind_propp: context * (string * (string list * string list))
    57     -> context * (term * (context -> context))
    58   val bind_propp_i: context * (term * (term list * term list))
    59     -> context * (term * (context -> context))
    60   val get_thm: context -> string -> thm
    61   val get_thms: context -> string -> thm list
    62   val get_thmss: context -> string list -> thm list
    63   val put_thm: string * thm -> context -> context
    64   val put_thms: string * thm list -> context -> context
    65   val put_thmss: (string * thm list) list -> context -> context
    66   val reset_thms: string -> context -> context
    67   val have_thmss: thm list -> string -> context attribute list
    68     -> (thm list * context attribute list) list -> context -> context * (string * thm list)
    69   val assume: ((int -> tactic) * (int -> tactic))
    70     -> (string * context attribute list * (string * (string list * string list)) list) list
    71     -> context -> context * ((string * thm list) list * thm list)
    72   val assume_i: ((int -> tactic) * (int -> tactic))
    73     -> (string * context attribute list * (term * (term list * term list)) list) list
    74     -> context -> context * ((string * thm list) list * thm list)
    75   val read_vars: context * (string list * string option) -> context * (string list * typ option)
    76   val cert_vars: context * (string list * typ option) -> context * (string list * typ option)
    77   val fix: (string list * string option) list -> context -> context
    78   val fix_i: (string list * typ option) list -> context -> context
    79   val get_case: context -> string -> RuleCases.T
    80   val add_cases: (string * RuleCases.T) list -> context -> context
    81   val setup: (theory -> theory) list
    82 end;
    83 
    84 signature PRIVATE_PROOF_CONTEXT =
    85 sig
    86   include PROOF_CONTEXT
    87   val init_data: Object.kind -> (theory -> Object.T) * (context -> Object.T -> unit)
    88     -> theory -> theory
    89   val print_data: Object.kind -> context -> unit
    90   val get_data: Object.kind -> (Object.T -> 'a) -> context -> 'a
    91   val put_data: Object.kind -> ('a -> Object.T) -> 'a -> context -> context
    92 end;
    93 
    94 structure ProofContext: PRIVATE_PROOF_CONTEXT =
    95 struct
    96 
    97 
    98 (** datatype context **)
    99 
   100 datatype context =
   101   Context of
   102    {thy: theory,                                                        (*current theory*)
   103     data: Object.T Symtab.table,                                        (*user data*)
   104     asms:
   105       ((cterm * ((int -> tactic) * (int -> tactic))) list *             (*assumes: A ==> _*)
   106         (string * thm list) list) *
   107       ((string * string) list * string list),                           (*fixes: !!x. _*)
   108     binds: (term * typ) option Vartab.table,                            (*term bindings*)
   109     thms: thm list option Symtab.table,                                 (*local thms*)
   110     cases: (string * RuleCases.T) list,                                 (*local contexts*)
   111     defs:
   112       typ Vartab.table *                                                (*type constraints*)
   113       sort Vartab.table *                                               (*default sorts*)
   114       (string list * term list Symtab.table)};                          (*used type variables*)
   115 
   116 exception CONTEXT of string * context;
   117 
   118 
   119 fun make_context (thy, data, asms, binds, thms, cases, defs) =
   120   Context {thy = thy, data = data, asms = asms, binds = binds, thms = thms,
   121     cases = cases, defs = defs};
   122 
   123 fun map_context f (Context {thy, data, asms, binds, thms, cases, defs}) =
   124   make_context (f (thy, data, asms, binds, thms, cases, defs));
   125 
   126 fun theory_of (Context {thy, ...}) = thy;
   127 val sign_of = Theory.sign_of o theory_of;
   128 
   129 fun prems_of (Context {asms = ((_, asms), _), ...}) = flat (map #2 asms);
   130 
   131 
   132 
   133 (** print context information **)
   134 
   135 val show_hyps = ref false;
   136 
   137 fun pretty_thm thm =
   138   if ! show_hyps then setmp Display.show_hyps true Display.pretty_thm_no_quote thm
   139   else Display.pretty_cterm (#prop (Thm.crep_thm thm));
   140 
   141 val verbose = ref false;
   142 fun verb f x = if ! verbose then f (x ()) else [];
   143 fun verb_single x = verb Library.single x;
   144 
   145 fun pretty_items prt name items =
   146   let
   147     fun prt_itms (name, [x]) = Pretty.block [Pretty.str (name ^ ":"), Pretty.brk 1, prt x]
   148       | prt_itms (name, xs) = Pretty.big_list (name ^ ":") (map prt xs);
   149   in
   150     if null items andalso not (! verbose) then []
   151     else [Pretty.big_list name (map prt_itms items)]
   152   end;
   153 
   154 
   155 (* term bindings *)
   156 
   157 val smash_option = fn (_, None) => None | (xi, Some b) => Some (xi, b);
   158 
   159 fun pretty_binds (ctxt as Context {binds, ...}) =
   160   let
   161     val prt_term = Sign.pretty_term (sign_of ctxt);
   162     fun prt_bind (xi, (t, T)) = prt_term (Logic.mk_equals (Var (xi, T), t));
   163     val bs = mapfilter smash_option (Vartab.dest binds);
   164   in
   165     if null bs andalso not (! verbose) then []
   166     else [Pretty.big_list "term bindings:" (map prt_bind bs)]
   167   end;
   168 
   169 val print_binds = Pretty.writeln o Pretty.chunks o pretty_binds;
   170 
   171 
   172 (* local theorems *)
   173 
   174 fun pretty_thms (Context {thms, ...}) =
   175   pretty_items pretty_thm "local theorems:" (mapfilter smash_option (Symtab.dest thms));
   176 
   177 val print_thms = Pretty.writeln o Pretty.chunks o pretty_thms;
   178 
   179 
   180 (* local contexts *)
   181 
   182 fun pretty_cases (ctxt as Context {cases, ...}) =
   183   let
   184     val prt_term = Sign.pretty_term (sign_of ctxt);
   185 
   186     fun prt_sect _ _ [] = []
   187       | prt_sect s prt xs = [Pretty.block (Pretty.breaks (Pretty.str s :: map prt xs))];
   188 
   189     fun prt_case (name, (xs, ts)) = Pretty.block (Pretty.breaks
   190       (Pretty.str (name ^ ":") ::
   191         prt_sect "fix" (prt_term o Free) xs @
   192         prt_sect "assume" (Pretty.quote o prt_term) ts));
   193 
   194     val cases' = rev (Library.gen_distinct Library.eq_fst cases);
   195   in
   196     if null cases andalso not (! verbose) then []
   197     else [Pretty.big_list "cases:" (map prt_case cases')]
   198   end;
   199 
   200 val print_cases = Pretty.writeln o Pretty.chunks o pretty_cases;
   201 
   202 
   203 (* main context *)
   204 
   205 fun pretty_prems ctxt =
   206   (case prems_of ctxt of
   207     [] => []
   208   | prems => [Pretty.big_list "prems:" (map pretty_thm prems)]);
   209 
   210 fun pretty_context (ctxt as Context {asms = (_, (fixes, _)), cases,
   211     defs = (types, sorts, (used, _)), ...}) =
   212   let
   213     val sign = sign_of ctxt;
   214 
   215     val prt_term = Sign.pretty_term sign;
   216     val prt_typ = Sign.pretty_typ sign;
   217     val prt_sort = Sign.pretty_sort sign;
   218 
   219     (*theory*)
   220     val pretty_thy = Pretty.block [Pretty.str "Theory:", Pretty.brk 1, Sign.pretty_sg sign];
   221 
   222     (*fixes*)
   223     fun prt_fix (x, x') = Pretty.block
   224       [prt_term (Syntax.free x), Pretty.str " =", Pretty.brk 1, prt_term (Syntax.free x')];
   225 
   226     fun prt_fixes xs = Pretty.block (Pretty.str "fixed variables:" :: Pretty.brk 1 ::
   227       Pretty.commas (map prt_fix xs));
   228 
   229     (*defaults*)
   230     fun prt_atom prt prtT (x, X) = Pretty.block
   231       [prt x, Pretty.str " ::", Pretty.brk 1, prtT X];
   232 
   233     fun prt_var (x, ~1) = prt_term (Syntax.free x)
   234       | prt_var xi = prt_term (Syntax.var xi);
   235 
   236     fun prt_varT (x, ~1) = prt_typ (TFree (x, []))
   237       | prt_varT xi = prt_typ (TVar (xi, []));
   238 
   239     val prt_defT = prt_atom prt_var prt_typ;
   240     val prt_defS = prt_atom prt_varT prt_sort;
   241   in
   242     verb_single (K pretty_thy) @
   243     (if null fixes then [] else [prt_fixes (rev fixes)]) @
   244     pretty_prems ctxt @
   245     verb pretty_binds (K ctxt) @
   246     verb pretty_thms (K ctxt) @
   247     verb pretty_cases (K ctxt) @
   248     verb_single (fn () => Pretty.big_list "type constraints:" (map prt_defT (Vartab.dest types))) @
   249     verb_single (fn () => Pretty.big_list "default sorts:" (map prt_defS (Vartab.dest sorts))) @
   250     verb_single (fn () => Pretty.strs ("used type variable names:" :: used))
   251   end;
   252 
   253 
   254 
   255 (** user data **)
   256 
   257 (* errors *)
   258 
   259 fun of_theory thy = "\nof theory " ^ Sign.str_of_sg (Theory.sign_of thy);
   260 
   261 fun err_inconsistent kinds =
   262   error ("Attempt to merge different versions of " ^ commas_quote kinds ^ " proof data");
   263 
   264 fun err_dup_init thy kind =
   265   error ("Duplicate initialization of " ^ quote kind ^ " proof data" ^ of_theory thy);
   266 
   267 fun err_undef ctxt kind =
   268   raise CONTEXT ("Tried to access undefined " ^ quote kind ^ " proof data", ctxt);
   269 
   270 fun err_uninit ctxt kind =
   271   raise CONTEXT ("Tried to access uninitialized " ^ quote kind ^ " proof data" ^
   272     of_theory (theory_of ctxt), ctxt);
   273 
   274 fun err_access ctxt kind =
   275   raise CONTEXT ("Unauthorized access to " ^ quote kind ^ " proof data" ^
   276     of_theory (theory_of ctxt), ctxt);
   277 
   278 
   279 (* data kind 'Isar/proof_data' *)
   280 
   281 structure ProofDataDataArgs =
   282 struct
   283   val name = "Isar/proof_data";
   284   type T = (Object.kind * ((theory -> Object.T) * (context -> Object.T -> unit))) Symtab.table;
   285 
   286   val empty = Symtab.empty;
   287   val copy = I;
   288   val prep_ext = I;
   289   fun merge tabs = Symtab.merge (Object.eq_kind o pairself fst) tabs
   290     handle Symtab.DUPS kinds => err_inconsistent kinds;
   291   fun print _ tab = Pretty.writeln (Pretty.strs (map #1 (Symtab.dest tab)));
   292 end;
   293 
   294 structure ProofDataData = TheoryDataFun(ProofDataDataArgs);
   295 val print_proof_data = ProofDataData.print;
   296 
   297 
   298 (* init proof data *)
   299 
   300 fun init_data kind meths thy =
   301   let
   302     val name = Object.name_of_kind kind;
   303     val tab = Symtab.update_new ((name, (kind, meths)), ProofDataData.get thy)
   304       handle Symtab.DUP _ => err_dup_init thy name;
   305   in thy |> ProofDataData.put tab end;
   306 
   307 
   308 (* access data *)
   309 
   310 fun lookup_data (ctxt as Context {data, ...}) kind =
   311   let
   312     val thy = theory_of ctxt;
   313     val name = Object.name_of_kind kind;
   314   in
   315     (case Symtab.lookup (ProofDataData.get thy, name) of
   316       Some (k, meths) =>
   317         if Object.eq_kind (kind, k) then
   318           (case Symtab.lookup (data, name) of
   319             Some x => (x, meths)
   320           | None => err_undef ctxt name)
   321         else err_access ctxt name
   322     | None => err_uninit ctxt name)
   323   end;
   324 
   325 fun get_data kind f ctxt =
   326   let val (x, _) = lookup_data ctxt kind
   327   in f x handle Match => Object.kind_error kind end;
   328 
   329 fun print_data kind ctxt =
   330   let val (x, (_, prt)) = lookup_data ctxt kind
   331   in prt ctxt x end;
   332 
   333 fun put_data kind f x ctxt =
   334  (lookup_data ctxt kind;
   335   ctxt |> map_context (fn (thy, data, asms, binds, thms, cases, defs) =>
   336     (thy, Symtab.update ((Object.name_of_kind kind, f x), data), asms, binds, thms, cases, defs)));
   337 
   338 
   339 (* init context *)
   340 
   341 fun init thy =
   342   let val data = Symtab.map (fn (_, (f, _)) => f thy) (ProofDataData.get thy) in
   343     make_context (thy, data, (([], []), ([], [])), Vartab.empty, Symtab.empty, [],
   344       (Vartab.empty, Vartab.empty, ([], Symtab.empty)))
   345   end;
   346 
   347 
   348 (* get assumptions *)
   349 
   350 fun assumptions (Context {asms = ((asms, _), _), ...}) = asms;
   351 fun fixed_names (Context {asms = (_, (fixes, _)), ...}) = map #2 fixes;
   352 fun used_table (Context {defs = (_, _, (_, tab)), ...}) = tab;
   353 
   354 
   355 
   356 (** default sorts and types **)
   357 
   358 fun def_sort (Context {defs = (_, sorts, _), ...}) xi = Vartab.lookup (sorts, xi);
   359 
   360 fun def_type (Context {binds, defs = (types, _, _), ...}) is_pat xi =
   361   (case Vartab.lookup (types, xi) of
   362     None =>
   363       if is_pat then None else
   364         (case Vartab.lookup (binds, xi) of
   365           Some (Some (_, T)) => Some (TypeInfer.polymorphicT T)
   366         | _ => None)
   367   | some => some);
   368 
   369 
   370 
   371 (** prepare types **)
   372 
   373 fun read_typ ctxt s =
   374   transform_error (Sign.read_typ (sign_of ctxt, def_sort ctxt)) s
   375     handle ERROR_MESSAGE msg => raise CONTEXT (msg, ctxt);
   376 
   377 fun cert_typ ctxt raw_T =
   378   Sign.certify_typ (sign_of ctxt) raw_T
   379     handle TYPE (msg, _, _) => raise CONTEXT (msg, ctxt);
   380 
   381 
   382 (* internalize Skolem constants *)
   383 
   384 fun get_skolem (Context {asms = (_, (fixes, _)), ...}) x = assoc (fixes, x);
   385 
   386 fun check_skolem ctxt check x =
   387   if check andalso can Syntax.dest_skolem x then
   388     raise CONTEXT ("Illegal reference to internal Skolem constant: " ^ quote x, ctxt)
   389   else x;
   390 
   391 fun intern_skolem ctxt check =
   392   let
   393     fun intern (t as Free (x, T)) =
   394           (case get_skolem ctxt (check_skolem ctxt check x) of
   395             Some x' => Free (x', T)
   396           | None => t)
   397       | intern (t $ u) = intern t $ intern u
   398       | intern (Abs (x, T, t)) = Abs (x, T, intern t)
   399       | intern a = a;
   400   in intern end;
   401 
   402 fun cert_skolem ctxt x =
   403   (case get_skolem ctxt x of
   404     None => raise CONTEXT ("Undeclared variable: " ^ quote x, ctxt)
   405   | Some x' => x');
   406 
   407 
   408 
   409 (** prepare terms and propositions **)
   410 
   411 (*
   412   (1) read / certify wrt. signature of context
   413   (2) intern Skolem constants
   414   (3) expand term bindings
   415 *)
   416 
   417 
   418 (* read / certify wrt. signature *)     (*exception ERROR*) (*exception TERM*)
   419 
   420 fun read_def_termTs freeze sg (types, sorts, used) sTs =
   421   Sign.read_def_terms (sg, types, sorts) used freeze sTs;
   422 
   423 fun read_def_termT freeze sg defs sT = apfst hd (read_def_termTs freeze sg defs [sT]);
   424 
   425 fun read_term_sg freeze sg defs s = #1 (read_def_termT freeze sg defs (s, TypeInfer.logicT));
   426 fun read_prop_sg freeze sg defs s = #1 (read_def_termT freeze sg defs (s, propT));
   427 
   428 
   429 fun cert_term_sg sg t = Thm.term_of (Thm.cterm_of sg t);
   430 
   431 fun cert_prop_sg sg tm =
   432   let
   433     val ctm = Thm.cterm_of sg tm;
   434     val {t, T, ...} = Thm.rep_cterm ctm;
   435   in
   436     if T = propT then t
   437     else raise TERM ("Term not of type prop", [t])
   438   end;
   439 
   440 
   441 (* norm_term *)
   442 
   443 (*beta normal form for terms (not eta normal form), chase variables in
   444   bindings environment (code taken from Pure/envir.ML)*)
   445 
   446 fun unifyT ctxt (T, U) =
   447   let val maxidx = Int.max (Term.maxidx_of_typ T, Term.maxidx_of_typ U)
   448   in #1 (Type.unify (Sign.tsig_of (sign_of ctxt)) maxidx Vartab.empty (T, U)) end;
   449 
   450 fun norm_term (ctxt as Context {binds, ...}) =
   451   let
   452     (*raised when norm has no effect on a term, to do sharing instead of copying*)
   453     exception SAME;
   454 
   455     fun norm (t as Var (xi, T)) =
   456           (case Vartab.lookup (binds, xi) of
   457             Some (Some (u, U)) =>
   458               let
   459                 val env = unifyT ctxt (T, U) handle Type.TUNIFY =>
   460                   raise TYPE ("norm_term: ill-typed variable assigment", [T, U], [t, u]);
   461                 val u' = Term.subst_TVars_Vartab env u;
   462               in norm u' handle SAME => u' end
   463           | _ => raise CONTEXT ("Unbound schematic variable: " ^ Syntax.string_of_vname xi, ctxt))
   464       | norm (Abs (a, T, body)) =  Abs (a, T, norm body)
   465       | norm (Abs (_, _, body) $ t) = normh (subst_bound (t, body))
   466       | norm (f $ t) =
   467           ((case norm f of
   468             Abs (_, _, body) => normh (subst_bound (t, body))
   469           | nf => nf $ (norm t handle SAME => t)) handle SAME => f $ norm t)
   470       | norm _ =  raise SAME
   471     and normh t = norm t handle SAME => t
   472   in normh end;
   473 
   474 
   475 (* dummy patterns *)
   476 
   477 local
   478 
   479 fun is_dummy (Const (c, _)) = c = PureThy.dummy_patternN
   480   | is_dummy _ = false;
   481 
   482 fun prep_dummy (i, t) =
   483   if is_dummy t then (i + 1, Var (("_dummy_", i), Term.fastype_of t)) else (i, t);
   484 
   485 in
   486 
   487 fun prepare_dummies tm = #2 (Term.foldl_map_aterms prep_dummy (1, tm));
   488 
   489 fun reject_dummies ctxt tm =
   490   if foldl_aterms (fn (ok, t) => ok andalso not (is_dummy t)) (true, tm) then tm
   491   else raise CONTEXT ("Illegal dummy pattern(s) in term", ctxt);
   492 
   493 end;
   494 
   495 
   496 (* read terms *)
   497 
   498 fun gen_read read app is_pat (ctxt as Context {defs = (_, _, (used, _)), ...}) s =
   499   (transform_error (read (sign_of ctxt) (def_type ctxt is_pat, def_sort ctxt, used)) s
   500     handle TERM (msg, _) => raise CONTEXT (msg, ctxt)
   501     | ERROR_MESSAGE msg => raise CONTEXT (msg, ctxt))
   502   |> app (intern_skolem ctxt true)
   503   |> app (if is_pat then I else norm_term ctxt)
   504   |> app (if is_pat then prepare_dummies else (reject_dummies ctxt));
   505 
   506 val read_termTs = gen_read (read_def_termTs false) (apfst o map) false;
   507 val read_termT_pats = #1 oo gen_read (read_def_termTs false) (apfst o map) true;
   508 
   509 fun read_term_pats T ctxt pats = read_termT_pats ctxt (map (rpair T) pats);
   510 val read_prop_pats = read_term_pats propT;
   511 
   512 val read_term = gen_read (read_term_sg true) I false;
   513 val read_prop = gen_read (read_prop_sg true) I false;
   514 
   515 
   516 (* certify terms *)
   517 
   518 fun gen_cert cert is_pat ctxt t = t
   519   |> intern_skolem ctxt false
   520   |> (if is_pat then I else norm_term ctxt)
   521   |> (fn t' => cert (sign_of ctxt) t' handle TERM (msg, _) => raise CONTEXT (msg, ctxt));
   522 
   523 val cert_term = gen_cert cert_term_sg false;
   524 val cert_prop = gen_cert cert_prop_sg false;
   525 
   526 fun cert_term_pats _ = map o gen_cert cert_term_sg true;
   527 val cert_prop_pats = map o gen_cert cert_prop_sg true;
   528 
   529 
   530 (* declare terms *)
   531 
   532 val ins_types = foldl_aterms
   533   (fn (types, Free (x, T)) => Vartab.update (((x, ~1), T), types)
   534     | (types, Var v) => Vartab.update (v, types)
   535     | (types, _) => types);
   536 
   537 val ins_sorts = foldl_types (foldl_atyps
   538   (fn (sorts, TFree (x, S)) => Vartab.update (((x, ~1), S), sorts)
   539     | (sorts, TVar v) => Vartab.update (v, sorts)
   540     | (sorts, _) => sorts));
   541 
   542 val ins_used = foldl_term_types (fn t => foldl_atyps
   543   (fn ((used, tab), TFree (x, _)) => (x ins used, Symtab.update_multi ((x, t), tab))
   544     | (used, _) => used));
   545 
   546 fun ins_skolem def_ty = foldr
   547   (fn ((x, x'), types) =>
   548     (case def_ty x' of
   549       Some T => Vartab.update (((x, ~1), T), types)
   550     | None => types));
   551 
   552 fun map_defaults f = map_context (fn (thy, data, asms, binds, thms, cases, defs) =>
   553   (thy, data, asms, binds, thms, cases, f defs));
   554 
   555 fun declare (ctxt as Context {asms = (_, (fixes, _)), ...}, t) =
   556   ctxt
   557   |> map_defaults (fn (types, sorts, used) => (ins_types (types, t), sorts, used))
   558   |> map_defaults (fn (types, sorts, used) => (types, ins_sorts (sorts, t), used))
   559   |> map_defaults (fn (types, sorts, used) => (types, sorts, ins_used (used, t)))
   560   |> map_defaults (fn (types, sorts, used) =>
   561       (ins_skolem (fn x => Vartab.lookup (types, (x, ~1))) (fixes, types), sorts, used));
   562 
   563 
   564 fun declare_term t ctxt = declare (ctxt, t);
   565 fun declare_terms ts ctxt = foldl declare (ctxt, ts);
   566 
   567 
   568 
   569 (** Hindley-Milner polymorphism **)
   570 
   571 
   572 (* warn_extra_tfrees *)
   573 
   574 local
   575 
   576 fun used_free (a, ts) =
   577   (case mapfilter (fn Free (x, _) => Some x | _ => None) ts of
   578     [] => None
   579   | xs => Some (a, xs));
   580 
   581 fun warn_extra (names1: string list, tab1) (names2, tab2) =
   582   if names1 = names2 then ()
   583   else
   584     let
   585       val extra =
   586         Library.gen_rems Library.eq_fst (Symtab.dest tab2, Symtab.dest tab1)
   587         |> mapfilter used_free;
   588       val tfrees = map #1 extra;
   589       val frees = Library.sort_strings (Library.distinct (flat (map #2 extra)));
   590     in
   591       if null extra then ()
   592       else warning ("Danger! Just introduced free type variable(s): " ^ commas tfrees ^ " in " ^
   593           space_implode " or " frees)
   594     end;
   595 
   596 in
   597 
   598 fun warn_extra_tfrees (ctxt1 as Context {defs = (_, _, used1), ...})
   599     (ctxt2 as Context {defs = (_, _, used2), ...}) = (warn_extra used1 used2; ctxt2);
   600 
   601 end;
   602 
   603 
   604 (* generalize type variables *)
   605 
   606 fun gen_tfrees inner opt_outer =
   607   let
   608     val inner_used = used_table inner;
   609     val inner_fixes = fixed_names inner;
   610     val (outer_used, outer_fixes) =
   611       (case opt_outer of
   612         None => (Symtab.empty, [])
   613       | Some ctxt => (used_table ctxt, fixed_names ctxt));
   614 
   615     val extra_fixes = inner_fixes \\ outer_fixes;
   616     fun still_fixed (Free (x, _)) = not (x mem_string extra_fixes)
   617       | still_fixed _ = false;
   618 
   619     fun add (gen, (a, xs)) =
   620       if is_some (Symtab.lookup (outer_used, a)) orelse exists still_fixed xs
   621       then gen else a :: gen;
   622   in Symtab.foldl add ([], inner_used) end;
   623 
   624 fun generalizeT inner outer =
   625   let
   626     val tfrees = gen_tfrees inner (Some outer);
   627     fun gen (x, S) = if x mem_string tfrees then TVar ((x, 0), S) else TFree (x, S);
   628   in Term.map_type_tfree gen end;
   629 
   630 val generalize = Term.map_term_types oo generalizeT;
   631 
   632 
   633 (* export theorems *)
   634 
   635 fun get_free x (None, t as Free (y, _)) = if x = y then Some t else None
   636   | get_free _ (opt, _) = opt;
   637 
   638 fun find_free t x = foldl_aterms (get_free x) (None, t);
   639 
   640 
   641 local
   642 
   643 fun export tfrees fixes casms thm =
   644   let
   645     val rule =
   646       thm
   647       |> Drule.forall_elim_vars 0
   648       |> Drule.implies_intr_list casms;
   649     val {sign, prop, ...} = Thm.rep_thm rule;
   650     val frees = map (Thm.cterm_of sign) (mapfilter (find_free prop) fixes);
   651   in
   652     rule
   653     |> Drule.forall_intr_list frees
   654     |> Drule.forall_elim_vars 0
   655     |> Drule.tvars_intr_list tfrees
   656   end;
   657 
   658 fun diff_context inner None = (gen_tfrees inner None, fixed_names inner, assumptions inner)
   659   | diff_context inner (Some outer) =
   660       (gen_tfrees inner (Some outer),
   661         fixed_names inner \\ fixed_names outer,
   662         Library.drop (length (assumptions outer), assumptions inner));
   663 
   664 in
   665 
   666 fun export_wrt inner opt_outer =
   667   let
   668     val (tfrees, fixes, asms) = diff_context inner opt_outer;
   669     val casms = map (Drule.mk_cgoal o #1) asms;
   670     val tacs = map #2 asms;
   671   in (export tfrees fixes casms, tacs) end;
   672 
   673 end;
   674 
   675 
   676 
   677 (** bindings **)
   678 
   679 (* update_binds *)
   680 
   681 fun del_bind (ctxt, xi) =
   682   ctxt
   683   |> map_context (fn (thy, data, asms, binds, thms, cases, defs) =>
   684       (thy, data, asms, Vartab.update ((xi, None), binds), thms, cases, defs));
   685 
   686 fun upd_bind (ctxt, ((x, i), t)) =
   687   let
   688     val T = Term.fastype_of t;
   689     val t' =
   690       if null (Term.term_tvars t \\ Term.typ_tvars T) then t
   691       else Var ((x ^ "_has_extra_type_vars_on_rhs", i), T);
   692   in
   693     ctxt
   694     |> declare_term t'
   695     |> map_context (fn (thy, data, asms, binds, thms, cases, defs) =>
   696         (thy, data, asms, Vartab.update (((x, i), Some (t', T)), binds), thms, cases, defs))
   697   end;
   698 
   699 fun del_upd_bind (ctxt, (xi, None)) = del_bind (ctxt, xi)
   700   | del_upd_bind (ctxt, (xi, Some t)) = upd_bind (ctxt, (xi, t));
   701 
   702 fun update_binds bs ctxt = foldl upd_bind (ctxt, bs);
   703 fun delete_update_binds bs ctxt = foldl del_upd_bind (ctxt, bs);
   704 
   705 
   706 (* simult_matches *)
   707 
   708 fun simult_matches ctxt [] = []
   709   | simult_matches ctxt pairs =
   710       let
   711         val maxidx = foldl (fn (i, (t1, t2)) =>
   712           Int.max (i, Int.max (Term.maxidx_of_term t1, Term.maxidx_of_term t2))) (~1, pairs);
   713         val envs = Unify.smash_unifiers (sign_of ctxt, Envir.empty maxidx, pairs);
   714         val env =
   715           (case Seq.pull envs of
   716             None => raise CONTEXT ("Pattern match failed!", ctxt)      (* FIXME improve msg (!?) *)
   717           | Some (env, _) => env);
   718         val binds =
   719           (*Note: Envir.norm_term ensures proper type instantiation*)
   720           map (apsnd (Envir.norm_term env)) (Envir.alist_of env);
   721       in binds end;
   722 
   723 
   724 (* add_binds(_i) *)
   725 
   726 local
   727 
   728 fun gen_bind prep (ctxt, (xi as (x, _), raw_t)) =
   729   ctxt |> delete_update_binds [(xi, apsome (prep ctxt) raw_t)];
   730 
   731 fun gen_binds prep binds ctxt = foldl (gen_bind prep) (ctxt, binds);
   732 
   733 in
   734 
   735 val add_binds = gen_binds read_term;
   736 val add_binds_i = gen_binds cert_term;
   737 
   738 val auto_bind_goal = add_binds_i o AutoBind.goal;
   739 val auto_bind_facts = add_binds_i oo AutoBind.facts;
   740 
   741 end;
   742 
   743 
   744 (* match_bind(_i) *)
   745 
   746 local
   747 
   748 fun prep_bind (prep, prep_pats) (ctxt, (raw_pats, raw_t)) =
   749   let
   750     val t = prep ctxt raw_t;
   751     val ctxt' = declare_term t ctxt;
   752     val pats = prep_pats (fastype_of t) ctxt' raw_pats;
   753     val binds = simult_matches ctxt' (map (rpair t) pats);
   754   in (ctxt', binds) end;
   755 
   756 fun gen_binds prepp gen raw_binds ctxt =
   757   let
   758     val (ctxt', binds) = apsnd flat (foldl_map (prep_bind prepp) (ctxt, raw_binds));
   759     val binds' =
   760       if gen then map (apsnd (generalize ctxt' ctxt)) binds
   761       else binds;
   762     val binds'' = map (apsnd Some) binds';
   763   in
   764     warn_extra_tfrees ctxt
   765      (if gen then ctxt (*sic!*) |> declare_terms (map #2 binds') |> add_binds_i binds''
   766       else ctxt' |> add_binds_i binds'')
   767   end;
   768 
   769 in
   770 
   771 val match_bind = gen_binds (read_term, read_term_pats);
   772 val match_bind_i = gen_binds (cert_term, cert_term_pats);
   773 
   774 end;
   775 
   776 
   777 (* proposition patterns *)
   778 
   779 fun prep_propp prep_prop prep_pats (ctxt, (raw_prop, (raw_pats1, raw_pats2))) =
   780   let
   781     val prop = prep_prop ctxt raw_prop;
   782     val ctxt' = declare_term prop ctxt;
   783 
   784     val pats = prep_pats ctxt' (raw_pats1 @ raw_pats2);    (*simultaneous type inference!*)
   785     val len1 = length raw_pats1;
   786   in (ctxt', (prop, (take (len1, pats), drop (len1, pats)))) end;
   787 
   788 val read_propp = prep_propp read_prop read_prop_pats;
   789 val cert_propp = prep_propp cert_prop cert_prop_pats;
   790 
   791 
   792 fun gen_bind_propp prepp (ctxt, propp) =
   793   let
   794     val (ctxt', (prop, (pats1, pats2))) = prepp (ctxt, propp);
   795     val pairs =
   796       map (rpair prop) pats1 @
   797       map (rpair (Logic.strip_imp_concl prop)) pats2;   (* FIXME handle params!? *)
   798     val binds = simult_matches ctxt' pairs;
   799 
   800     (*note: context evaluated now, binds added later (lazy)*)
   801     val gen = generalize ctxt' ctxt;
   802     fun gen_binds ct = ct |> add_binds_i (map (apsnd (Some o gen)) binds);
   803   in (ctxt' |> add_binds_i (map (apsnd Some) binds), (prop, gen_binds)) end;
   804 
   805 val bind_propp = gen_bind_propp read_propp;
   806 val bind_propp_i = gen_bind_propp cert_propp;
   807 
   808 
   809 
   810 (** theorems **)
   811 
   812 (* get_thm(s) *)
   813 
   814 fun get_thm (ctxt as Context {thy, thms, ...}) name =
   815   (case Symtab.lookup (thms, name) of
   816     Some (Some [th]) => th
   817   | Some (Some _) => raise CONTEXT ("Single theorem expected: " ^ quote name, ctxt)
   818   | _ => (PureThy.get_thm thy name handle THEORY (msg, _) => raise CONTEXT (msg, ctxt)));
   819 
   820 fun get_thms (ctxt as Context {thy, thms, ...}) name =
   821   (case Symtab.lookup (thms, name) of
   822     Some (Some ths) => ths
   823   | _ => (PureThy.get_thms thy name handle THEORY (msg, _) => raise CONTEXT (msg, ctxt)));
   824 
   825 fun get_thmss ctxt names = flat (map (get_thms ctxt) names);
   826 
   827 
   828 (* put_thm(s) *)
   829 
   830 fun put_thms ("", _) = I
   831   | put_thms (name, ths) = map_context
   832       (fn (thy, data, asms, binds, thms, cases, defs) =>
   833         (thy, data, asms, binds, Symtab.update ((name, Some ths), thms), cases, defs));
   834 
   835 fun put_thm (name, th) = put_thms (name, [th]);
   836 
   837 fun put_thmss [] ctxt = ctxt
   838   | put_thmss (th :: ths) ctxt = ctxt |> put_thms th |> put_thmss ths;
   839 
   840 
   841 (* reset_thms *)
   842 
   843 fun reset_thms name = map_context (fn (thy, data, asms, binds, thms, cases, defs) =>
   844   (thy, data, asms, binds, Symtab.update ((name, None), thms), cases, defs));
   845 
   846 
   847 (* have_thmss *)
   848 
   849 fun have_thmss more_ths name more_attrs ths_attrs ctxt =
   850   let
   851     fun app ((ct, ths), (th, attrs)) =
   852       let val (ct', th') = Thm.applys_attributes ((ct, th), attrs @ more_attrs)
   853       in (ct', th' :: ths) end
   854     val (ctxt', rev_thms) = foldl app ((ctxt, []), ths_attrs);
   855     val thms = flat (rev rev_thms) @ more_ths;
   856   in (ctxt' |> put_thms (name, thms), (name, thms)) end;
   857 
   858 
   859 
   860 (** assumptions **)
   861 
   862 (* assume *)
   863 
   864 local
   865 
   866 fun gen_assm prepp tac (ctxt, (name, attrs, raw_prop_pats)) =
   867   let
   868     val (ctxt', props) = foldl_map prepp (ctxt, raw_prop_pats);
   869 
   870     val cprops = map (Thm.cterm_of (sign_of ctxt')) props;
   871     val cprops_tac = map (rpair tac) cprops;
   872     val asms = map (Drule.forall_elim_vars 0 o Drule.assume_goal) cprops;
   873 
   874     val ths = map (fn th => ([th], [])) asms;
   875     val (ctxt'', (_, thms)) =
   876       ctxt'
   877       |> auto_bind_facts name props
   878       |> have_thmss [] name (attrs @ [Drule.tag_assumption]) ths;
   879 
   880     val ctxt''' =
   881       ctxt''
   882       |> map_context (fn (thy, data, ((asms_ct, asms_th), fixes), binds, thms, cases, defs) =>
   883         (thy, data, ((asms_ct @ cprops_tac, asms_th @ [(name, asms)]), fixes),
   884           binds, thms, cases, defs));
   885   in (ctxt''', (name, thms)) end;
   886 
   887 fun gen_assms prepp tac args ctxt =
   888   let val (ctxt', thmss) = foldl_map (gen_assm prepp tac) (ctxt, args)
   889   in (warn_extra_tfrees ctxt ctxt', (thmss, prems_of ctxt')) end;
   890 
   891 in
   892 
   893 val assume = gen_assms (apsnd #1 o bind_propp);
   894 val assume_i = gen_assms (apsnd #1 o bind_propp_i);
   895 
   896 end;
   897 
   898 
   899 (* variables *)
   900 
   901 fun prep_vars prep_typ check (ctxt, (xs, raw_T)) =
   902   let
   903     val _ = (case filter (not o Syntax.is_identifier) (map (check_skolem ctxt check) xs) of
   904       [] => () | bads => raise CONTEXT ("Bad variable name(s): " ^ commas_quote bads, ctxt));
   905 
   906     val opt_T = apsome (prep_typ ctxt) raw_T;
   907     val T = if_none opt_T TypeInfer.logicT;
   908     val ctxt' = ctxt |> declare_terms (map (fn x => Free (x, T)) xs);
   909   in (ctxt', (xs, opt_T)) end;
   910 
   911 val read_vars = prep_vars read_typ true;
   912 val cert_vars = prep_vars cert_typ false;
   913 
   914 
   915 (* fix *)
   916 
   917 local
   918 
   919 fun add_vars xs (fixes, names) =
   920   let
   921     val xs' = variantlist (xs, names);
   922     val fixes' = (xs ~~ map Syntax.skolem xs') @ fixes;
   923     val names' = xs' @ names;
   924   in (fixes', names') end;
   925 
   926 fun map_vars f = map_context (fn (thy, data, (assumes, vars), binds, thms, cases, defs) =>
   927   (thy, data, (assumes, f vars), binds, thms, cases, defs));
   928 
   929 fun gen_fix prep raw_vars ctxt =
   930   let
   931     val (ctxt', varss) = foldl_map prep (ctxt, raw_vars);
   932     val xs = flat (map fst varss);
   933   in
   934     (case Library.duplicates xs of
   935       [] => ()
   936     | dups => raise CONTEXT ("Duplicate variable name(s): " ^ commas_quote dups, ctxt));
   937     ctxt' |> map_vars (add_vars xs)
   938   end;
   939 
   940 in
   941 
   942 val fix = gen_fix read_vars;
   943 val fix_i = gen_fix cert_vars;
   944 
   945 end;
   946 
   947 
   948 
   949 (** cases **)
   950 
   951 fun check_case ctxt name (xs, ts) =
   952   if null (foldr Term.add_typ_tvars (map snd xs, [])) andalso
   953     null (foldr Term.add_term_vars (ts, [])) then ()
   954   else raise CONTEXT ("Illegal schematic variable(s) in case " ^ quote name, ctxt);
   955 
   956 fun get_case (ctxt as Context {cases, ...}) name =
   957   (case assoc (cases, name) of
   958     None => raise CONTEXT ("Unknown case: " ^ quote name, ctxt)
   959   | Some c => (check_case ctxt name c; c));
   960 
   961 
   962 fun add_cases xs = map_context (fn (thy, data, asms, binds, thms, cases, defs) =>
   963   (thy, data, asms, binds, thms, rev (filter_out (equal "" o #1) xs) @ cases, defs));
   964 
   965 
   966 
   967 (** theory setup **)
   968 
   969 val setup = [ProofDataData.init];
   970 
   971 
   972 end;