src/Pure/Isar/proof_context.ML
author haftmann
Fri Mar 14 08:52:53 2008 +0100 (2008-03-14 ago)
changeset 26268 80aaf4d034be
parent 26250 96035b40be60
child 26284 533dcb120a8e
permissions -rw-r--r--
added mk_const functions
     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: elevates primitive local
     6 reasoning Gamma |- phi to a structured concept, with generic context
     7 elements.  See also structure Variable and Assumption.
     8 *)
     9 
    10 signature PROOF_CONTEXT =
    11 sig
    12   val theory_of: Proof.context -> theory
    13   val init: theory -> Proof.context
    14   type mode
    15   val mode_default: mode
    16   val mode_stmt: mode
    17   val mode_pattern: mode
    18   val mode_schematic: mode
    19   val mode_abbrev: mode
    20   val set_mode: mode -> Proof.context -> Proof.context
    21   val get_mode: Proof.context -> mode
    22   val restore_mode: Proof.context -> Proof.context -> Proof.context
    23   val set_stmt: bool -> Proof.context -> Proof.context
    24   val naming_of: Proof.context -> NameSpace.naming
    25   val full_name: Proof.context -> bstring -> string
    26   val consts_of: Proof.context -> Consts.T
    27   val const_syntax_name: Proof.context -> string -> string
    28   val the_const_constraint: Proof.context -> string -> typ
    29   val mk_const: Proof.context -> string * typ list -> term
    30   val set_syntax_mode: Syntax.mode -> Proof.context -> Proof.context
    31   val restore_syntax_mode: Proof.context -> Proof.context -> Proof.context
    32   val theorems_of: Proof.context -> thm list NameSpace.table
    33   val fact_index_of: Proof.context -> FactIndex.T
    34   val transfer: theory -> Proof.context -> Proof.context
    35   val theory: (theory -> theory) -> Proof.context -> Proof.context
    36   val theory_result: (theory -> 'a * theory) -> Proof.context -> 'a * Proof.context
    37   val pretty_term_abbrev: Proof.context -> term -> Pretty.T
    38   val pretty_thm_legacy: thm -> Pretty.T
    39   val pretty_thm: Proof.context -> thm -> Pretty.T
    40   val pretty_thms: Proof.context -> thm list -> Pretty.T
    41   val pretty_fact: Proof.context -> string * thm list -> Pretty.T
    42   val pretty_proof: Proof.context -> Proofterm.proof -> Pretty.T
    43   val pretty_proof_of: Proof.context -> bool -> thm -> Pretty.T
    44   val string_of_thm: Proof.context -> thm -> string
    45   val read_typ: Proof.context -> string -> typ
    46   val read_typ_syntax: Proof.context -> string -> typ
    47   val read_typ_abbrev: Proof.context -> string -> typ
    48   val cert_typ: Proof.context -> typ -> typ
    49   val cert_typ_syntax: Proof.context -> typ -> typ
    50   val cert_typ_abbrev: Proof.context -> typ -> typ
    51   val get_skolem: Proof.context -> string -> string
    52   val revert_skolem: Proof.context -> string -> string
    53   val revert_skolems: Proof.context -> term -> term
    54   val infer_type: Proof.context -> string -> typ
    55   val inferred_param: string -> Proof.context -> (string * typ) * Proof.context
    56   val inferred_fixes: Proof.context -> (string * typ) list * Proof.context
    57   val read_tyname: Proof.context -> string -> typ
    58   val read_const_proper: Proof.context -> string -> term
    59   val read_const: Proof.context -> string -> term
    60   val decode_term: Proof.context -> term -> term
    61   val standard_infer_types: Proof.context -> term list -> term list
    62   val read_term_pattern: Proof.context -> string -> term
    63   val read_term_schematic: Proof.context -> string -> term
    64   val read_term_abbrev: Proof.context -> string -> term
    65   val expand_abbrevs: Proof.context -> term -> term
    66   val cert_term: Proof.context -> term -> term
    67   val cert_prop: Proof.context -> term -> term
    68   val goal_export: Proof.context -> Proof.context -> thm list -> thm list
    69   val export: Proof.context -> Proof.context -> thm list -> thm list
    70   val export_morphism: Proof.context -> Proof.context -> morphism
    71   val add_binds: (indexname * string option) list -> Proof.context -> Proof.context
    72   val add_binds_i: (indexname * term option) list -> Proof.context -> Proof.context
    73   val auto_bind_goal: term list -> Proof.context -> Proof.context
    74   val auto_bind_facts: term list -> Proof.context -> Proof.context
    75   val match_bind: bool -> (string list * string) list -> Proof.context -> term list * Proof.context
    76   val match_bind_i: bool -> (term list * term) list -> Proof.context -> term list * Proof.context
    77   val read_propp: Proof.context * (string * string list) list list
    78     -> Proof.context * (term * term list) list list
    79   val cert_propp: Proof.context * (term * term list) list list
    80     -> Proof.context * (term * term list) list list
    81   val read_propp_schematic: Proof.context * (string * string list) list list
    82     -> Proof.context * (term * term list) list list
    83   val cert_propp_schematic: Proof.context * (term * term list) list list
    84     -> Proof.context * (term * term list) list list
    85   val bind_propp: Proof.context * (string * string list) list list
    86     -> Proof.context * (term list list * (Proof.context -> Proof.context))
    87   val bind_propp_i: Proof.context * (term * term list) list list
    88     -> Proof.context * (term list list * (Proof.context -> Proof.context))
    89   val bind_propp_schematic: Proof.context * (string * string list) list list
    90     -> Proof.context * (term list list * (Proof.context -> Proof.context))
    91   val bind_propp_schematic_i: Proof.context * (term * term list) list list
    92     -> Proof.context * (term list list * (Proof.context -> Proof.context))
    93   val fact_tac: thm list -> int -> tactic
    94   val some_fact_tac: Proof.context -> int -> tactic
    95   val get_thm: Proof.context -> thmref -> thm
    96   val get_thm_closure: Proof.context -> thmref -> thm
    97   val get_thms: Proof.context -> thmref -> thm list
    98   val get_thms_closure: Proof.context -> thmref -> thm list
    99   val valid_thms: Proof.context -> string * thm list -> bool
   100   val lthms_containing: Proof.context -> FactIndex.spec -> (string * thm list) list
   101   val add_path: string -> Proof.context -> Proof.context
   102   val no_base_names: Proof.context -> Proof.context
   103   val qualified_names: Proof.context -> Proof.context
   104   val sticky_prefix: string -> Proof.context -> Proof.context
   105   val restore_naming: Proof.context -> Proof.context -> Proof.context
   106   val reset_naming: Proof.context -> Proof.context
   107   val hide_thms: bool -> string list -> Proof.context -> Proof.context
   108   val put_thms: bool -> string * thm list option -> Proof.context -> Proof.context
   109   val note_thmss: string ->
   110     ((bstring * attribute list) * (thmref * attribute list) list) list ->
   111       Proof.context -> (bstring * thm list) list * Proof.context
   112   val note_thmss_i: string ->
   113     ((bstring * attribute list) * (thm list * attribute list) list) list ->
   114       Proof.context -> (bstring * thm list) list * Proof.context
   115   val read_vars: (string * string option * mixfix) list -> Proof.context ->
   116     (string * typ option * mixfix) list * Proof.context
   117   val cert_vars: (string * typ option * mixfix) list -> Proof.context ->
   118     (string * typ option * mixfix) list * Proof.context
   119   val add_fixes: (string * string option * mixfix) list ->
   120     Proof.context -> string list * Proof.context
   121   val add_fixes_i: (string * typ option * mixfix) list ->
   122     Proof.context -> string list * Proof.context
   123   val auto_fixes: Proof.context * (term list list * 'a) -> Proof.context * (term list list * 'a)
   124   val bind_fixes: string list -> Proof.context -> (term -> term) * Proof.context
   125   val add_assms: Assumption.export ->
   126     ((string * attribute list) * (string * string list) list) list ->
   127     Proof.context -> (bstring * thm list) list * Proof.context
   128   val add_assms_i: Assumption.export ->
   129     ((string * attribute list) * (term * term list) list) list ->
   130     Proof.context -> (bstring * thm list) list * Proof.context
   131   val add_cases: bool -> (string * RuleCases.T option) list -> Proof.context -> Proof.context
   132   val apply_case: RuleCases.T -> Proof.context -> (string * term list) list * Proof.context
   133   val get_case: Proof.context -> string -> string option list -> RuleCases.T
   134   val notation: bool -> Syntax.mode -> (term * mixfix) list -> Proof.context -> Proof.context
   135   val target_notation: bool -> Syntax.mode -> (term * mixfix) list -> morphism ->
   136     Context.generic -> Context.generic
   137   val add_const_constraint: string * typ option -> Proof.context -> Proof.context
   138   val add_abbrev: string -> Markup.property list ->
   139     bstring * term -> Proof.context -> (term * term) * Proof.context
   140   val revert_abbrev: string -> string -> Proof.context -> Proof.context
   141   val verbose: bool ref
   142   val setmp_verbose: ('a -> 'b) -> 'a -> 'b
   143   val print_syntax: Proof.context -> unit
   144   val print_abbrevs: Proof.context -> unit
   145   val print_binds: Proof.context -> unit
   146   val print_lthms: Proof.context -> unit
   147   val print_cases: Proof.context -> unit
   148   val debug: bool ref
   149   val prems_limit: int ref
   150   val pretty_ctxt: Proof.context -> Pretty.T list
   151   val pretty_context: Proof.context -> Pretty.T list
   152 end;
   153 
   154 structure ProofContext: PROOF_CONTEXT =
   155 struct
   156 
   157 val theory_of = Context.theory_of_proof;
   158 
   159 val init = Context.init_proof;
   160 
   161 
   162 (** inner syntax mode **)
   163 
   164 datatype mode =
   165   Mode of
   166    {stmt: bool,                (*inner statement mode*)
   167     pattern: bool,             (*pattern binding schematic variables*)
   168     schematic: bool,           (*term referencing loose schematic variables*)
   169     abbrev: bool};             (*abbrev mode -- no normalization*)
   170 
   171 fun make_mode (stmt, pattern, schematic, abbrev) =
   172   Mode {stmt = stmt, pattern = pattern, schematic = schematic, abbrev = abbrev};
   173 
   174 val mode_default   = make_mode (false, false, false, false);
   175 val mode_stmt      = make_mode (true, false, false, false);
   176 val mode_pattern   = make_mode (false, true, false, false);
   177 val mode_schematic = make_mode (false, false, true, false);
   178 val mode_abbrev    = make_mode (false, false, false, true);
   179 
   180 
   181 
   182 (** Isar proof context information **)
   183 
   184 datatype ctxt =
   185   Ctxt of
   186    {mode: mode,                                       (*inner syntax mode*)
   187     naming: NameSpace.naming,                         (*local naming conventions*)
   188     syntax: LocalSyntax.T,                            (*local syntax*)
   189     consts: Consts.T * Consts.T,                      (*local/global consts*)
   190     thms: thm list NameSpace.table * FactIndex.T,     (*local thms*)
   191     cases: (string * (RuleCases.T * bool)) list};     (*local contexts*)
   192 
   193 fun make_ctxt (mode, naming, syntax, consts, thms, cases) =
   194   Ctxt {mode = mode, naming = naming, syntax = syntax,
   195     consts = consts, thms = thms, cases = cases};
   196 
   197 val local_naming = NameSpace.default_naming |> NameSpace.add_path "local";
   198 
   199 structure ContextData = ProofDataFun
   200 (
   201   type T = ctxt;
   202   fun init thy =
   203     make_ctxt (mode_default, local_naming, LocalSyntax.init thy,
   204       (Sign.consts_of thy, Sign.consts_of thy),
   205       (NameSpace.empty_table, FactIndex.empty), []);
   206 );
   207 
   208 fun rep_context ctxt = ContextData.get ctxt |> (fn Ctxt args => args);
   209 
   210 fun map_context f =
   211   ContextData.map (fn Ctxt {mode, naming, syntax, consts, thms, cases} =>
   212     make_ctxt (f (mode, naming, syntax, consts, thms, cases)));
   213 
   214 fun set_mode mode = map_context (fn (_, naming, syntax, consts, thms, cases) =>
   215   (mode, naming, syntax, consts, thms, cases));
   216 
   217 fun map_mode f =
   218   map_context (fn (Mode {stmt, pattern, schematic, abbrev}, naming, syntax, consts, thms, cases) =>
   219     (make_mode (f (stmt, pattern, schematic, abbrev)), naming, syntax, consts, thms, cases));
   220 
   221 fun map_naming f =
   222   map_context (fn (mode, naming, syntax, consts, thms, cases) =>
   223     (mode, f naming, syntax, consts, thms, cases));
   224 
   225 fun map_syntax f =
   226   map_context (fn (mode, naming, syntax, consts, thms, cases) =>
   227     (mode, naming, f syntax, consts, thms, cases));
   228 
   229 fun map_consts f =
   230   map_context (fn (mode, naming, syntax, consts, thms, cases) =>
   231     (mode, naming, syntax, f consts, thms, cases));
   232 
   233 fun map_thms f =
   234   map_context (fn (mode, naming, syntax, consts, thms, cases) =>
   235     (mode, naming, syntax, consts, f thms, cases));
   236 
   237 fun map_cases f =
   238   map_context (fn (mode, naming, syntax, consts, thms, cases) =>
   239     (mode, naming, syntax, consts, thms, f cases));
   240 
   241 val get_mode = #mode o rep_context;
   242 fun restore_mode ctxt = set_mode (get_mode ctxt);
   243 
   244 fun set_stmt stmt =
   245   map_mode (fn (_, pattern, schematic, abbrev) => (stmt, pattern, schematic, abbrev));
   246 
   247 val naming_of = #naming o rep_context;
   248 val full_name = NameSpace.full o naming_of;
   249 
   250 val syntax_of = #syntax o rep_context;
   251 val syn_of = LocalSyntax.syn_of o syntax_of;
   252 val set_syntax_mode = map_syntax o LocalSyntax.set_mode;
   253 val restore_syntax_mode = map_syntax o LocalSyntax.restore_mode o syntax_of;
   254 
   255 val consts_of = #1 o #consts o rep_context;
   256 val const_syntax_name = Consts.syntax_name o consts_of;
   257 val the_const_constraint = Consts.the_constraint o consts_of;
   258 
   259 fun mk_const ctxt (c, Ts) = Const (c, Consts.instance (consts_of ctxt) (c, Ts));
   260 
   261 val thms_of = #thms o rep_context;
   262 val theorems_of = #1 o thms_of;
   263 val fact_index_of = #2 o thms_of;
   264 
   265 val cases_of = #cases o rep_context;
   266 
   267 
   268 (* theory transfer *)
   269 
   270 fun transfer_syntax thy =
   271   map_syntax (LocalSyntax.rebuild thy) #>
   272   map_consts (fn consts as (local_consts, global_consts) =>
   273     let val thy_consts = Sign.consts_of thy in
   274       if Consts.eq_consts (thy_consts, global_consts) then consts
   275       else (Consts.merge (local_consts, thy_consts), thy_consts)
   276     end);
   277 
   278 fun transfer thy = Context.transfer_proof thy #> transfer_syntax thy;
   279 
   280 fun theory f ctxt = transfer (f (theory_of ctxt)) ctxt;
   281 
   282 fun theory_result f ctxt =
   283   let val (res, thy') = f (theory_of ctxt)
   284   in (res, ctxt |> transfer thy') end;
   285 
   286 
   287 
   288 (** pretty printing **)
   289 
   290 fun pretty_term_abbrev ctxt = Syntax.pretty_term (set_mode mode_abbrev ctxt);
   291 
   292 fun pretty_thm_legacy th =
   293   let val thy = Thm.theory_of_thm th
   294   in Display.pretty_thm_aux (Syntax.pp (init thy)) true false [] th end;
   295 
   296 fun pretty_thm ctxt th =
   297   let val asms = map Thm.term_of (Assumption.assms_of ctxt)
   298   in Display.pretty_thm_aux (Syntax.pp ctxt) false true asms th end;
   299 
   300 fun pretty_thms ctxt [th] = pretty_thm ctxt th
   301   | pretty_thms ctxt ths = Pretty.blk (0, Pretty.fbreaks (map (pretty_thm ctxt) ths));
   302 
   303 fun pretty_fact ctxt ("", ths) = pretty_thms ctxt ths
   304   | pretty_fact ctxt (a, [th]) =
   305       Pretty.block [Pretty.str (a ^ ":"), Pretty.brk 1, pretty_thm ctxt th]
   306   | pretty_fact ctxt (a, ths) =
   307       Pretty.block (Pretty.fbreaks (Pretty.str (a ^ ":") :: map (pretty_thm ctxt) ths));
   308 
   309 fun pretty_proof ctxt prf =
   310   pretty_term_abbrev (ctxt |> transfer_syntax (ProofSyntax.proof_syntax prf (theory_of ctxt)))
   311     (ProofSyntax.term_of_proof prf);
   312 
   313 fun pretty_proof_of ctxt full th =
   314   pretty_proof ctxt (ProofSyntax.proof_of full th);
   315 
   316 val string_of_thm = Pretty.string_of oo pretty_thm;
   317 
   318 
   319 
   320 (** prepare types **)
   321 
   322 (* read_typ *)
   323 
   324 fun read_typ_mode mode ctxt s =
   325   Syntax.read_typ (Type.set_mode mode ctxt) s;
   326 
   327 val read_typ        = read_typ_mode Type.mode_default;
   328 val read_typ_syntax = read_typ_mode Type.mode_syntax;
   329 val read_typ_abbrev = read_typ_mode Type.mode_abbrev;
   330 
   331 
   332 (* cert_typ *)
   333 
   334 fun cert_typ_mode mode ctxt T =
   335   Sign.certify_typ_mode mode (theory_of ctxt) T
   336     handle TYPE (msg, _, _) => error msg;
   337 
   338 val cert_typ        = cert_typ_mode Type.mode_default;
   339 val cert_typ_syntax = cert_typ_mode Type.mode_syntax;
   340 val cert_typ_abbrev = cert_typ_mode Type.mode_abbrev;
   341 
   342 
   343 
   344 (** prepare variables **)
   345 
   346 (* internalize Skolem constants *)
   347 
   348 val lookup_skolem = AList.lookup (op =) o Variable.fixes_of;
   349 fun get_skolem ctxt x = the_default x (lookup_skolem ctxt x);
   350 
   351 fun no_skolem internal x =
   352   if can Name.dest_skolem x then
   353     error ("Illegal reference to internal Skolem constant: " ^ quote x)
   354   else if not internal andalso can Name.dest_internal x then
   355     error ("Illegal reference to internal variable: " ^ quote x)
   356   else x;
   357 
   358 
   359 (* revert Skolem constants -- approximation only! *)
   360 
   361 fun revert_skolem ctxt =
   362   let
   363     val rev_fixes = map Library.swap (Variable.fixes_of ctxt);
   364     val revert = AList.lookup (op =) rev_fixes;
   365   in
   366     fn x =>
   367       (case revert x of
   368         SOME x' => x'
   369       | NONE => perhaps (try Name.dest_skolem) x)
   370    end;
   371 
   372 fun revert_skolems ctxt =
   373   let
   374     val revert = revert_skolem ctxt;
   375     fun reverts (Free (x, T)) = Free (revert x, T)
   376       | reverts (t $ u) = reverts t $ reverts u
   377       | reverts (Abs (x, T, t)) = Abs (x, T, reverts t)
   378       | reverts a = a;
   379   in reverts end;
   380 
   381 
   382 
   383 (** prepare terms and propositions **)
   384 
   385 (* inferred types of parameters *)
   386 
   387 fun infer_type ctxt x =
   388   Term.fastype_of (singleton (Syntax.check_terms (set_mode mode_schematic ctxt))
   389     (Free (x, dummyT)));
   390 
   391 fun inferred_param x ctxt =
   392   let val T = infer_type ctxt x
   393   in ((x, T), ctxt |> Variable.declare_term (Free (x, T))) end;
   394 
   395 fun inferred_fixes ctxt =
   396   fold_map inferred_param (rev (map #2 (Variable.fixes_of ctxt))) ctxt;
   397 
   398 
   399 (* type and constant names *)
   400 
   401 fun read_tyname ctxt c =
   402   if Syntax.is_tid c then
   403     TFree (c, the_default (Sign.defaultS (theory_of ctxt)) (Variable.def_sort ctxt (c, ~1)))
   404   else
   405     let
   406       val thy = theory_of ctxt;
   407       val d = Sign.intern_type thy c;
   408     in Type (d, replicate (Sign.arity_number thy d) dummyT) end;
   409 
   410 fun read_const_proper ctxt c =
   411   (case Variable.lookup_const ctxt c of
   412     SOME d => Const (d, Consts.type_scheme (consts_of ctxt) d handle TYPE (msg, _, _) => error msg)
   413   | NONE => Consts.read_const (consts_of ctxt) c);
   414 
   415 fun read_const ctxt c =
   416   (case (lookup_skolem ctxt c, Variable.is_const ctxt c) of
   417     (SOME x, false) => Free (x, infer_type ctxt x)
   418   | _ => read_const_proper ctxt c);
   419 
   420 
   421 (* read_term *)
   422 
   423 fun read_term_mode mode ctxt = Syntax.read_term (set_mode mode ctxt);
   424 
   425 val read_term_pattern   = read_term_mode mode_pattern;
   426 val read_term_schematic = read_term_mode mode_schematic;
   427 val read_term_abbrev    = read_term_mode mode_abbrev;
   428 
   429 
   430 (* local abbreviations *)
   431 
   432 val tsig_of = Sign.tsig_of o ProofContext.theory_of;
   433 
   434 local
   435 
   436 fun certify_consts ctxt =
   437   let val Mode {abbrev, ...} = get_mode ctxt
   438   in Consts.certify (Syntax.pp ctxt) (tsig_of ctxt) (not abbrev) (consts_of ctxt) end;
   439 
   440 fun reject_schematic (Var (xi, _)) =
   441       error ("Unbound schematic variable: " ^ Term.string_of_vname xi)
   442   | reject_schematic (Abs (_, _, t)) = reject_schematic t
   443   | reject_schematic (t $ u) = (reject_schematic t; reject_schematic u)
   444   | reject_schematic _ = ();
   445 
   446 fun expand_binds ctxt =
   447   let val Mode {pattern, schematic, ...} = get_mode ctxt in
   448     if pattern then I
   449     else Variable.expand_binds ctxt #> (if schematic then I else tap reject_schematic)
   450   end;
   451 
   452 in
   453 
   454 fun expand_abbrevs ctxt = certify_consts ctxt #> expand_binds ctxt;
   455 
   456 end;
   457 
   458 
   459 fun contract_abbrevs ctxt t =
   460   let
   461     val thy = theory_of ctxt;
   462     val consts = consts_of ctxt;
   463     val Mode {abbrev, ...} = get_mode ctxt;
   464   in
   465     if abbrev orelse print_mode_active "no_abbrevs" orelse not (can Term.type_of t) then t
   466     else t |> Pattern.rewrite_term thy (Consts.abbrevs_of consts (print_mode_value () @ [""])) []
   467   end;
   468 
   469 
   470 (* patterns *)
   471 
   472 fun prepare_patternT ctxt =
   473   let val Mode {pattern, schematic, ...} = get_mode ctxt in
   474     if pattern orelse schematic then I
   475     else Term.map_atyps
   476       (fn T as TVar (xi, _) =>
   477             if not (TypeInfer.is_param xi)
   478             then error ("Illegal schematic type variable: " ^ Term.string_of_vname xi)
   479             else T
   480         | T => T)
   481   end;
   482 
   483 
   484 local
   485 
   486 fun prepare_dummies ts = #1 (fold_map Term.replace_dummy_patterns ts 1);
   487 
   488 fun reject_dummies t = Term.no_dummy_patterns t
   489   handle TERM _ => error "Illegal dummy pattern(s) in term";
   490 
   491 in
   492 
   493 fun prepare_patterns ctxt =
   494   let val Mode {pattern, ...} = get_mode ctxt in
   495     TypeInfer.fixate_params (Variable.names_of ctxt) #>
   496     pattern ? Variable.polymorphic ctxt #>
   497     (map o Term.map_types) (prepare_patternT ctxt) #>
   498     (if pattern then prepare_dummies else map reject_dummies)
   499   end;
   500 
   501 end;
   502 
   503 
   504 (* decoding raw terms (syntax trees) *)
   505 
   506 local
   507 
   508 fun intern_skolem ctxt def_type x =
   509   let
   510     val _ = no_skolem false x;
   511     val sko = lookup_skolem ctxt x;
   512     val is_const = can (read_const_proper ctxt) x orelse NameSpace.is_qualified x;
   513     val is_declared = is_some (def_type (x, ~1));
   514   in
   515     if Variable.is_const ctxt x then NONE
   516     else if is_some sko then sko
   517     else if not is_const orelse is_declared then SOME x
   518     else NONE
   519   end;
   520 
   521 in
   522 
   523 fun term_context ctxt =
   524   let val thy = theory_of ctxt in
   525    {get_sort = Sign.get_sort thy (Variable.def_sort ctxt),
   526     map_const = try (#1 o Term.dest_Const o read_const_proper ctxt),
   527     map_free = intern_skolem ctxt (Variable.def_type ctxt false),
   528     map_type = Sign.intern_tycons thy,
   529     map_sort = Sign.intern_sort thy}
   530   end;
   531 
   532 fun decode_term ctxt =
   533   let val {get_sort, map_const, map_free, map_type, map_sort} = term_context ctxt
   534   in Syntax.decode_term get_sort map_const map_free map_type map_sort end;
   535 
   536 end;
   537 
   538 
   539 (* certify terms *)
   540 
   541 local
   542 
   543 fun gen_cert prop ctxt t =
   544   t
   545   |> expand_abbrevs ctxt
   546   |> (fn t' => #1 (Sign.certify' prop (Syntax.pp ctxt) false (consts_of ctxt) (theory_of ctxt) t')
   547     handle TYPE (msg, _, _) => error msg
   548       | TERM (msg, _) => error msg);
   549 
   550 in
   551 
   552 val cert_term = gen_cert false;
   553 val cert_prop = gen_cert true;
   554 
   555 end;
   556 
   557 
   558 (* type checking/inference *)
   559 
   560 fun standard_infer_types ctxt ts =
   561   let val Mode {pattern, ...} = get_mode ctxt in
   562     TypeInfer.infer_types (Syntax.pp ctxt) (tsig_of ctxt) (Syntax.check_typs ctxt)
   563       (try (Consts.the_constraint (consts_of ctxt))) (Variable.def_type ctxt pattern)
   564       (Variable.names_of ctxt) (Variable.maxidx_of ctxt) NONE (map (rpair dummyT) ts)
   565     |> #1 |> map #1
   566     handle TYPE (msg, _, _) => error msg
   567   end;
   568 
   569 local
   570 
   571 fun standard_typ_check ctxt =
   572   map (cert_typ_mode (Type.get_mode ctxt) ctxt) #>
   573   map (prepare_patternT ctxt);
   574 
   575 fun standard_term_check ctxt =
   576   standard_infer_types ctxt #>
   577   map (expand_abbrevs ctxt);
   578 
   579 fun standard_term_uncheck ctxt =
   580   map (contract_abbrevs ctxt);
   581 
   582 fun add eq what f = Context.add_setup
   583   (Context.theory_map (what (fn xs => fn ctxt =>
   584     let val xs' = f ctxt xs in if eq_list eq (xs, xs') then NONE else SOME (xs', ctxt) end)));
   585 
   586 in
   587 
   588 val _ = add (op =) (Syntax.add_typ_check 0 "standard") standard_typ_check;
   589 val _ = add (op aconv) (Syntax.add_term_check 0 "standard") standard_term_check;
   590 val _ = add (op aconv) (Syntax.add_term_check 100 "fixate") prepare_patterns;
   591 
   592 val _ = add (op aconv) (Syntax.add_term_uncheck 0 "standard") standard_term_uncheck;
   593 
   594 end;
   595 
   596 
   597 
   598 (** inner syntax operations **)
   599 
   600 local
   601 
   602 fun parse_sort ctxt str =
   603   Syntax.standard_parse_sort ctxt (syn_of ctxt) (Sign.intern_sort (theory_of ctxt)) str;
   604 
   605 fun parse_typ ctxt str =
   606   let
   607     val thy = ProofContext.theory_of ctxt;
   608     val get_sort = Sign.get_sort thy (Variable.def_sort ctxt);
   609     val T = Sign.intern_tycons thy
   610       (Syntax.standard_parse_typ ctxt (syn_of ctxt) get_sort (Sign.intern_sort thy) str);
   611   in T end
   612   handle ERROR msg => cat_error msg ("The error(s) above occurred in type " ^ quote str);
   613 
   614 fun parse_term T ctxt str =
   615   let
   616     val thy = theory_of ctxt;
   617     val (T', _) = TypeInfer.paramify_dummies T 0;
   618     fun check t = (Syntax.check_term ctxt (TypeInfer.constrain T' t); NONE)
   619       handle ERROR msg => SOME msg;
   620     val {get_sort, map_const, map_free, map_type, map_sort} = term_context ctxt;
   621     val read = Syntax.standard_parse_term (Syntax.pp ctxt) check get_sort
   622       map_const map_free map_type map_sort ctxt (Sign.is_logtype thy) (syn_of ctxt) T';
   623   in read str end;
   624 
   625 
   626 fun unparse_sort ctxt S =
   627   Syntax.standard_unparse_sort ctxt (syn_of ctxt) (Sign.extern_sort (theory_of ctxt) S);
   628 
   629 fun unparse_typ ctxt T =
   630   Syntax.standard_unparse_typ ctxt (syn_of ctxt) (Sign.extern_typ (theory_of ctxt) T);
   631 
   632 fun unparse_term ctxt t =
   633   let
   634     val thy = theory_of ctxt;
   635     val syntax = syntax_of ctxt;
   636     val consts = consts_of ctxt;
   637   in
   638     t
   639     |> Sign.extern_term (Consts.extern_early consts) thy
   640     |> LocalSyntax.extern_term syntax
   641     |> Syntax.standard_unparse_term (Consts.extern consts) ctxt (LocalSyntax.syn_of syntax)
   642         (Context.exists_name Context.CPureN thy)
   643   end;
   644 
   645 in
   646 
   647 val _ = Syntax.install_operations
   648   {parse_sort = parse_sort,
   649    parse_typ = parse_typ,
   650    parse_term = parse_term dummyT,
   651    parse_prop = parse_term propT,
   652    unparse_sort = unparse_sort,
   653    unparse_typ = unparse_typ,
   654    unparse_term = unparse_term};
   655 
   656 end;
   657 
   658 
   659 
   660 (** export results **)
   661 
   662 fun common_export is_goal inner outer =
   663   map (Assumption.export is_goal inner outer) #>
   664   Variable.export inner outer;
   665 
   666 val goal_export = common_export true;
   667 val export = common_export false;
   668 
   669 fun export_morphism inner outer =
   670   Assumption.export_morphism inner outer $>
   671   Variable.export_morphism inner outer;
   672 
   673 
   674 
   675 (** bindings **)
   676 
   677 (* simult_matches *)
   678 
   679 fun simult_matches ctxt (t, pats) =
   680   (case Seq.pull (Unify.matchers (theory_of ctxt) (map (rpair t) pats)) of
   681     NONE => error "Pattern match failed!"
   682   | SOME (env, _) => map (apsnd snd) (Envir.alist_of env));
   683 
   684 
   685 (* add_binds(_i) *)
   686 
   687 local
   688 
   689 fun gen_bind prep (xi as (x, _), raw_t) ctxt =
   690   ctxt
   691   |> Variable.add_binds [(xi, Option.map (prep (set_mode mode_default ctxt)) raw_t)];
   692 
   693 in
   694 
   695 fun drop_schematic (b as (xi, SOME t)) = if Term.exists_subterm is_Var t then (xi, NONE) else b
   696   | drop_schematic b = b;
   697 
   698 val add_binds = fold (gen_bind Syntax.read_term);
   699 val add_binds_i = fold (gen_bind cert_term);
   700 
   701 fun auto_bind f ts ctxt = ctxt |> add_binds_i (map drop_schematic (f (theory_of ctxt) ts));
   702 val auto_bind_goal = auto_bind AutoBind.goal;
   703 val auto_bind_facts = auto_bind AutoBind.facts;
   704 
   705 end;
   706 
   707 
   708 (* match_bind(_i) *)
   709 
   710 local
   711 
   712 fun gen_bind prep_terms gen raw_binds ctxt =
   713   let
   714     fun prep_bind (raw_pats, t) ctxt1 =
   715       let
   716         val T = Term.fastype_of t;
   717         val ctxt2 = Variable.declare_term t ctxt1;
   718         val pats = prep_terms (set_mode mode_pattern ctxt2) T raw_pats;
   719         val binds = simult_matches ctxt2 (t, pats);
   720       in (binds, ctxt2) end;
   721 
   722     val ts = prep_terms ctxt dummyT (map snd raw_binds);
   723     val (binds, ctxt') = apfst flat (fold_map prep_bind (map fst raw_binds ~~ ts) ctxt);
   724     val binds' =
   725       if gen then map #1 binds ~~ Variable.exportT_terms ctxt' ctxt (map #2 binds)
   726       else binds;
   727     val binds'' = map (apsnd SOME) binds';
   728     val ctxt'' =
   729       tap (Variable.warn_extra_tfrees ctxt)
   730        (if gen then
   731           ctxt (*sic!*) |> fold Variable.declare_term (map #2 binds') |> add_binds_i binds''
   732         else ctxt' |> add_binds_i binds'');
   733   in (ts, ctxt'') end;
   734 
   735 in
   736 
   737 fun read_terms ctxt T =
   738   map (Syntax.parse_term ctxt #> TypeInfer.constrain T) #> Syntax.check_terms ctxt;
   739 
   740 val match_bind = gen_bind read_terms;
   741 val match_bind_i = gen_bind (fn ctxt => fn _ => map (cert_term ctxt));
   742 
   743 end;
   744 
   745 
   746 (* propositions with patterns *)
   747 
   748 local
   749 
   750 fun prep_propp mode prep_props (context, args) =
   751   let
   752     fun prep (_, raw_pats) (ctxt, prop :: props) =
   753       let val ctxt' = Variable.declare_term prop ctxt
   754       in ((prop, prep_props (set_mode mode_pattern ctxt') raw_pats), (ctxt', props)) end;
   755 
   756     val (propp, (context', _)) = (fold_map o fold_map) prep args
   757       (context, prep_props (set_mode mode context) (maps (map fst) args));
   758   in (context', propp) end;
   759 
   760 fun gen_bind_propp mode parse_prop (ctxt, raw_args) =
   761   let
   762     val (ctxt', args) = prep_propp mode parse_prop (ctxt, raw_args);
   763     val binds = flat (flat (map (map (simult_matches ctxt')) args));
   764     val propss = map (map #1) args;
   765 
   766     (*generalize result: context evaluated now, binds added later*)
   767     val gen = Variable.exportT_terms ctxt' ctxt;
   768     fun gen_binds c = c |> add_binds_i (map #1 binds ~~ map SOME (gen (map #2 binds)));
   769   in (ctxt' |> add_binds_i (map (apsnd SOME) binds), (propss, gen_binds)) end;
   770 
   771 in
   772 
   773 val read_propp           = prep_propp mode_default Syntax.read_props;
   774 val cert_propp           = prep_propp mode_default (map o cert_prop);
   775 val read_propp_schematic = prep_propp mode_schematic Syntax.read_props;
   776 val cert_propp_schematic = prep_propp mode_schematic (map o cert_prop);
   777 
   778 val bind_propp             = gen_bind_propp mode_default Syntax.read_props;
   779 val bind_propp_i           = gen_bind_propp mode_default (map o cert_prop);
   780 val bind_propp_schematic   = gen_bind_propp mode_schematic Syntax.read_props;
   781 val bind_propp_schematic_i = gen_bind_propp mode_schematic (map o cert_prop);
   782 
   783 end;
   784 
   785 
   786 
   787 (** theorems **)
   788 
   789 (* fact_tac *)
   790 
   791 fun comp_incr_tac [] _ st = no_tac st
   792   | comp_incr_tac (th :: ths) i st =
   793       (Goal.compose_hhf_tac (Drule.incr_indexes st th) i APPEND comp_incr_tac ths i) st;
   794 
   795 fun fact_tac facts = Goal.norm_hhf_tac THEN' comp_incr_tac facts;
   796 
   797 fun some_fact_tac ctxt = SUBGOAL (fn (goal, i) =>
   798   let
   799     val index = fact_index_of ctxt;
   800     val facts = FactIndex.could_unify index (Term.strip_all_body goal);
   801   in fact_tac facts i end);
   802 
   803 
   804 (* get_thm(s) *)
   805 
   806 fun retrieve_thms _ pick ctxt (Fact s) =
   807       let
   808         val prop = Syntax.read_prop (set_mode mode_default ctxt) s
   809           |> singleton (Variable.polymorphic ctxt);
   810         val th = Goal.prove ctxt [] [] prop (K (ALLGOALS (some_fact_tac ctxt)))
   811           handle ERROR msg => cat_error msg "Failed to retrieve literal fact.";
   812       in pick "" [th] end
   813   | retrieve_thms from_thy pick ctxt xthmref =
   814       let
   815         val thy = theory_of ctxt;
   816         val (space, tab) = #1 (thms_of ctxt);
   817         val thmref = PureThy.map_name_of_thmref (NameSpace.intern space) xthmref;
   818         val name = PureThy.name_of_thmref thmref;
   819         val thms =
   820           if name = "" then [Thm.transfer thy Drule.dummy_thm]
   821           else
   822             (case Symtab.lookup tab name of
   823               SOME ths => map (Thm.transfer thy) (PureThy.select_thm thmref ths)
   824             | NONE => from_thy thy xthmref);
   825       in pick name thms end;
   826 
   827 val get_thm = retrieve_thms PureThy.get_thms PureThy.single_thm;
   828 val get_thm_closure = retrieve_thms PureThy.get_thms_closure PureThy.single_thm;
   829 val get_thms = retrieve_thms PureThy.get_thms (K I);
   830 val get_thms_closure = retrieve_thms PureThy.get_thms_closure (K I);
   831 
   832 
   833 (* valid_thms *)
   834 
   835 fun valid_thms ctxt (name, ths) =
   836   (case try (fn () => get_thms ctxt (Name name)) () of
   837     NONE => false
   838   | SOME ths' => Thm.eq_thms (ths, ths'));
   839 
   840 
   841 (* lthms_containing *)
   842 
   843 fun lthms_containing ctxt spec =
   844   FactIndex.find (fact_index_of ctxt) spec
   845   |> map (fn (name, ths) =>
   846     if valid_thms ctxt (name, ths) then (name, ths)
   847     else (NameSpace.hidden (if name = "" then "unnamed" else name), ths));
   848 
   849 
   850 (* name space operations *)
   851 
   852 val add_path        = map_naming o NameSpace.add_path;
   853 val no_base_names   = map_naming NameSpace.no_base_names;
   854 val qualified_names = map_naming NameSpace.qualified_names;
   855 val sticky_prefix   = map_naming o NameSpace.sticky_prefix;
   856 val restore_naming  = map_naming o K o naming_of;
   857 val reset_naming    = map_naming (K local_naming);
   858 
   859 fun hide_thms fully names = map_thms (fn ((space, tab), index) =>
   860   ((fold (NameSpace.hide fully) names space, tab), index));
   861 
   862 
   863 (* put_thms *)
   864 
   865 fun update_thms _ ("", NONE) ctxt = ctxt
   866   | update_thms opts ("", SOME ths) ctxt = ctxt |> map_thms (fn (facts, index) =>
   867       let
   868         val index' = uncurry FactIndex.add_local opts ("", ths) index;
   869       in (facts, index') end)
   870   | update_thms _ (bname, NONE) ctxt = ctxt |> map_thms (fn ((space, tab), index) =>
   871       let
   872         val name = full_name ctxt bname;
   873         val tab' = Symtab.delete_safe name tab;
   874       in ((space, tab'), index) end)
   875   | update_thms opts (bname, SOME ths) ctxt = ctxt |> map_thms (fn ((space, tab), index) =>
   876       let
   877         val name = full_name ctxt bname;
   878         val space' = NameSpace.declare (naming_of ctxt) name space;
   879         val tab' = Symtab.update (name, ths) tab;
   880         val index' = uncurry FactIndex.add_local opts (name, ths) index;
   881       in ((space', tab'), index') end);
   882 
   883 fun put_thms do_props thms ctxt =
   884   ctxt |> map_naming (K local_naming) |> update_thms (do_props, false) thms |> restore_naming ctxt;
   885 
   886 
   887 (* note_thmss *)
   888 
   889 local
   890 
   891 fun gen_note_thmss get k = fold_map (fn ((bname, more_attrs), raw_facts) => fn ctxt =>
   892   let
   893     val name = full_name ctxt bname;
   894     val facts = PureThy.name_thmss false name (map (apfst (get ctxt)) raw_facts);
   895     fun app (th, attrs) x =
   896       swap (foldl_map (Thm.proof_attributes (attrs @ more_attrs @ [PureThy.kind k])) (x, th));
   897     val (res, ctxt') = fold_map app facts ctxt;
   898     val thms = PureThy.name_thms false false name (flat res);
   899     val Mode {stmt, ...} = get_mode ctxt;
   900   in ((bname, thms), ctxt' |> update_thms (stmt, true) (bname, SOME thms)) end);
   901 
   902 in
   903 
   904 fun note_thmss k = gen_note_thmss get_thms k;
   905 fun note_thmss_i k = gen_note_thmss (K I) k;
   906 
   907 end;
   908 
   909 
   910 
   911 (** parameters **)
   912 
   913 (* variables *)
   914 
   915 fun declare_var (x, opt_T, mx) ctxt =
   916   let val T = (case opt_T of SOME T => T | NONE => Syntax.mixfixT mx)
   917   in ((x, T, mx), ctxt |> Variable.declare_constraints (Free (x, T))) end;
   918 
   919 local
   920 
   921 fun prep_vars prep_typ internal =
   922   fold_map (fn (raw_x, raw_T, raw_mx) => fn ctxt =>
   923     let
   924       val (x, mx) = Syntax.const_mixfix raw_x raw_mx;
   925       val _ = Syntax.is_identifier (no_skolem internal x) orelse
   926         error ("Illegal variable name: " ^ quote x);
   927 
   928       fun cond_tvars T =
   929         if internal then T
   930         else Type.no_tvars T handle TYPE (msg, _, _) => error msg;
   931       val opt_T = Option.map (cond_tvars o cert_typ ctxt o prep_typ ctxt) raw_T;
   932       val var = (x, opt_T, mx);
   933     in (var, ctxt |> declare_var var |> #2) end);
   934 
   935 in
   936 
   937 val read_vars = prep_vars Syntax.parse_typ false;
   938 val cert_vars = prep_vars (K I) true;
   939 
   940 end;
   941 
   942 
   943 (* authentic constants *)
   944 
   945 local
   946 
   947 fun const_ast_tr intern ctxt [Syntax.Variable c] =
   948       let
   949         val Const (c', _) = read_const_proper ctxt c;
   950         val d = if intern then const_syntax_name ctxt c' else c;
   951       in Syntax.Constant d end
   952   | const_ast_tr _ _ asts = raise Syntax.AST ("const_ast_tr", asts);
   953 
   954 in
   955 
   956 val _ = Context.add_setup
   957  (Sign.add_syntax
   958    [("_context_const", "id => 'a", Delimfix "CONST _"),
   959     ("_context_const", "longid => 'a", Delimfix "CONST _"),
   960     ("_context_xconst", "id => 'a", Delimfix "XCONST _"),
   961     ("_context_xconst", "longid => 'a", Delimfix "XCONST _")] #>
   962   Sign.add_advanced_trfuns
   963     ([("_context_const", const_ast_tr true), ("_context_xconst", const_ast_tr false)], [], [], []));
   964 
   965 end;
   966 
   967 
   968 (* notation *)
   969 
   970 local
   971 
   972 fun const_syntax ctxt (Free (x, T), mx) = SOME (true, (x, T, mx))
   973   | const_syntax ctxt (Const (c, _), mx) =
   974       Option.map (pair false) (try (Consts.syntax (consts_of ctxt)) (c, mx))
   975   | const_syntax _ _ = NONE;
   976 
   977 in
   978 
   979 fun notation add mode args ctxt =
   980   ctxt |> map_syntax
   981     (LocalSyntax.update_modesyntax (theory_of ctxt) add mode (map_filter (const_syntax ctxt) args));
   982 
   983 fun target_notation add mode args phi =
   984   let val args' = filter (fn (t, _) => Type.similar_types (t, Morphism.term phi t)) args;
   985   in Context.mapping (Sign.notation add mode args') (notation add mode args') end;
   986 
   987 end;
   988 
   989 
   990 (* local constants *)
   991 
   992 fun add_const_constraint (c, opt_T) ctxt =
   993   let
   994     fun prepT raw_T =
   995       let val T = cert_typ ctxt raw_T
   996       in cert_term ctxt (Const (c, T)); T end;
   997   in ctxt |> (map_consts o apfst) (Consts.constrain (c, Option.map prepT opt_T)) end;
   998 
   999 fun add_abbrev mode tags (c, raw_t) ctxt =
  1000   let
  1001     val t0 = cert_term (ctxt |> set_mode mode_abbrev) raw_t
  1002       handle ERROR msg => cat_error msg ("in constant abbreviation " ^ quote c);
  1003     val [t] = Variable.exportT_terms (Variable.declare_term t0 ctxt) ctxt [t0];
  1004     val ((lhs, rhs), consts') = consts_of ctxt
  1005       |> Consts.abbreviate (Syntax.pp ctxt) (tsig_of ctxt) (naming_of ctxt) mode tags (c, t);
  1006   in
  1007     ctxt
  1008     |> (map_consts o apfst) (K consts')
  1009     |> Variable.declare_term rhs
  1010     |> pair (lhs, rhs)
  1011   end;
  1012 
  1013 fun revert_abbrev mode c = (map_consts o apfst) (Consts.revert_abbrev mode c);
  1014 
  1015 
  1016 (* fixes *)
  1017 
  1018 local
  1019 
  1020 fun prep_mixfix (x, T, mx) =
  1021   if mx <> NoSyn andalso mx <> Structure andalso
  1022       (can Name.dest_internal x orelse can Name.dest_skolem x) then
  1023     error ("Illegal mixfix syntax for internal/skolem constant " ^ quote x)
  1024   else (true, (x, T, mx));
  1025 
  1026 fun gen_fixes prep raw_vars ctxt =
  1027   let
  1028     val (vars, _) = prep raw_vars ctxt;
  1029     val (xs', ctxt') = Variable.add_fixes (map #1 vars) ctxt;
  1030   in
  1031     ctxt'
  1032     |> fold_map declare_var (map2 (fn x' => fn (_, T, mx) => (x', T, mx)) xs' vars)
  1033     |-> (map_syntax o LocalSyntax.add_syntax (theory_of ctxt) o map prep_mixfix)
  1034     |> pair xs'
  1035   end;
  1036 
  1037 in
  1038 
  1039 val add_fixes = gen_fixes read_vars;
  1040 val add_fixes_i = gen_fixes cert_vars;
  1041 
  1042 end;
  1043 
  1044 
  1045 (* fixes vs. frees *)
  1046 
  1047 fun auto_fixes (arg as (ctxt, (propss, x))) =
  1048   ((fold o fold) Variable.auto_fixes propss ctxt, (propss, x));
  1049 
  1050 fun bind_fixes xs ctxt =
  1051   let
  1052     val (_, ctxt') = ctxt |> add_fixes_i (map (fn x => (x, NONE, NoSyn)) xs);
  1053     fun bind (t as Free (x, T)) =
  1054           if member (op =) xs x then
  1055             (case lookup_skolem ctxt' x of SOME x' => Free (x', T) | NONE => t)
  1056           else t
  1057       | bind (t $ u) = bind t $ bind u
  1058       | bind (Abs (x, T, t)) = Abs (x, T, bind t)
  1059       | bind a = a;
  1060   in (bind, ctxt') end;
  1061 
  1062 
  1063 
  1064 (** assumptions **)
  1065 
  1066 local
  1067 
  1068 fun gen_assms prepp exp args ctxt =
  1069   let
  1070     val cert = Thm.cterm_of (theory_of ctxt);
  1071     val (propss, ctxt1) = swap (prepp (ctxt, map snd args));
  1072     val _ = Variable.warn_extra_tfrees ctxt ctxt1;
  1073     val (premss, ctxt2) = fold_burrow (Assumption.add_assms exp o map cert) propss ctxt1;
  1074   in
  1075     ctxt2
  1076     |> auto_bind_facts (flat propss)
  1077     |> put_thms false (AutoBind.premsN, SOME (Assumption.prems_of ctxt2))
  1078     |> note_thmss_i Thm.assumptionK (map fst args ~~ map (map (fn th => ([th], []))) premss)
  1079   end;
  1080 
  1081 in
  1082 
  1083 val add_assms = gen_assms (apsnd #1 o bind_propp);
  1084 val add_assms_i = gen_assms (apsnd #1 o bind_propp_i);
  1085 
  1086 end;
  1087 
  1088 
  1089 
  1090 (** cases **)
  1091 
  1092 local
  1093 
  1094 fun rem_case name = remove (fn (x: string, (y, _)) => x = y) name;
  1095 
  1096 fun add_case _ ("", _) cases = cases
  1097   | add_case _ (name, NONE) cases = rem_case name cases
  1098   | add_case is_proper (name, SOME c) cases = (name, (c, is_proper)) :: rem_case name cases;
  1099 
  1100 fun prep_case name fxs c =
  1101   let
  1102     fun replace (opt_x :: xs) ((y, T) :: ys) = (the_default y opt_x, T) :: replace xs ys
  1103       | replace [] ys = ys
  1104       | replace (_ :: _) [] = error ("Too many parameters for case " ^ quote name);
  1105     val RuleCases.Case {fixes, assumes, binds, cases} = c;
  1106     val fixes' = replace fxs fixes;
  1107     val binds' = map drop_schematic binds;
  1108   in
  1109     if null (fold (Term.add_tvarsT o snd) fixes []) andalso
  1110       null (fold (fold Term.add_vars o snd) assumes []) then
  1111         RuleCases.Case {fixes = fixes', assumes = assumes, binds = binds', cases = cases}
  1112     else error ("Illegal schematic variable(s) in case " ^ quote name)
  1113   end;
  1114 
  1115 fun fix (x, T) ctxt =
  1116   let
  1117     val (bind, ctxt') = bind_fixes [x] ctxt;
  1118     val t = bind (Free (x, T));
  1119   in (t, ctxt' |> Variable.declare_constraints t) end;
  1120 
  1121 in
  1122 
  1123 fun add_cases is_proper = map_cases o fold (add_case is_proper);
  1124 
  1125 fun case_result c ctxt =
  1126   let
  1127     val RuleCases.Case {fixes, ...} = c;
  1128     val (ts, ctxt') = ctxt |> fold_map fix fixes;
  1129     val RuleCases.Case {assumes, binds, cases, ...} = RuleCases.apply ts c;
  1130   in
  1131     ctxt'
  1132     |> add_binds_i (map drop_schematic binds)
  1133     |> add_cases true (map (apsnd SOME) cases)
  1134     |> pair (assumes, (binds, cases))
  1135   end;
  1136 
  1137 val apply_case = apfst fst oo case_result;
  1138 
  1139 fun get_case ctxt name xs =
  1140   (case AList.lookup (op =) (cases_of ctxt) name of
  1141     NONE => error ("Unknown case: " ^ quote name)
  1142   | SOME (c, _) => prep_case name xs c);
  1143 
  1144 end;
  1145 
  1146 
  1147 
  1148 (** print context information **)
  1149 
  1150 val debug = ref false;
  1151 
  1152 val verbose = ref false;
  1153 fun verb f x = if ! verbose then f (x ()) else [];
  1154 
  1155 fun setmp_verbose f x = Library.setmp verbose true f x;
  1156 
  1157 
  1158 (* local syntax *)
  1159 
  1160 val print_syntax = Syntax.print_syntax o syn_of;
  1161 
  1162 
  1163 (* abbreviations *)
  1164 
  1165 fun pretty_abbrevs show_globals ctxt =
  1166   let
  1167     val ((space, consts), (_, globals)) =
  1168       pairself (#constants o Consts.dest) (#consts (rep_context ctxt));
  1169     fun add_abbr (_, (_, NONE)) = I
  1170       | add_abbr (c, (T, SOME t)) =
  1171           if not show_globals andalso Symtab.defined globals c then I
  1172           else cons (c, Logic.mk_equals (Const (c, T), t));
  1173     val abbrevs = NameSpace.extern_table (space, Symtab.make (Symtab.fold add_abbr consts []));
  1174   in
  1175     if null abbrevs andalso not (! verbose) then []
  1176     else [Pretty.big_list "abbreviations:" (map (pretty_term_abbrev ctxt o #2) abbrevs)]
  1177   end;
  1178 
  1179 val print_abbrevs = Pretty.writeln o Pretty.chunks o pretty_abbrevs true;
  1180 
  1181 
  1182 (* term bindings *)
  1183 
  1184 fun pretty_binds ctxt =
  1185   let
  1186     val binds = Variable.binds_of ctxt;
  1187     fun prt_bind (xi, (T, t)) = pretty_term_abbrev ctxt (Logic.mk_equals (Var (xi, T), t));
  1188   in
  1189     if Vartab.is_empty binds andalso not (! verbose) then []
  1190     else [Pretty.big_list "term bindings:" (map prt_bind (Vartab.dest binds))]
  1191   end;
  1192 
  1193 val print_binds = Pretty.writeln o Pretty.chunks o pretty_binds;
  1194 
  1195 
  1196 (* local theorems *)
  1197 
  1198 fun pretty_lthms ctxt =
  1199   let
  1200     val props = FactIndex.props (fact_index_of ctxt);
  1201     val facts =
  1202       (if null props then I else cons ("unnamed", props))
  1203       (NameSpace.extern_table (#1 (thms_of ctxt)));
  1204   in
  1205     if null facts andalso not (! verbose) then []
  1206     else [Pretty.big_list "facts:" (map (pretty_fact ctxt) facts)]
  1207   end;
  1208 
  1209 val print_lthms = Pretty.writeln o Pretty.chunks o pretty_lthms;
  1210 
  1211 
  1212 (* local contexts *)
  1213 
  1214 fun pretty_cases ctxt =
  1215   let
  1216     val prt_term = Syntax.pretty_term ctxt;
  1217 
  1218     fun prt_let (xi, t) = Pretty.block
  1219       [Pretty.quote (prt_term (Var (xi, Term.fastype_of t))), Pretty.str " =", Pretty.brk 1,
  1220         Pretty.quote (prt_term t)];
  1221 
  1222     fun prt_asm (a, ts) = Pretty.block (Pretty.breaks
  1223       ((if a = "" then [] else [Pretty.str (a ^ ":")]) @ map (Pretty.quote o prt_term) ts));
  1224 
  1225     fun prt_sect _ _ _ [] = []
  1226       | prt_sect s sep prt xs = [Pretty.block (Pretty.breaks (Pretty.str s ::
  1227             flat (Library.separate sep (map (Library.single o prt) xs))))];
  1228 
  1229     fun prt_case (name, (fixes, (asms, (lets, cs)))) = Pretty.block (Pretty.fbreaks
  1230       (Pretty.str (name ^ ":") ::
  1231         prt_sect "fix" [] (Pretty.str o fst) fixes @
  1232         prt_sect "let" [Pretty.str "and"] prt_let
  1233           (map_filter (fn (xi, SOME t) => SOME (xi, t) | _ => NONE) lets) @
  1234         (if forall (null o #2) asms then []
  1235           else prt_sect "assume" [Pretty.str "and"] prt_asm asms) @
  1236         prt_sect "subcases:" [] (Pretty.str o fst) cs));
  1237 
  1238     fun add_case (_, (_, false)) = I
  1239       | add_case (name, (c as RuleCases.Case {fixes, ...}, true)) =
  1240           cons (name, (fixes, #1 (case_result c ctxt)));
  1241     val cases = fold add_case (cases_of ctxt) [];
  1242   in
  1243     if null cases andalso not (! verbose) then []
  1244     else [Pretty.big_list "cases:" (map prt_case cases)]
  1245   end;
  1246 
  1247 val print_cases = Pretty.writeln o Pretty.chunks o pretty_cases;
  1248 
  1249 
  1250 (* core context *)
  1251 
  1252 val prems_limit = ref ~1;
  1253 
  1254 fun pretty_ctxt ctxt =
  1255   if ! prems_limit < 0 andalso not (! debug) then []
  1256   else
  1257     let
  1258       val prt_term = Syntax.pretty_term ctxt;
  1259 
  1260       (*structures*)
  1261       val structs = LocalSyntax.structs_of (syntax_of ctxt);
  1262       val prt_structs = if null structs then []
  1263         else [Pretty.block (Pretty.str "structures:" :: Pretty.brk 1 ::
  1264           Pretty.commas (map Pretty.str structs))];
  1265 
  1266       (*fixes*)
  1267       fun prt_fix (x, x') =
  1268         if x = x' then Pretty.str x
  1269         else Pretty.block [Pretty.str x, Pretty.str " =", Pretty.brk 1, prt_term (Syntax.free x')];
  1270       val fixes =
  1271         rev (filter_out ((can Name.dest_internal orf member (op =) structs) o #1)
  1272           (Variable.fixes_of ctxt));
  1273       val prt_fixes = if null fixes then []
  1274         else [Pretty.block (Pretty.str "fixed variables:" :: Pretty.brk 1 ::
  1275           Pretty.commas (map prt_fix fixes))];
  1276 
  1277       (*prems*)
  1278       val prems = Assumption.prems_of ctxt;
  1279       val len = length prems;
  1280       val suppressed = len - ! prems_limit;
  1281       val prt_prems = if null prems then []
  1282         else [Pretty.big_list "prems:" ((if suppressed <= 0 then [] else [Pretty.str "..."]) @
  1283           map (pretty_thm ctxt) (Library.drop (suppressed, prems)))];
  1284     in prt_structs @ prt_fixes @ prt_prems end;
  1285 
  1286 
  1287 (* main context *)
  1288 
  1289 fun pretty_context ctxt =
  1290   let
  1291     val prt_term = Syntax.pretty_term ctxt;
  1292     val prt_typ = Syntax.pretty_typ ctxt;
  1293     val prt_sort = Syntax.pretty_sort ctxt;
  1294 
  1295     (*theory*)
  1296     val pretty_thy = Pretty.block
  1297       [Pretty.str "theory:", Pretty.brk 1, Context.pretty_thy (theory_of ctxt)];
  1298 
  1299     (*defaults*)
  1300     fun prt_atom prt prtT (x, X) = Pretty.block
  1301       [prt x, Pretty.str " ::", Pretty.brk 1, prtT X];
  1302 
  1303     fun prt_var (x, ~1) = prt_term (Syntax.free x)
  1304       | prt_var xi = prt_term (Syntax.var xi);
  1305 
  1306     fun prt_varT (x, ~1) = prt_typ (TFree (x, []))
  1307       | prt_varT xi = prt_typ (TVar (xi, []));
  1308 
  1309     val prt_defT = prt_atom prt_var prt_typ;
  1310     val prt_defS = prt_atom prt_varT prt_sort;
  1311 
  1312     val (types, sorts) = Variable.constraints_of ctxt;
  1313   in
  1314     verb single (K pretty_thy) @
  1315     pretty_ctxt ctxt @
  1316     verb (pretty_abbrevs false) (K ctxt) @
  1317     verb pretty_binds (K ctxt) @
  1318     verb pretty_lthms (K ctxt) @
  1319     verb pretty_cases (K ctxt) @
  1320     verb single (fn () => Pretty.big_list "type constraints:" (map prt_defT (Vartab.dest types))) @
  1321     verb single (fn () => Pretty.big_list "default sorts:" (map prt_defS (Vartab.dest sorts)))
  1322   end;
  1323 
  1324 end;