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