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