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