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