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