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