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