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