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