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