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