src/Pure/Isar/proof_context.ML
author ballarin
Thu Mar 24 17:03:37 2005 +0100 (2005-03-24 ago)
changeset 15624 484178635bd8
parent 15596 8665d08085df
child 15696 1da4ce092c0b
permissions -rw-r--r--
Further work on interpretation commands. New command `interpret' for
interpretation in proof contexts.
     1 (*  Title:      Pure/Isar/proof_context.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 Proof context information.
     6 *)
     7 
     8 (*Jia: changed: datatype context
     9        affected files:  make_context, map_context, init, put_data, add_syntax, map_defaults, del_bind, upd_bind, qualified, hide_thms, put_thms, reset_thms, gen_assms, map_fixes, add_cases
    10 
    11        added: put_delta, get_delta 
    12        06/01/05
    13 *)
    14 
    15 val show_structs = ref false;
    16 
    17 signature PROOF_CONTEXT =
    18 sig
    19   type context
    20   type exporter
    21   exception CONTEXT of string * context
    22   val theory_of: context -> theory
    23   val sign_of: context -> Sign.sg
    24   val is_fixed: context -> string -> bool
    25   val fixed_names_of: context -> string list
    26   val assumptions_of: context -> (cterm list * exporter) list
    27   val prems_of: context -> thm list
    28   val print_proof_data: theory -> unit
    29   val init: theory -> context
    30   val pretty_term: context -> term -> Pretty.T
    31   val pretty_typ: context -> typ -> Pretty.T
    32   val pretty_sort: context -> sort -> Pretty.T
    33   val pp: context -> Pretty.pp
    34   val pretty_thm: context -> thm -> Pretty.T
    35   val pretty_thms: context -> thm list -> Pretty.T
    36   val pretty_fact: context -> string * thm list -> Pretty.T
    37   val string_of_term: context -> term -> string
    38   val default_type: context -> string -> typ option
    39   val used_types: context -> string list
    40   val read_typ: context -> string -> typ
    41   val read_typ_raw: context -> string -> typ
    42   val cert_typ: context -> typ -> typ
    43   val cert_typ_raw: context -> typ -> typ
    44   val get_skolem: context -> string -> string
    45   val extern_skolem: context -> term -> term
    46   val read_termTs: context -> (string -> bool) -> (indexname -> typ option)
    47     -> (indexname -> sort option) -> string list -> (string * typ) list
    48     -> term list * (indexname * typ) list
    49   val read_termTs_schematic: context -> (string -> bool) -> (indexname -> typ option)
    50     -> (indexname -> sort option) -> string list -> (string * typ) list
    51     -> term list * (indexname * typ) list
    52   val read_term_liberal: context -> string -> term
    53   val read_term: context -> string -> term
    54   val read_prop: context -> string -> term
    55   val read_prop_schematic: context -> string -> term
    56   val read_terms: context -> string list -> term list
    57   val read_term_pats: typ -> context -> string list -> term list
    58   val read_prop_pats: context -> string list -> term list
    59   val cert_term: context -> term -> term
    60   val cert_prop: context -> term -> term
    61   val cert_term_pats: typ -> context -> term list -> term list
    62   val cert_prop_pats: context -> term list -> term list
    63   val declare_term: term -> context -> context
    64   val declare_terms: term list -> context -> context
    65   val warn_extra_tfrees: context -> context -> context
    66   val generalize: context -> context -> term list -> term list
    67   val find_free: term -> string -> term option
    68   val export: bool -> context -> context -> thm -> thm Seq.seq
    69   val export_standard: cterm list -> context -> context -> thm -> thm
    70   val drop_schematic: indexname * term option -> indexname * term option
    71   val add_binds: (indexname * string option) list -> context -> context
    72   val add_binds_i: (indexname * term option) list -> context -> context
    73   val auto_bind_goal: term list -> context -> context
    74   val auto_bind_facts: term list -> context -> context
    75   val match_bind: bool -> (string list * string) list -> context -> context
    76   val match_bind_i: bool -> (term list * term) list -> context -> context
    77   val read_propp: context * (string * (string list * string list)) list list
    78     -> context * (term * (term list * term list)) list list
    79   val cert_propp: context * (term * (term list * term list)) list list
    80     -> context * (term * (term list * term list)) list list
    81   val read_propp_schematic: context * (string * (string list * string list)) list list
    82     -> context * (term * (term list * term list)) list list
    83   val cert_propp_schematic: context * (term * (term list * term list)) list list
    84     -> context * (term * (term list * term list)) list list
    85   val bind_propp: context * (string * (string list * string list)) list list
    86     -> context * (term list list * (context -> context))
    87   val bind_propp_i: context * (term * (term list * term list)) list list
    88     -> context * (term list list * (context -> context))
    89   val bind_propp_schematic: context * (string * (string list * string list)) list list
    90     -> context * (term list list * (context -> context))
    91   val bind_propp_schematic_i: context * (term * (term list * term list)) list list
    92     -> context * (term list list * (context -> context))
    93   val get_thm: context -> thmref -> thm
    94   val get_thm_closure: context -> thmref -> thm
    95   val get_thms: context -> thmref -> thm list
    96   val get_thms_closure: context -> thmref -> thm list
    97   val cond_extern: context -> string -> xstring
    98   val qualified: bool -> context -> context
    99   val restore_qualified: context -> context -> context
   100   val hide_thms: bool -> string list -> context -> context
   101   val put_thm: string * thm -> context -> context
   102   val put_thms: string * thm list -> context -> context
   103   val put_thmss: (string * thm list) list -> context -> context
   104   val reset_thms: string -> context -> context
   105   val note_thmss:
   106     ((bstring * context attribute list) * (thmref * context attribute list) list) list ->
   107       context -> context * (bstring * thm list) list
   108   val note_thmss_i:
   109     ((bstring * context attribute list) * (thm list * context attribute list) list) list ->
   110       context -> context * (bstring * thm list) list
   111   val export_assume: exporter
   112   val export_presume: exporter
   113   val cert_def: context -> term -> string * term
   114   val export_def: exporter
   115   val assume: exporter
   116     -> ((string * context attribute list) * (string * (string list * string list)) list) list
   117     -> context -> context * (bstring * thm list) list
   118   val assume_i: exporter
   119     -> ((string * context attribute list) * (term * (term list * term list)) list) list
   120     -> context -> context * (bstring * thm list) list
   121   val read_vars: context * (string list * string option)
   122     -> context * (string list * typ option)
   123   val cert_vars: context * (string list * typ option)
   124     -> context * (string list * typ option)
   125   val read_vars_liberal: context * (string list * string option)
   126     -> context * (string list * typ option)
   127   val cert_vars_liberal: context * (string list * typ option)
   128     -> context * (string list * typ option)
   129   val fix: (string list * string option) list -> context -> context
   130   val fix_i: (string list * typ option) list -> context -> context
   131   val add_fixes: (string * typ option * Syntax.mixfix option) list -> context -> context
   132   val add_fixes_liberal: (string * typ option * Syntax.mixfix option) list -> context -> context
   133   val fix_frees: term list -> context -> context
   134   val bind_skolem: context -> string list -> term -> term
   135   val get_case: context -> string -> string option list -> RuleCases.T
   136   val add_cases: (string * RuleCases.T) list -> context -> context
   137   val apply_case: RuleCases.T -> context
   138     -> context * ((indexname * term option) list * (string * term list) list)
   139   val verbose: bool ref
   140   val setmp_verbose: ('a -> 'b) -> 'a -> 'b
   141   val print_syntax: context -> unit
   142   val print_binds: context -> unit
   143   val print_lthms: context -> unit
   144   val print_cases: context -> unit
   145   val prems_limit: int ref
   146   val pretty_asms: context -> Pretty.T list
   147   val pretty_context: context -> Pretty.T list
   148   val thms_containing_limit: int ref
   149   val print_thms_containing: context -> int option -> string list -> unit
   150   val setup: (theory -> theory) list
   151 
   152   val get_delta: context -> Object.T Symtab.table (* Jia: (claset, simpset) *)
   153   val put_delta: Object.T Symtab.table -> context -> context 
   154   val get_delta_count_incr: context -> int
   155 
   156 end;
   157 
   158 signature PRIVATE_PROOF_CONTEXT =
   159 sig
   160   include PROOF_CONTEXT
   161   val init_data: Object.kind -> (theory -> Object.T) * (context -> Object.T -> unit)
   162     -> theory -> theory
   163   val print_data: Object.kind -> context -> unit
   164   val get_data: Object.kind -> (Object.T -> 'a) -> context -> 'a
   165   val put_data: Object.kind -> ('a -> Object.T) -> 'a -> context -> context
   166 end;
   167 
   168 structure ProofContext: PRIVATE_PROOF_CONTEXT =
   169 struct
   170 
   171 
   172 (** datatype context **)
   173 
   174 type exporter = bool -> cterm list -> thm -> thm Seq.seq;
   175 
   176 (* note: another field added to context. *)
   177 datatype context =
   178   Context of
   179    {thy: theory,                                              (*current theory*)
   180     syntax: Syntax.syntax * string list * string list,        (*syntax with structs and mixfixed*)
   181     data: Object.T Symtab.table,                              (*user data*)
   182     asms:
   183       ((cterm list * exporter) list *                         (*assumes: A ==> _*)
   184         (string * thm list) list) *                           (*prems: A |- A *)
   185       (string * string) list,                                 (*fixes: !!x. _*)
   186     binds: (term * typ) option Vartab.table,                  (*term bindings*)
   187     thms: bool * NameSpace.T * thm list option Symtab.table
   188       * FactIndex.T,                                          (*local thms*)
   189     (*thms is of the form (q, n, t, i) where
   190        q: indicates whether theorems with qualified names may be stored;
   191           this is initially forbidden (false); flag may be changed with
   192           qualified and restore_qualified;
   193        n: theorem namespace;
   194        t: table of theorems;
   195        i: index for theorem lookup (cf. thms_containing) *)
   196     cases: (string * RuleCases.T) list,                       (*local contexts*)
   197     defs:
   198       typ Vartab.table *                                      (*type constraints*)
   199       sort Vartab.table *                                     (*default sorts*)
   200       string list *                                           (*used type variables*)
   201       term list Symtab.table,
   202     delta: Object.T Symtab.table (* difference between local and global claset and simpset*),
   203     delta_count: int ref (* number of local anonymous thms *)
   204 };                                (*type variable occurrences*)
   205 
   206 exception CONTEXT of string * context;
   207 
   208 
   209 fun make_context (thy, syntax, data, asms, binds, thms, cases, defs, delta, delta_count) =
   210   Context {thy = thy, syntax = syntax, data = data, asms = asms, binds = binds,
   211     thms = thms, cases = cases, defs = defs, delta = delta, delta_count = delta_count};
   212 
   213 fun map_context f (Context {thy, syntax, data, asms, binds, thms, cases, defs, delta, delta_count}) =
   214   make_context (f (thy, syntax, data, asms, binds, thms, cases, defs, delta, delta_count));
   215 
   216 fun theory_of (Context {thy, ...}) = thy;
   217 val sign_of = Theory.sign_of o theory_of;
   218 fun syntax_of (Context {syntax, ...}) = syntax;
   219 
   220 fun fixes_of (Context {asms = (_, fixes), ...}) = fixes;
   221 val fixed_names_of = map #2 o fixes_of;
   222 fun is_fixed ctxt x = exists (equal x o #2) (fixes_of ctxt);
   223 fun is_known (ctxt as Context {defs = (types, _, _, _), ...}) x =
   224   isSome (Vartab.lookup (types, (x, ~1))) orelse is_fixed ctxt x;
   225 fun type_occs (Context {defs = (_, _, _, tab), ...}) = tab;
   226 
   227 fun assumptions_of (Context {asms = ((asms, _), _), ...}) = asms;
   228 fun prems_of (Context {asms = ((_, prems), _), ...}) = List.concat (map #2 prems);
   229 
   230 
   231 
   232 (** user data **)
   233 
   234 (* errors *)
   235 
   236 fun of_theory thy = "\nof theory " ^ Sign.str_of_sg (Theory.sign_of thy);
   237 
   238 fun err_inconsistent kinds =
   239   error ("Attempt to merge different versions of " ^ commas_quote kinds ^ " proof data");
   240 
   241 fun err_dup_init thy kind =
   242   error ("Duplicate initialization of " ^ quote kind ^ " proof data" ^ of_theory thy);
   243 
   244 fun err_undef ctxt kind =
   245   raise CONTEXT ("Tried to access undefined " ^ quote kind ^ " proof data", ctxt);
   246 
   247 fun err_uninit ctxt kind =
   248   raise CONTEXT ("Tried to access uninitialized " ^ quote kind ^ " proof data" ^
   249     of_theory (theory_of ctxt), ctxt);
   250 
   251 fun err_access ctxt kind =
   252   raise CONTEXT ("Unauthorized access to " ^ quote kind ^ " proof data" ^
   253     of_theory (theory_of ctxt), ctxt);
   254 
   255 
   256 (* data kind 'Isar/proof_data' *)
   257 
   258 structure ProofDataDataArgs =
   259 struct
   260   val name = "Isar/proof_data";
   261   type T = (Object.kind * ((theory -> Object.T) * (context -> Object.T -> unit))) Symtab.table;
   262 
   263   val empty = Symtab.empty;
   264   val copy = I;
   265   val prep_ext = I;
   266   fun merge tabs = Symtab.merge (Object.eq_kind o pairself fst) tabs
   267     handle Symtab.DUPS kinds => err_inconsistent kinds;
   268   fun print _ tab = Pretty.writeln (Pretty.strs (map #1 (Symtab.dest tab)));
   269 end;
   270 
   271 structure ProofDataData = TheoryDataFun(ProofDataDataArgs);
   272 val print_proof_data = ProofDataData.print;
   273 
   274 
   275 (* init proof data *)
   276 
   277 fun init_data kind meths thy =
   278   let
   279     val name = Object.name_of_kind kind;
   280     val tab = Symtab.update_new ((name, (kind, meths)), ProofDataData.get thy)
   281       handle Symtab.DUP _ => err_dup_init thy name;
   282   in thy |> ProofDataData.put tab end;
   283 
   284 
   285 (* access data *)
   286 
   287 fun lookup_data (ctxt as Context {data, ...}) kind =
   288   let
   289     val thy = theory_of ctxt;
   290     val name = Object.name_of_kind kind;
   291   in
   292     (case Symtab.lookup (ProofDataData.get thy, name) of
   293       SOME (k, meths) =>
   294         if Object.eq_kind (kind, k) then
   295           (case Symtab.lookup (data, name) of
   296             SOME x => (x, meths)
   297           | NONE => err_undef ctxt name)
   298         else err_access ctxt name
   299     | NONE => err_uninit ctxt name)
   300   end;
   301 
   302 fun get_data kind f ctxt =
   303   let val (x, _) = lookup_data ctxt kind
   304   in f x handle Match => Object.kind_error kind end;
   305 
   306 fun print_data kind ctxt =
   307   let val (x, (_, prt)) = lookup_data ctxt kind
   308   in prt ctxt x end;
   309 
   310 fun put_data kind f x ctxt =
   311  (lookup_data ctxt kind;
   312   map_context (fn (thy, syntax, data, asms, binds, thms, cases, defs, delta,delta_count) =>
   313     (thy, syntax, Symtab.update ((Object.name_of_kind kind, f x), data),
   314       asms, binds, thms, cases, defs, delta, delta_count)) ctxt);
   315 
   316 
   317 (* added get_delta and put_delta *)
   318 
   319 fun get_delta (ctxt as Context {delta, ...}) = delta;
   320 
   321 fun get_delta_count (ctxt as Context {delta_count, ...}) = !delta_count;
   322 
   323 fun get_delta_count_incr (ctxt as Context {delta_count, ...}) =
   324   let val current_delta_count = !delta_count
   325   in
   326     (delta_count:=(!delta_count)+1;current_delta_count)
   327 end;
   328 
   329 fun incr_delta_count (ctxt as Context {delta_count, ...}) = (delta_count:=(!delta_count)+1);
   330 
   331 (* replace the old delta by new delta *)
   332 (* count not changed! *)
   333 fun put_delta new_delta ctxt =
   334     map_context (fn (thy, syntax, data, asms, binds, thms, cases, defs,delta, delta_count) =>
   335     (thy, syntax, data, asms, binds, thms, cases, defs, new_delta,delta_count)) ctxt;
   336 
   337 
   338 (* init context *)
   339 
   340 fun init thy =
   341   let val data = Symtab.map (fn (_, (f, _)) => f thy) (ProofDataData.get thy) in
   342     make_context (thy, (Theory.syn_of thy, [], []), data, (([], []), []), Vartab.empty,
   343       (false, NameSpace.empty, Symtab.empty, FactIndex.empty), [],
   344       (Vartab.empty, Vartab.empty, [], Symtab.empty), Symtab.empty, ref 0)
   345   end;
   346 
   347 
   348 
   349 (** local syntax **)
   350 
   351 val fixedN = "\\<^fixed>";
   352 val structN = "\\<^struct>";
   353 
   354 
   355 (* translation functions *)
   356 
   357 fun fixed_tr x = (fixedN ^ x, curry Term.list_comb (Syntax.free x));
   358 
   359 fun context_tr' ctxt =
   360   let
   361     val (_, structs, mixfixed) = syntax_of ctxt;
   362 
   363     fun tr' (t $ u) = tr' t $ tr' u
   364       | tr' (Abs (x, T, t)) = Abs (x, T, tr' t)
   365       | tr' (t as Free (x, T)) =
   366           let val i = Library.find_index_eq x structs + 1 in
   367             if i = 0 andalso x mem_string mixfixed then Const (fixedN ^ x, T)
   368             else if i = 1 andalso not (! show_structs) then
   369               Syntax.const "_struct" $ Syntax.const "_indexdefault"
   370             else t
   371           end
   372       | tr' a = a;
   373   in tr' end;
   374 
   375 
   376 (* add syntax *)
   377 
   378 fun mixfix_type mx = replicate (Syntax.mixfix_args mx) TypeInfer.logicT ---> TypeInfer.logicT;
   379 
   380 local
   381 
   382 fun mixfix x NONE mx = (fixedN ^ x, mixfix_type mx, Syntax.fix_mixfix x mx)
   383   | mixfix x (SOME T) mx = (fixedN ^ x, T, Syntax.fix_mixfix x mx);
   384 
   385 fun prep_mixfix (_, _, NONE) = NONE
   386   | prep_mixfix (x, opt_T, SOME mx) = SOME (mixfix x opt_T mx);
   387 
   388 fun prep_mixfix' (_, _, NONE) = NONE
   389   | prep_mixfix' (x, _, SOME Syntax.NoSyn) = NONE
   390   | prep_mixfix' (x, opt_T, _) = SOME (x, mixfix x opt_T (Syntax.literal x));
   391 
   392 fun prep_struct (x, _, NONE) = SOME x
   393   | prep_struct _ = NONE;
   394 
   395 in
   396 
   397 fun add_syntax decls =
   398   map_context (fn (thy, (syn, structs, mixfixed), data, asms, binds, thms, cases, defs, delta, delta_count) =>
   399     let
   400       val is_logtype = Sign.is_logtype (Theory.sign_of thy);
   401       val structs' = structs @ List.mapPartial prep_struct decls;
   402       val mxs = List.mapPartial prep_mixfix decls;
   403       val (fixed, mxs_output) = Library.split_list (List.mapPartial prep_mixfix' decls);
   404       val trs = map fixed_tr fixed;
   405       val syn' = syn
   406         |> Syntax.extend_const_gram is_logtype ("", false) mxs_output
   407         |> Syntax.extend_const_gram is_logtype ("", true) mxs
   408         |> Syntax.extend_trfuns ([], trs, [], []);
   409     in (thy, (syn', structs', fixed @ mixfixed), data, asms, binds, thms, cases, defs, delta, delta_count) end)
   410 
   411 fun syn_of (Context {syntax = (syn, structs, _), ...}) =
   412   syn |> Syntax.extend_trfuns (Syntax.struct_trfuns structs);
   413 
   414 end;
   415 
   416 
   417 
   418 (** pretty printing **)
   419 
   420 fun pretty_term ctxt t = Sign.pretty_term' (syn_of ctxt) (sign_of ctxt) (context_tr' ctxt t);
   421 fun pretty_typ ctxt T = Sign.pretty_typ (sign_of ctxt) T;
   422 fun pretty_sort ctxt S = Sign.pretty_sort (sign_of ctxt) S;
   423 fun pretty_classrel ctxt cs = Sign.pretty_classrel (sign_of ctxt) cs;
   424 fun pretty_arity ctxt ar = Sign.pretty_arity (sign_of ctxt) ar;
   425 
   426 fun pp ctxt = Pretty.pp (pretty_term ctxt, pretty_typ ctxt, pretty_sort ctxt,
   427   pretty_classrel ctxt, pretty_arity ctxt);
   428 
   429 val string_of_term = Pretty.string_of oo pretty_term;
   430 
   431 fun pretty_thm ctxt thm =
   432   if ! Display.show_hyps then
   433     Display.pretty_thm_aux (pp ctxt) false thm
   434   else pretty_term ctxt (Thm.prop_of thm);
   435 
   436 fun pretty_thms ctxt [th] = pretty_thm ctxt th
   437   | pretty_thms ctxt ths = Pretty.blk (0, Pretty.fbreaks (map (pretty_thm ctxt) ths));
   438 
   439 fun pretty_fact ctxt ("", ths) = pretty_thms ctxt ths
   440   | pretty_fact ctxt (a, [th]) =
   441       Pretty.block [Pretty.str (a ^ ":"), Pretty.brk 1, pretty_thm ctxt th]
   442   | pretty_fact ctxt (a, ths) =
   443       Pretty.block (Pretty.fbreaks (Pretty.str (a ^ ":") :: map (pretty_thm ctxt) ths));
   444 
   445 
   446 
   447 (** default sorts and types **)
   448 
   449 fun def_sort (Context {defs = (_, sorts, _, _), ...}) xi = Vartab.lookup (sorts, xi);
   450 
   451 fun def_type (Context {binds, defs = (types, _, _, _), ...}) pattern xi =
   452   (case Vartab.lookup (types, xi) of
   453     NONE =>
   454       if pattern then NONE else
   455         (case Vartab.lookup (binds, xi) of
   456           SOME (SOME (_, T)) => SOME (TypeInfer.polymorphicT T)
   457         | _ => NONE)
   458   | some => some);
   459 
   460 fun default_type (Context {defs = (types, _, _, _), ...}) x = Vartab.lookup (types, (x, ~1));
   461 fun used_types (Context {defs = (_, _, used, _), ...}) = used;
   462 
   463 
   464 
   465 (** prepare types **)
   466 
   467 local
   468 
   469 fun read_typ_aux read ctxt s =
   470   transform_error (read (syn_of ctxt) (sign_of ctxt, def_sort ctxt)) s
   471     handle ERROR_MESSAGE msg => raise CONTEXT (msg, ctxt);
   472 
   473 fun cert_typ_aux cert ctxt raw_T =
   474   cert (sign_of ctxt) raw_T
   475     handle TYPE (msg, _, _) => raise CONTEXT (msg, ctxt);
   476 
   477 in
   478 
   479 (* Read/certify type, using default sort information from context. *)
   480 
   481 val read_typ     = read_typ_aux Sign.read_typ';
   482 val read_typ_raw = read_typ_aux Sign.read_typ_raw';
   483 val cert_typ     = cert_typ_aux Sign.certify_typ;
   484 val cert_typ_raw = cert_typ_aux Sign.certify_typ_raw;
   485 
   486 end;
   487 
   488 
   489 (* internalize Skolem constants *)
   490 
   491 fun lookup_skolem ctxt x = assoc (fixes_of ctxt, x);
   492 fun get_skolem ctxt x = getOpt (lookup_skolem ctxt x, x);
   493 
   494 fun no_skolem internal ctxt x =
   495   if can Syntax.dest_skolem x then
   496     raise CONTEXT ("Illegal reference to internal Skolem constant: " ^ quote x, ctxt)
   497   else if not internal andalso can Syntax.dest_internal x then
   498     raise CONTEXT ("Illegal reference to internal variable: " ^ quote x, ctxt)
   499   else x;
   500 
   501 fun intern_skolem ctxt internal =
   502   let
   503     fun intern (t as Free (x, T)) =
   504           if internal x then t
   505           else
   506             (case lookup_skolem ctxt (no_skolem false ctxt x) of
   507               SOME x' => Free (x', T)
   508             | NONE => t)
   509       | intern (t $ u) = intern t $ intern u
   510       | intern (Abs (x, T, t)) = Abs (x, T, intern t)
   511       | intern a = a;
   512   in intern end;
   513 
   514 
   515 (* externalize Skolem constants -- for printing purposes only *)
   516 
   517 fun extern_skolem ctxt =
   518   let
   519     val rev_fixes = map Library.swap (fixes_of ctxt);
   520 
   521     fun extern (t as Free (x, T)) =
   522           (case assoc (rev_fixes, x) of
   523             SOME x' => Free (if lookup_skolem ctxt x' = SOME x then x' else NameSpace.hidden x', T)
   524           | NONE => t)
   525       | extern (t $ u) = extern t $ extern u
   526       | extern (Abs (x, T, t)) = Abs (x, T, extern t)
   527       | extern a = a;
   528   in extern end
   529 
   530 
   531 (** prepare terms and propositions **)
   532 
   533 (*
   534   (1) read / certify wrt. signature of context
   535   (2) intern Skolem constants
   536   (3) expand term bindings
   537 *)
   538 
   539 
   540 (* read / certify wrt. signature *)     (*exception ERROR*) (*exception TERM*)
   541 
   542 fun read_def_termTs freeze pp syn sg (types, sorts, used) sTs =
   543   Sign.read_def_terms' pp (Sign.is_logtype sg) syn (sg, types, sorts) used freeze sTs;
   544 
   545 fun read_def_termT freeze pp syn sg defs sT =
   546   apfst hd (read_def_termTs freeze pp syn sg defs [sT]);
   547 
   548 fun read_term_sg freeze pp syn sg defs s =
   549   #1 (read_def_termT freeze pp syn sg defs (s, TypeInfer.logicT));
   550 
   551 fun read_prop_sg freeze pp syn sg defs s =
   552   #1 (read_def_termT freeze pp syn sg defs (s, propT));
   553 
   554 fun read_terms_sg freeze pp syn sg defs =
   555   #1 o read_def_termTs freeze pp syn sg defs o map (rpair TypeInfer.logicT);
   556 
   557 fun read_props_sg freeze pp syn sg defs =
   558   #1 o read_def_termTs freeze pp syn sg defs o map (rpair propT);
   559 
   560 
   561 fun cert_term_sg pp sg t = #1 (Sign.certify_term pp sg t);
   562 
   563 fun cert_prop_sg pp sg tm =
   564   let val (t, T, _) = Sign.certify_term pp sg tm
   565   in if T = propT then t else raise TERM ("Term not of type prop", [t]) end;
   566 
   567 
   568 (* norm_term *)
   569 
   570 (*beta normal form for terms (not eta normal form), chase variables in
   571   bindings environment (code taken from Pure/envir.ML)*)
   572 
   573 fun unifyT ctxt (T, U) =
   574   let val maxidx = Int.max (Term.maxidx_of_typ T, Term.maxidx_of_typ U)
   575   in #1 (Type.unify (Sign.tsig_of (sign_of ctxt)) (Vartab.empty, maxidx) (T, U)) end;
   576 
   577 fun norm_term (ctxt as Context {binds, ...}) schematic =
   578   let
   579     (*raised when norm has no effect on a term, to do sharing instead of copying*)
   580     exception SAME;
   581 
   582     fun norm (t as Var (xi, T)) =
   583           (case Vartab.lookup (binds, xi) of
   584             SOME (SOME (u, U)) =>
   585               let
   586                 val env = unifyT ctxt (T, U) handle Type.TUNIFY =>
   587                   raise TYPE ("norm_term: ill-typed variable assignment", [T, U], [t, u]);
   588                 val u' = Term.subst_TVars_Vartab env u;
   589               in norm u' handle SAME => u' end
   590           | _ =>
   591             if schematic then raise SAME
   592             else raise CONTEXT ("Unbound schematic variable: " ^ Syntax.string_of_vname xi, ctxt))
   593       | norm (Abs (a, T, body)) =  Abs (a, T, norm body)
   594       | norm (Abs (_, _, body) $ t) = normh (subst_bound (t, body))
   595       | norm (f $ t) =
   596           ((case norm f of
   597             Abs (_, _, body) => normh (subst_bound (t, body))
   598           | nf => nf $ (norm t handle SAME => t)) handle SAME => f $ norm t)
   599       | norm _ =  raise SAME
   600     and normh t = norm t handle SAME => t
   601   in normh end;
   602 
   603 
   604 (* dummy patterns *)
   605 
   606 fun prepare_dummies t = #2 (Term.replace_dummy_patterns (1, t));
   607 
   608 fun reject_dummies ctxt t = Term.no_dummy_patterns t
   609   handle TERM _ => raise CONTEXT ("Illegal dummy pattern(s) in term", ctxt);
   610 
   611 
   612 (* read terms *)
   613 
   614 local
   615 
   616 fun append_env e1 e2 x = (case e2 x of NONE => e1 x | some => some);
   617 
   618 fun gen_read' read app pattern dummies schematic
   619     ctxt internal more_types more_sorts more_used s =
   620   let
   621     val types = append_env (def_type ctxt pattern) more_types;
   622     val sorts = append_env (def_sort ctxt) more_sorts;
   623     val used = used_types ctxt @ more_used;
   624   in
   625     (transform_error (read (pp ctxt) (syn_of ctxt) (sign_of ctxt) (types, sorts, used)) s
   626       handle TERM (msg, _) => raise CONTEXT (msg, ctxt)
   627         | ERROR_MESSAGE msg => raise CONTEXT (msg, ctxt))
   628     |> app (intern_skolem ctxt internal)
   629     |> app (if pattern then I else norm_term ctxt schematic)
   630     |> app (if pattern then prepare_dummies else if dummies then I else reject_dummies ctxt)
   631   end;
   632 
   633 fun gen_read read app pattern dummies schematic ctxt =
   634   gen_read' read app pattern dummies schematic ctxt (K false) (K NONE) (K NONE) [];
   635 
   636 in
   637 
   638 (* CB: for attribute where.  See attrib.ML. *)
   639 val read_termTs           = gen_read' (read_def_termTs false) (apfst o map) false false false;
   640 
   641 (* CB: for rule_tac etc.  See method.ML. *)
   642 val read_termTs_schematic = gen_read' (read_def_termTs false) (apfst o map) false false true;
   643 
   644 fun read_term_pats T ctxt =
   645   #1 o gen_read (read_def_termTs false) (apfst o map) true false false ctxt o map (rpair T);
   646 val read_prop_pats = read_term_pats propT;
   647 
   648 fun read_term_liberal ctxt =
   649   gen_read' (read_term_sg true) I false false false ctxt (K true) (K NONE) (K NONE) [];
   650 
   651 val read_term              = gen_read (read_term_sg true) I false false false;
   652 val read_term_dummies      = gen_read (read_term_sg true) I false true false;
   653 val read_prop              = gen_read (read_prop_sg true) I false false false;
   654 val read_prop_schematic    = gen_read (read_prop_sg true) I false false true;
   655 val read_terms             = gen_read (read_terms_sg true) map false false false;
   656 fun read_props schematic   = gen_read (read_props_sg true) map false false schematic;
   657 
   658 end;
   659 
   660 
   661 (* certify terms *)
   662 
   663 local
   664 
   665 fun gen_cert cert pattern schematic ctxt t = t
   666   |> (if pattern then I else norm_term ctxt schematic)
   667   |> (fn t' => cert (pp ctxt) (sign_of ctxt) t'
   668     handle TERM (msg, _) => raise CONTEXT (msg, ctxt));
   669 
   670 in
   671 
   672 val cert_term = gen_cert cert_term_sg false false;
   673 val cert_prop = gen_cert cert_prop_sg false false;
   674 val cert_props = map oo gen_cert cert_prop_sg false;
   675 
   676 fun cert_term_pats _ = map o gen_cert cert_term_sg true false;
   677 val cert_prop_pats = map o gen_cert cert_prop_sg true false;
   678 
   679 end;
   680 
   681 
   682 (* declare terms *)
   683 
   684 local
   685 
   686 val ins_types = foldl_aterms
   687   (fn (types, Free (x, T)) => Vartab.update (((x, ~1), T), types)
   688     | (types, Var v) => Vartab.update (v, types)
   689     | (types, _) => types);
   690 
   691 val ins_sorts = foldl_types (foldl_atyps
   692   (fn (sorts, TFree (x, S)) => Vartab.update (((x, ~1), S), sorts)
   693     | (sorts, TVar v) => Vartab.update (v, sorts)
   694     | (sorts, _) => sorts));
   695 
   696 val ins_used = foldl_term_types (fn t => foldl_atyps
   697   (fn (used, TFree (x, _)) => x ins_string used
   698     | (used, _) => used));
   699 
   700 val ins_occs = foldl_term_types (fn t => foldl_atyps
   701   (fn (tab, TFree (x, _)) => Symtab.update_multi ((x, t), tab) | (tab, _) => tab));
   702 
   703 fun ins_skolem def_ty = foldr
   704   (fn ((x, x'), types) =>
   705     (case def_ty x' of
   706       SOME T => Vartab.update (((x, ~1), T), types)
   707     | NONE => types));
   708 
   709 fun map_defaults f = map_context (fn (thy, syntax, data, asms, binds, thms, cases, defs, delta, delta_count) =>
   710   (thy, syntax, data, asms, binds, thms, cases, f defs, delta, delta_count));
   711 
   712 fun declare_syn (ctxt, t) =
   713   ctxt
   714   |> map_defaults (fn (types, sorts, used, occ) => (ins_types (types, t), sorts, used, occ))
   715   |> map_defaults (fn (types, sorts, used, occ) => (types, ins_sorts (sorts, t), used, occ))
   716   |> map_defaults (fn (types, sorts, used, occ) => (types, sorts, ins_used (used, t), occ));
   717 
   718 fun declare_occ (ctxt as Context {asms = (_, fixes), ...}, t) =
   719   declare_syn (ctxt, t)
   720   |> map_defaults (fn (types, sorts, used, occ) => (types, sorts, used, ins_occs (occ, t)))
   721   |> map_defaults (fn (types, sorts, used, occ) =>
   722       (ins_skolem (fn x => Vartab.lookup (types, (x, ~1))) types fixes, sorts, used, occ));
   723 
   724 in
   725 
   726 fun declare_term t ctxt = declare_occ (ctxt, t);
   727 fun declare_terms ts ctxt = Library.foldl declare_occ (ctxt, ts);
   728 fun declare_terms_syntax ts ctxt = Library.foldl declare_syn (ctxt, ts);
   729 
   730 end;
   731 
   732 
   733 
   734 (** Hindley-Milner polymorphism **)
   735 
   736 (* warn_extra_tfrees *)
   737 
   738 fun warn_extra_tfrees
   739     (ctxt1 as Context {defs = (_, _, _, occ1), ...})
   740     (ctxt2 as Context {defs = (_, _, _, occ2), ...}) =
   741   let
   742     fun known_tfree a (Type (_, Ts)) = exists (known_tfree a) Ts
   743       | known_tfree a (TFree (a', _)) = a = a'
   744       | known_tfree _ _ = false;
   745 
   746     val extras =
   747       Library.gen_rems Library.eq_fst (Symtab.dest occ2, Symtab.dest occ1)
   748       |> map (fn (a, ts) => map (pair a) (List.mapPartial (try (#1 o Term.dest_Free)) ts)) |> List.concat
   749       |> List.mapPartial (fn (a, x) =>
   750           (case def_type ctxt1 false (x, ~1) of NONE => SOME (a, x)
   751           | SOME T => if known_tfree a T then NONE else SOME (a, x)));
   752     val tfrees = map #1 extras |> Library.sort_strings |> Library.unique_strings;
   753     val frees = map #2 extras |> Library.sort_strings |> Library.unique_strings;
   754   in
   755     if null extras then ()
   756     else warning ("Just introduced free type variable(s): " ^ commas tfrees ^ " in " ^
   757       space_implode " or " frees);
   758     ctxt2
   759   end;
   760 
   761 
   762 (* generalize type variables *)
   763 
   764 fun generalize_tfrees inner outer =
   765   let
   766     val extra_fixes = fixed_names_of inner \\ fixed_names_of outer;
   767     fun still_fixed (Free (x, _)) = not (x mem_string extra_fixes)
   768       | still_fixed _ = false;
   769     val occs_inner = type_occs inner;
   770     val occs_outer = type_occs outer;
   771     fun add (gen, a) =
   772       if isSome (Symtab.lookup (occs_outer, a)) orelse
   773         exists still_fixed (Symtab.lookup_multi (occs_inner, a))
   774       then gen else a :: gen;
   775   in fn tfrees => Library.foldl add ([], tfrees) end;
   776 
   777 fun generalize inner outer ts =
   778   let
   779     val tfrees = generalize_tfrees inner outer (foldr Term.add_term_tfree_names [] ts);
   780     fun gen (x, S) = if x mem_string tfrees then TVar ((x, 0), S) else TFree (x, S);
   781   in map (Term.map_term_types (Term.map_type_tfree gen)) ts end;
   782 
   783 
   784 
   785 (** export theorems **)
   786 
   787 fun get_free x (NONE, t as Free (y, _)) = if x = y then SOME t else NONE
   788   | get_free _ (opt, _) = opt;
   789 
   790 fun find_free t x = foldl_aterms (get_free x) (NONE, t);
   791 
   792 fun export_view view is_goal inner outer =
   793   let
   794     val gen = generalize_tfrees inner outer;
   795     val fixes = fixed_names_of inner \\ fixed_names_of outer;
   796     val asms = Library.drop (length (assumptions_of outer), assumptions_of inner);
   797     val exp_asms = map (fn (cprops, exp) => exp is_goal cprops) asms;
   798   in fn thm => thm
   799     |> Tactic.norm_hhf_rule
   800     |> Seq.EVERY (rev exp_asms)
   801     |> Seq.map (Drule.implies_intr_list view)
   802     |> Seq.map (fn rule =>
   803       let
   804         val {sign, prop, ...} = Thm.rep_thm rule;
   805         val frees = map (Thm.cterm_of sign) (List.mapPartial (find_free prop) fixes);
   806         val tfrees = gen (Term.add_term_tfree_names (prop, []));
   807       in
   808         rule
   809         |> Drule.forall_intr_list frees
   810         |> Tactic.norm_hhf_rule
   811         |> (#1 o Drule.tvars_intr_list tfrees)
   812       end)
   813   end;
   814 
   815 val export = export_view [];
   816 
   817 fun export_standard view inner outer =
   818   let val exp = export_view view false inner outer in
   819     fn th =>
   820       (case Seq.pull (exp th) of
   821         SOME (th', _) => th' |> Drule.local_standard
   822       | NONE => raise CONTEXT ("Internal failure while exporting theorem", inner))
   823   end;
   824 
   825 
   826 
   827 (** bindings **)
   828 
   829 (* update_binds *)
   830 
   831 fun del_bind (ctxt, xi) =
   832   ctxt
   833   |> map_context (fn (thy, syntax, data, asms, binds, thms, cases, defs, delta, delta_count) =>
   834       (thy, syntax, data, asms, Vartab.update ((xi, NONE), binds), thms, cases, defs, delta, delta_count));
   835 
   836 fun upd_bind (ctxt, ((x, i), t)) =
   837   let
   838     val T = Term.fastype_of t;
   839     val t' =
   840       if null (Term.term_tvars t \\ Term.typ_tvars T) then t
   841       else Var ((x ^ "_has_extra_type_vars_on_rhs", i), T);
   842   in
   843     ctxt
   844     |> declare_term t'
   845     |> map_context (fn (thy, syntax, data, asms, binds, thms, cases, defs, delta, delta_count) =>
   846       (thy, syntax, data, asms, Vartab.update (((x, i), SOME (t', T)), binds), thms, cases, defs, delta, delta_count))
   847   end;
   848 
   849 fun del_upd_bind (ctxt, (xi, NONE)) = del_bind (ctxt, xi)
   850   | del_upd_bind (ctxt, (xi, SOME t)) = upd_bind (ctxt, (xi, t));
   851 
   852 fun update_binds bs ctxt = Library.foldl upd_bind (ctxt, bs);
   853 fun delete_update_binds bs ctxt = Library.foldl del_upd_bind (ctxt, bs);
   854 
   855 
   856 (* simult_matches *)
   857 
   858 fun simult_matches ctxt [] = []
   859   | simult_matches ctxt pairs =
   860       let
   861         fun fail () = raise CONTEXT ("Pattern match failed!", ctxt);
   862 
   863         val maxidx = Library.foldl (fn (i, (t1, t2)) =>
   864           Int.max (i, Int.max (Term.maxidx_of_term t1, Term.maxidx_of_term t2))) (~1, pairs);
   865         val envs = Unify.smash_unifiers (sign_of ctxt, Envir.empty maxidx,
   866           map swap pairs);    (*prefer assignment of variables from patterns*)
   867         val env =
   868           (case Seq.pull envs of
   869             NONE => fail ()
   870           | SOME (env, _) => env);    (*ignore further results*)
   871         val domain =
   872           filter_out Term.is_replaced_dummy_pattern (map #1 (Drule.vars_of_terms (map #1 pairs)));
   873         val _ =    (*may not assign variables from text*)
   874           if null (map #1 (Envir.alist_of env) inter (map #1 (Drule.vars_of_terms (map #2 pairs))))
   875           then () else fail ();
   876         fun norm_bind (xi, t) = if xi mem domain then SOME (xi, Envir.norm_term env t) else NONE;
   877       in List.mapPartial norm_bind (Envir.alist_of env) end;
   878 
   879 
   880 (* add_binds(_i) *)
   881 
   882 local
   883 
   884 fun gen_bind prep (ctxt, (xi as (x, _), raw_t)) =
   885   ctxt |> delete_update_binds [(xi, Option.map (prep ctxt) raw_t)];
   886 
   887 fun gen_binds prep binds ctxt = Library.foldl (gen_bind prep) (ctxt, binds);
   888 
   889 in
   890 
   891 fun drop_schematic (b as (xi, SOME t)) = if null (Term.term_vars t) then b else (xi, NONE)
   892   | drop_schematic b = b;
   893 
   894 val add_binds = gen_binds read_term;
   895 val add_binds_i = gen_binds cert_term;
   896 
   897 fun auto_bind f ts ctxt = ctxt |> add_binds_i (map drop_schematic (f (sign_of ctxt) ts));
   898 val auto_bind_goal = auto_bind AutoBind.goal;
   899 val auto_bind_facts = auto_bind AutoBind.facts;
   900 
   901 end;
   902 
   903 
   904 (* match_bind(_i) *)
   905 
   906 local
   907 
   908 fun prep_bind prep_pats (ctxt, (raw_pats, t)) =
   909   let
   910     val ctxt' = declare_term t ctxt;
   911     val pats = prep_pats (fastype_of t) ctxt' raw_pats;
   912     val binds = simult_matches ctxt' (map (rpair t) pats);
   913   in (ctxt', binds) end;
   914 
   915 fun gen_binds prep_terms prep_pats gen raw_binds ctxt =
   916   let
   917     val ts = prep_terms ctxt (map snd raw_binds);
   918     val (ctxt', binds) =
   919       apsnd List.concat (foldl_map (prep_bind prep_pats) (ctxt, map fst raw_binds ~~ ts));
   920     val binds' =
   921       if gen then map #1 binds ~~ generalize ctxt' ctxt (map #2 binds)
   922       else binds;
   923     val binds'' = map (apsnd SOME) binds';
   924   in
   925     warn_extra_tfrees ctxt
   926      (if gen then ctxt (*sic!*) |> declare_terms (map #2 binds') |> add_binds_i binds''
   927       else ctxt' |> add_binds_i binds'')
   928   end;
   929 
   930 in
   931 
   932 val match_bind = gen_binds read_terms read_term_pats;
   933 val match_bind_i = gen_binds (map o cert_term) cert_term_pats;
   934 
   935 end;
   936 
   937 
   938 (* propositions with patterns *)
   939 
   940 local
   941 
   942 fun prep_propp schematic prep_props prep_pats (context, args) =
   943   let
   944     fun prep ((ctxt, prop :: props), (_, (raw_pats1, raw_pats2))) =
   945           let
   946             val ctxt' = declare_term prop ctxt;
   947             val pats = prep_pats ctxt' (raw_pats1 @ raw_pats2);    (*simultaneous type inference!*)
   948           in ((ctxt', props), (prop, splitAt(length raw_pats1, pats))) end
   949       | prep _ = sys_error "prep_propp";
   950     val ((context', _), propp) = foldl_map (foldl_map prep)
   951         ((context, prep_props schematic context (List.concat (map (map fst) args))), args);
   952   in (context', propp) end;
   953 
   954 fun matches ctxt (prop, (pats1, pats2)) =
   955   simult_matches ctxt (map (rpair prop) pats1 @ map (rpair (Logic.strip_imp_concl prop)) pats2);
   956 
   957 fun gen_bind_propp prepp (ctxt, raw_args) =
   958   let
   959     val (ctxt', args) = prepp (ctxt, raw_args);
   960     val binds = List.concat (List.concat (map (map (matches ctxt')) args));
   961     val propss = map (map #1) args;
   962 
   963     (*generalize result: context evaluated now, binds added later*)
   964     val gen = generalize ctxt' ctxt;
   965     fun gen_binds c = c |> add_binds_i (map #1 binds ~~ map SOME (gen (map #2 binds)));
   966   in (ctxt' |> add_binds_i (map (apsnd SOME) binds), (propss, gen_binds)) end;
   967 
   968 in
   969 
   970 val read_propp = prep_propp false read_props read_prop_pats;
   971 val cert_propp = prep_propp false cert_props cert_prop_pats;
   972 val read_propp_schematic = prep_propp true read_props read_prop_pats;
   973 val cert_propp_schematic = prep_propp true cert_props cert_prop_pats;
   974 
   975 val bind_propp = gen_bind_propp read_propp;
   976 val bind_propp_i = gen_bind_propp cert_propp;
   977 val bind_propp_schematic = gen_bind_propp read_propp_schematic;
   978 val bind_propp_schematic_i = gen_bind_propp cert_propp_schematic;
   979 
   980 end;
   981 
   982 
   983 
   984 (** theorems **)
   985 
   986 (* get_thm(s) *)
   987 
   988 (*beware of proper order of evaluation!*)
   989 fun retrieve_thms f g (ctxt as Context {thy, thms = (_, space, tab, _), ...}) =
   990   let
   991     val sg_ref = Sign.self_ref (Theory.sign_of thy);
   992     val get_from_thy = f thy;
   993   in
   994     fn xnamei as (xname, _) =>
   995       (case Symtab.lookup (tab, NameSpace.intern space xname) of
   996         SOME (SOME ths) => map (Thm.transfer_sg (Sign.deref sg_ref))
   997           (PureThy.select_thm xnamei ths)
   998       | _ => get_from_thy xnamei) |> g xname
   999   end;
  1000 
  1001 val get_thm = retrieve_thms PureThy.get_thms PureThy.single_thm;
  1002 val get_thm_closure = retrieve_thms PureThy.get_thms_closure PureThy.single_thm;
  1003 val get_thms = retrieve_thms PureThy.get_thms (K I);
  1004 val get_thms_closure = retrieve_thms PureThy.get_thms_closure (K I);
  1005 
  1006 
  1007 (* name space operations *)
  1008 
  1009 fun cond_extern (Context {thms = (_, space, _, _), ...}) = NameSpace.cond_extern space;
  1010 
  1011 fun qualified q = map_context (fn (thy, syntax, data, asms, binds,
  1012     (_, space, tab, index), cases, defs, delta, delta_count) =>
  1013   (thy, syntax, data, asms, binds, (q, space, tab, index), cases, defs, delta, delta_count));
  1014 
  1015 fun restore_qualified (Context {thms, ...}) = qualified (#1 thms);
  1016 
  1017 fun hide_thms fully names =
  1018   map_context (fn (thy, syntax, data, asms, binds, (q, space, tab, index), cases, defs, delta, delta_count) =>
  1019     (thy, syntax, data, asms, binds, (q, NameSpace.hide fully (space, names), tab, index),
  1020       cases, defs, delta, delta_count));
  1021 
  1022 
  1023 (* put_thm(s) *)
  1024 
  1025 fun put_thms ("", _) ctxt = ctxt
  1026   | put_thms (name, ths) ctxt = ctxt |> map_context
  1027       (fn (thy, syntax, data, asms, binds, (q, space, tab, index), cases, defs, delta, delta_count) =>
  1028         if not q andalso NameSpace.is_qualified name then
  1029           raise CONTEXT ("Attempt to declare qualified name " ^ quote name, ctxt)
  1030         else (thy, syntax, data, asms, binds, (q, NameSpace.extend (space, [name]),
  1031           Symtab.update ((name, SOME ths), tab),
  1032             FactIndex.add (is_known ctxt) (index, (name, ths))), cases, defs, delta, delta_count));
  1033 
  1034 fun put_thm (name, th) = put_thms (name, [th]);
  1035 
  1036 fun put_thmss [] ctxt = ctxt
  1037   | put_thmss (th :: ths) ctxt = ctxt |> put_thms th |> put_thmss ths;
  1038 
  1039 
  1040 (* reset_thms *)
  1041 
  1042 fun reset_thms name =
  1043   map_context (fn (thy, syntax, data, asms, binds, (q, space, tab, index), cases, defs, delta, delta_count) =>
  1044     (thy, syntax, data, asms, binds, (q, space, Symtab.update ((name, NONE), tab), index),
  1045       cases, defs, delta,delta_count));
  1046 
  1047 
  1048 (* note_thmss *)
  1049 
  1050 local
  1051 
  1052 fun gen_note_thss get (ctxt, ((name, more_attrs), ths_attrs)) =
  1053   let
  1054     fun app ((ct, ths), (th, attrs)) =
  1055       let val (ct', th') = Thm.applys_attributes ((ct, get ctxt th), attrs @ more_attrs)
  1056       in (ct', th' :: ths) end;
  1057     val (ctxt', rev_thms) = Library.foldl app ((ctxt, []), ths_attrs);
  1058     val thms = List.concat (rev rev_thms);
  1059   in (ctxt' |> put_thms (name, thms), (name, thms)) end;
  1060 
  1061 fun gen_note_thmss get args ctxt = foldl_map (gen_note_thss get) (ctxt, args);
  1062 
  1063 in
  1064 
  1065 val note_thmss = gen_note_thmss get_thms;
  1066 val note_thmss_i = gen_note_thmss (K I);
  1067 
  1068 end;
  1069 
  1070 
  1071 
  1072 (** assumptions **)
  1073 
  1074 (* basic exporters *)
  1075 
  1076 fun export_assume true = Seq.single oo Drule.implies_intr_goals
  1077   | export_assume false = Seq.single oo Drule.implies_intr_list;
  1078 
  1079 fun export_presume _ = export_assume false;
  1080 
  1081 
  1082 (* defs *)
  1083 
  1084 fun cert_def ctxt eq =
  1085   let
  1086     fun err msg = raise CONTEXT (msg ^
  1087       "\nThe error(s) above occurred in local definition: " ^ string_of_term ctxt eq, ctxt);
  1088     val (lhs, rhs) = Logic.dest_equals (Term.strip_all_body eq)
  1089       handle TERM _ => err "Not a meta-equality (==)";
  1090     val (f, xs) = Term.strip_comb lhs;
  1091     val (c, _) = Term.dest_Free f handle TERM _ =>
  1092       err "Head of lhs must be a free/fixed variable";
  1093 
  1094     fun is_free (Free (x, _)) = not (is_fixed ctxt x)
  1095       | is_free _ = false;
  1096     val extra_frees = List.filter is_free (term_frees rhs) \\ xs;
  1097   in
  1098     conditional (not (forall (is_Bound orf is_free) xs andalso null (duplicates xs))) (fn () =>
  1099       err "Arguments of lhs must be distinct free/bound variables");
  1100     conditional (f mem Term.term_frees rhs) (fn () =>
  1101       err "Element to be defined occurs on rhs");
  1102     conditional (not (null extra_frees)) (fn () =>
  1103       err ("Extra free variables on rhs: " ^ commas_quote (map (#1 o dest_Free) extra_frees)));
  1104     (c, Term.list_all_free (List.mapPartial (try Term.dest_Free) xs, eq))
  1105   end;
  1106 
  1107 fun head_of_def cprop =
  1108   #1 (Term.strip_comb (#1 (Logic.dest_equals (Term.strip_all_body (Thm.term_of cprop)))))
  1109   |> Thm.cterm_of (Thm.sign_of_cterm cprop);
  1110 
  1111 fun export_def _ cprops thm =
  1112   thm
  1113   |> Drule.implies_intr_list cprops
  1114   |> Drule.forall_intr_list (map head_of_def cprops)
  1115   |> Drule.forall_elim_vars 0
  1116   |> RANGE (replicate (length cprops) (Tactic.rtac Drule.reflexive_thm)) 1;
  1117 
  1118 
  1119 (* assume *)
  1120 
  1121 local
  1122 
  1123 fun add_assm (ctxt, ((name, attrs), props)) =
  1124   let
  1125     val cprops = map (Thm.cterm_of (sign_of ctxt)) props;
  1126     val asms = map (Tactic.norm_hhf_rule o Thm.assume) cprops;
  1127 
  1128     val ths = map (fn th => ([th], [])) asms;
  1129     val (ctxt', [(_, thms)]) =
  1130       ctxt
  1131       |> auto_bind_facts props
  1132       |> note_thmss_i [((name, attrs), ths)];
  1133   in (ctxt', (cprops, (name, asms), (name, thms))) end;
  1134 
  1135 fun gen_assms prepp exp args ctxt =
  1136   let
  1137     val (ctxt1, propss) = prepp (ctxt, map snd args);
  1138     val (ctxt2, results) = foldl_map add_assm (ctxt1, map fst args ~~ propss);
  1139 
  1140     val cprops = List.concat (map #1 results);
  1141     val asmss = map #2 results;
  1142     val thmss = map #3 results;
  1143     val ctxt3 = ctxt2 |> map_context
  1144       (fn (thy, syntax, data, ((asms_ct, asms_th), fixes), binds, thms, cases, defs, delta, delta_count) =>
  1145         (thy, syntax, data, ((asms_ct @ [(cprops, exp)], asms_th @ asmss), fixes), binds, thms,
  1146           cases, defs, delta, delta_count));
  1147     val ctxt4 = ctxt3 |> put_thms ("prems", prems_of ctxt3);
  1148   in (warn_extra_tfrees ctxt ctxt4, thmss) end;
  1149 
  1150 in
  1151 
  1152 val assume = gen_assms (apsnd #1 o bind_propp);
  1153 val assume_i = gen_assms (apsnd #1 o bind_propp_i);
  1154 
  1155 end;
  1156 
  1157 
  1158 (* variables *)
  1159 
  1160 local
  1161 
  1162 fun prep_vars prep_typ internal liberal (ctxt, (xs, raw_T)) =
  1163   let
  1164     fun cond_tvars T =
  1165       if internal then T
  1166       else Type.no_tvars T handle TYPE (msg, _, _) => raise CONTEXT (msg, ctxt);
  1167 
  1168     val _ = if liberal then () else
  1169       (case List.filter (not o Syntax.is_identifier) (map (no_skolem internal ctxt) xs) of
  1170       [] => () | bads => raise CONTEXT ("Bad variable name(s): " ^ commas_quote bads, ctxt));
  1171 
  1172     val opt_T = Option.map (cond_tvars o prep_typ ctxt) raw_T;
  1173     val T = getOpt (opt_T, TypeInfer.logicT);
  1174     val ctxt' = ctxt |> declare_terms_syntax (map (fn x => Free (x, T)) xs);
  1175   in (ctxt', (xs, opt_T)) end;
  1176 
  1177 in
  1178 
  1179 val read_vars         = prep_vars read_typ false false;
  1180 val cert_vars         = prep_vars cert_typ true false;
  1181 val read_vars_liberal = prep_vars read_typ false true;
  1182 val cert_vars_liberal = prep_vars cert_typ true true;
  1183 
  1184 end;
  1185 
  1186 
  1187 (* fix *)
  1188 
  1189 local
  1190 
  1191 fun map_fixes f =
  1192   map_context (fn (thy, syntax, data, (assumes, fixes), binds, thms, cases, defs, delta, delta_count) =>
  1193     (thy, syntax, data, (assumes, f fixes), binds, thms, cases, defs, delta, delta_count));
  1194 
  1195 fun err_dups ctxt xs = raise CONTEXT ("Duplicate variable(s): " ^ commas_quote xs, ctxt);
  1196 
  1197 val declare =
  1198   declare_terms_syntax o List.mapPartial (fn (_, NONE) => NONE | (x, SOME T) => SOME (Free (x, T)));
  1199 
  1200 fun add_vars xs Ts ctxt =
  1201   let val xs' = Term.variantlist (map Syntax.skolem xs, map #2 (fixes_of ctxt)) in
  1202     ctxt
  1203     |> declare (xs' ~~ Ts)
  1204     |> map_fixes (fn fixes => (xs ~~ xs') @ fixes)
  1205   end;
  1206 
  1207 fun add_vars_direct xs Ts ctxt =
  1208   ctxt
  1209   |> declare (xs ~~ Ts)
  1210   |> map_fixes (fn fixes =>
  1211     (case xs inter_string map #1 fixes of
  1212       [] => (xs ~~ xs) @ fixes
  1213     | dups => err_dups ctxt dups));
  1214 
  1215 
  1216 fun gen_fix prep add raw_vars ctxt =
  1217   let
  1218     val (ctxt', varss) = foldl_map prep (ctxt, raw_vars);
  1219     val vars = rev (List.concat (map (fn (xs, T) => map (rpair T) xs) varss));
  1220     val xs = map #1 vars;
  1221     val Ts = map #2 vars;
  1222   in
  1223     (case Library.duplicates xs of [] => () | dups => err_dups ctxt dups);
  1224     ctxt' |> add xs Ts
  1225   end;
  1226 
  1227 fun prep_type (x, NONE, SOME mx) = ([x], SOME (mixfix_type mx))
  1228   | prep_type (x, opt_T, _) = ([x], opt_T);
  1229 
  1230 in
  1231 
  1232 val fix = gen_fix read_vars add_vars;
  1233 val fix_i = gen_fix cert_vars add_vars;
  1234 
  1235 fun fix_direct liberal =
  1236   gen_fix (if liberal then cert_vars_liberal else cert_vars) add_vars_direct;
  1237 
  1238 fun add_fixes decls = add_syntax decls o fix_direct false (map prep_type decls);
  1239 fun add_fixes_liberal decls = add_syntax decls o fix_direct true (map prep_type decls);
  1240 
  1241 end;
  1242 
  1243 fun fix_frees ts ctxt =
  1244   let
  1245     val frees = Library.foldl Term.add_frees ([], ts);
  1246     fun new (x, T) = if is_fixed ctxt x then NONE else SOME ([x], SOME T);
  1247   in fix_direct false (rev (List.mapPartial new frees)) ctxt end;
  1248 
  1249 
  1250 (*Note: improper use may result in variable capture / dynamic scoping!*)
  1251 fun bind_skolem ctxt xs =
  1252   let
  1253     val ctxt' = ctxt |> fix_i [(xs, NONE)];
  1254     fun bind (t as Free (x, T)) =
  1255           if x mem_string xs then
  1256             (case lookup_skolem ctxt' x of SOME x' => Free (x', T) | NONE => t)
  1257           else t
  1258       | bind (t $ u) = bind t $ bind u
  1259       | bind (Abs (x, T, t)) = Abs (x, T, bind t)
  1260       | bind a = a;
  1261   in bind end;
  1262 
  1263 
  1264 
  1265 (** cases **)
  1266 
  1267 fun prep_case ctxt name xs {fixes, assumes, binds} =
  1268   let
  1269     fun replace (opt_x :: xs) ((y, T) :: ys) = (getOpt (opt_x,y), T) :: replace xs ys
  1270       | replace [] ys = ys
  1271       | replace (_ :: _) [] = raise CONTEXT ("Too many parameters for case " ^ quote name, ctxt);
  1272   in
  1273     if null (foldr Term.add_typ_tvars [] (map snd fixes)) andalso
  1274       null (foldr Term.add_term_vars [] (List.concat (map snd assumes))) then
  1275         {fixes = replace xs fixes, assumes = assumes, binds = map drop_schematic binds}
  1276     else raise CONTEXT ("Illegal schematic variable(s) in case " ^ quote name, ctxt)
  1277   end;
  1278 
  1279 fun get_case (ctxt as Context {cases, ...}) name xs =
  1280   (case assoc (cases, name) of
  1281     NONE => raise CONTEXT ("Unknown case: " ^ quote name, ctxt)
  1282   | SOME c => prep_case ctxt name xs c);
  1283 
  1284 
  1285 fun add_cases xs = map_context (fn (thy, syntax, data, asms, binds, thms, cases, defs, delta, delta_count) =>
  1286   (thy, syntax, data, asms, binds, thms, rev (filter_out (equal "" o #1) xs) @ cases, defs, delta, delta_count));
  1287 
  1288 
  1289 
  1290 (** print context information **)
  1291 
  1292 val verbose = ref false;
  1293 fun verb f x = if ! verbose then f (x ()) else [];
  1294 fun verb_single x = verb Library.single x;
  1295 
  1296 fun setmp_verbose f x = Library.setmp verbose true f x;
  1297 
  1298 fun pretty_items prt name items =
  1299   let
  1300     fun prt_itms (name, [x]) = Pretty.block [Pretty.str (name ^ ":"), Pretty.brk 1, prt x]
  1301       | prt_itms (name, xs) = Pretty.big_list (name ^ ":") (map prt xs);
  1302   in
  1303     if null items andalso not (! verbose) then []
  1304     else [Pretty.big_list name (map prt_itms items)]
  1305   end;
  1306 
  1307 
  1308 (* local syntax *)
  1309 
  1310 val print_syntax = Syntax.print_syntax o syn_of;
  1311 
  1312 
  1313 (* term bindings *)
  1314 
  1315 val smash_option = fn (_, NONE) => NONE | (xi, SOME b) => SOME (xi, b);
  1316 
  1317 fun pretty_binds (ctxt as Context {binds, ...}) =
  1318   let
  1319     fun prt_bind (xi, (t, T)) = pretty_term ctxt (Logic.mk_equals (Var (xi, T), t));
  1320     val bs = List.mapPartial smash_option (Vartab.dest binds);
  1321   in
  1322     if null bs andalso not (! verbose) then []
  1323     else [Pretty.big_list "term bindings:" (map prt_bind bs)]
  1324   end;
  1325 
  1326 val print_binds = Pretty.writeln o Pretty.chunks o pretty_binds;
  1327 
  1328 
  1329 (* local theorems *)
  1330 
  1331 fun pretty_lthms (ctxt as Context {thms = (_, space, tab, _), ...}) =
  1332   pretty_items (pretty_thm ctxt) "facts:"
  1333     (List.mapPartial smash_option (NameSpace.cond_extern_table space tab));
  1334 
  1335 val print_lthms = Pretty.writeln o Pretty.chunks o pretty_lthms;
  1336 
  1337 
  1338 (* local contexts *)
  1339 
  1340 fun apply_case ({fixes, assumes, binds}: RuleCases.T) ctxt =
  1341   let
  1342     fun bind (c, (x, T)) = (c |> fix_i [([x], SOME T)], bind_skolem c [x] (Free (x, T)));
  1343     val (ctxt', xs) = foldl_map bind (ctxt, fixes);
  1344     fun app t = Library.foldl Term.betapply (t, xs);
  1345   in (ctxt', (map (apsnd (Option.map app)) binds, map (apsnd (map app)) assumes)) end;
  1346 
  1347 fun pretty_cases (ctxt as Context {cases, ...}) =
  1348   let
  1349     val prt_term = pretty_term ctxt;
  1350 
  1351     fun prt_let (xi, t) = Pretty.block
  1352       [Pretty.quote (prt_term (Var (xi, Term.fastype_of t))), Pretty.str " =", Pretty.brk 1,
  1353         Pretty.quote (prt_term t)];
  1354 
  1355     fun prt_asm (a, ts) = Pretty.block (Pretty.breaks
  1356       ((if a = "" then [] else [Pretty.str (a ^ ":")]) @ map (Pretty.quote o prt_term) ts));
  1357 
  1358     fun prt_sect _ _ _ [] = []
  1359       | prt_sect s sep prt xs = [Pretty.block (Pretty.breaks (Pretty.str s ::
  1360             List.concat (Library.separate sep (map (Library.single o prt) xs))))];
  1361 
  1362     fun prt_case (name, (fixes, (lets, asms))) = Pretty.block (Pretty.fbreaks
  1363       (Pretty.str (name ^ ":") ::
  1364         prt_sect "fix" [] (Pretty.str o fst) fixes @
  1365         prt_sect "let" [Pretty.str "and"] prt_let
  1366           (List.mapPartial (fn (xi, SOME t) => SOME (xi, t) | _ => NONE) lets) @
  1367         (if forall (null o #2) asms then []
  1368           else prt_sect "assume" [Pretty.str "and"] prt_asm asms)));
  1369 
  1370     val cases' = rev (Library.gen_distinct Library.eq_fst cases);
  1371   in
  1372     if null cases andalso not (! verbose) then []
  1373     else [Pretty.big_list "cases:"
  1374       (map (prt_case o apsnd (fn c => (#fixes c, #2 (apply_case c ctxt)))) cases')]
  1375   end;
  1376 
  1377 val print_cases = Pretty.writeln o Pretty.chunks o pretty_cases;
  1378 
  1379 
  1380 (* core context *)
  1381 
  1382 val prems_limit = ref 10;
  1383 
  1384 fun pretty_asms ctxt =
  1385   let
  1386     val prt_term = pretty_term ctxt;
  1387 
  1388     (*structures*)
  1389     val (_, structs, _) = syntax_of ctxt;
  1390     val prt_structs = if null structs then []
  1391       else [Pretty.block (Pretty.str "structures:" :: Pretty.brk 1 ::
  1392         Pretty.commas (map Pretty.str structs))];
  1393 
  1394     (*fixes*)
  1395     fun prt_fix (x, x') =
  1396       if x = x' then Pretty.str x
  1397       else Pretty.block [Pretty.str x, Pretty.str " =", Pretty.brk 1, prt_term (Syntax.free x')];
  1398     val fixes = rev (filter_out
  1399       ((can Syntax.dest_internal o #1) orf (fn (_, x') => x' mem_string structs)) (fixes_of ctxt));
  1400     val prt_fixes = if null fixes then []
  1401       else [Pretty.block (Pretty.str "fixed variables:" :: Pretty.brk 1 ::
  1402         Pretty.commas (map prt_fix fixes))];
  1403 
  1404     (*prems*)
  1405     val limit = ! prems_limit;
  1406     val prems = prems_of ctxt;
  1407     val len = length prems;
  1408     val prt_prems = if null prems then []
  1409       else [Pretty.big_list "prems:" ((if len <= limit then [] else [Pretty.str "..."]) @
  1410         map (pretty_thm ctxt) (Library.drop (len - limit, prems)))];
  1411 
  1412   in prt_structs @ prt_fixes @ prt_prems end;
  1413 
  1414 
  1415 (* main context *)
  1416 
  1417 fun pretty_context (ctxt as Context {cases, defs = (types, sorts, used, _), ...}) =
  1418   let
  1419     val prt_term = pretty_term ctxt;
  1420     val prt_typ = pretty_typ ctxt;
  1421     val prt_sort = pretty_sort ctxt;
  1422 
  1423     (*theory*)
  1424     val pretty_thy = Pretty.block
  1425       [Pretty.str "Theory:", Pretty.brk 1, Sign.pretty_sg (sign_of ctxt)];
  1426 
  1427     (*defaults*)
  1428     fun prt_atom prt prtT (x, X) = Pretty.block
  1429       [prt x, Pretty.str " ::", Pretty.brk 1, prtT X];
  1430 
  1431     fun prt_var (x, ~1) = prt_term (Syntax.free x)
  1432       | prt_var xi = prt_term (Syntax.var xi);
  1433 
  1434     fun prt_varT (x, ~1) = prt_typ (TFree (x, []))
  1435       | prt_varT xi = prt_typ (TVar (xi, []));
  1436 
  1437     val prt_defT = prt_atom prt_var prt_typ;
  1438     val prt_defS = prt_atom prt_varT prt_sort;
  1439   in
  1440     verb_single (K pretty_thy) @
  1441     pretty_asms ctxt @
  1442     verb pretty_binds (K ctxt) @
  1443     verb pretty_lthms (K ctxt) @
  1444     verb pretty_cases (K ctxt) @
  1445     verb_single (fn () => Pretty.big_list "type constraints:" (map prt_defT (Vartab.dest types))) @
  1446     verb_single (fn () => Pretty.big_list "default sorts:" (map prt_defS (Vartab.dest sorts))) @
  1447     verb_single (fn () => Pretty.strs ("used type variable names:" :: used))
  1448   end;
  1449 
  1450 
  1451 (* print_thms_containing *)
  1452 
  1453 fun lthms_containing (ctxt as Context {thms = (_, _, _, index), ...}) idx =
  1454   let
  1455     fun valid (name, ths) =
  1456       (case try (transform_error (fn () => get_thms ctxt (name, NONE))) () of
  1457         NONE => false
  1458       | SOME ths' => Library.equal_lists Thm.eq_thm (ths, ths'));
  1459   in gen_distinct eq_fst (List.filter valid (FactIndex.find idx index)) end;
  1460 
  1461 
  1462 val thms_containing_limit = ref 40;
  1463 
  1464 fun print_thms_containing ctxt opt_limit ss =
  1465   let
  1466     val prt_term = pretty_term ctxt;
  1467     val prt_fact = pretty_fact ctxt;
  1468     fun prt_consts [] = []
  1469       | prt_consts cs = [Pretty.block (Pretty.breaks (Pretty.str "constants" ::
  1470           map (Pretty.quote o prt_term o Syntax.const) cs))];
  1471     fun prt_frees [] = []
  1472       | prt_frees xs = [Pretty.block (Pretty.breaks (Pretty.str "variables" ::
  1473           map (Pretty.quote o prt_term o Syntax.free) xs))];
  1474 
  1475     val (cs, xs) = Library.foldl (FactIndex.index_term (is_known ctxt))
  1476       (([], []), map (read_term_dummies ctxt) ss);
  1477     val empty_idx = null cs andalso null xs;
  1478 
  1479     val header =
  1480       if empty_idx then [Pretty.block [Pretty.str "Known facts:", Pretty.fbrk]]
  1481       else [Pretty.block (Pretty.breaks (Pretty.str "Facts containing" ::
  1482         separate (Pretty.str "and") (prt_consts cs @ prt_frees xs)) @
  1483           [Pretty.str ":", Pretty.fbrk])]
  1484     val facts =
  1485       PureThy.thms_containing (theory_of ctxt) (cs, xs) @ lthms_containing ctxt (cs, xs)
  1486       |> sort_wrt #1;
  1487     val len = length facts;
  1488     val limit = getOpt (opt_limit, ! thms_containing_limit);
  1489   in
  1490     if empty_idx andalso not (null ss) then
  1491       warning "thms_containing: no consts/frees in specification"
  1492     else (header @ (if len <= limit then [] else [Pretty.str "..."]) @
  1493         map prt_fact (Library.drop (len - limit, facts))) |> Pretty.chunks |> Pretty.writeln
  1494   end;
  1495 
  1496 
  1497 
  1498 (** theory setup **)
  1499 
  1500 val setup = [ProofDataData.init];
  1501 
  1502 end;