src/Pure/Isar/specification.ML
author wenzelm
Sun May 30 21:34:19 2010 +0200 (2010-05-30)
changeset 37198 3af985b10550
parent 37145 01aa36932739
child 37216 3165bc303f66
permissions -rw-r--r--
replaced ML_Lex.read_antiq by more concise ML_Lex.read, which includes full read/report with explicit position information;
ML_Context.eval/expression expect explicit ML_Lex source, which allows surrounding further text without loosing position information;
fall back on ML_Context.eval_text if there is no position or no surrounding text;
proper Args.name_source_position for method "tactic" and "raw_tactic";
tuned;
     1 (*  Title:      Pure/Isar/specification.ML
     2     Author:     Makarius
     3 
     4 Derived local theory specifications --- with type-inference and
     5 toplevel polymorphism.
     6 *)
     7 
     8 signature SPECIFICATION =
     9 sig
    10   val print_consts: local_theory -> (string * typ -> bool) -> (string * typ) list -> unit
    11   val check_spec:
    12     (binding * typ option * mixfix) list -> (Attrib.binding * term) list -> Proof.context ->
    13     (((binding * typ) * mixfix) list * (Attrib.binding * term) list) * Proof.context
    14   val read_spec:
    15     (binding * string option * mixfix) list -> (Attrib.binding * string) list -> Proof.context ->
    16     (((binding * typ) * mixfix) list * (Attrib.binding * term) list) * Proof.context
    17   val check_free_spec:
    18     (binding * typ option * mixfix) list -> (Attrib.binding * term) list -> Proof.context ->
    19     (((binding * typ) * mixfix) list * (Attrib.binding * term) list) * Proof.context
    20   val read_free_spec:
    21     (binding * string option * mixfix) list -> (Attrib.binding * string) list -> Proof.context ->
    22     (((binding * typ) * mixfix) list * (Attrib.binding * term) list) * Proof.context
    23   val check_specification: (binding * typ option * mixfix) list ->
    24     (Attrib.binding * term list) list -> Proof.context ->
    25     (((binding * typ) * mixfix) list * (Attrib.binding * term list) list) * Proof.context
    26   val read_specification: (binding * string option * mixfix) list ->
    27     (Attrib.binding * string list) list -> Proof.context ->
    28     (((binding * typ) * mixfix) list * (Attrib.binding * term list) list) * Proof.context
    29   val axiomatization: (binding * typ option * mixfix) list ->
    30     (Attrib.binding * term list) list -> theory ->
    31     (term list * thm list list) * theory
    32   val axiomatization_cmd: (binding * string option * mixfix) list ->
    33     (Attrib.binding * string list) list -> theory ->
    34     (term list * thm list list) * theory
    35   val axiom: Attrib.binding * term -> theory -> thm * theory
    36   val axiom_cmd: Attrib.binding * string -> theory -> thm * theory
    37   val definition:
    38     (binding * typ option * mixfix) option * (Attrib.binding * term) ->
    39     local_theory -> (term * (string * thm)) * local_theory
    40   val definition_cmd:
    41     (binding * string option * mixfix) option * (Attrib.binding * string) ->
    42     local_theory -> (term * (string * thm)) * local_theory
    43   val abbreviation: Syntax.mode -> (binding * typ option * mixfix) option * term ->
    44     local_theory -> local_theory
    45   val abbreviation_cmd: Syntax.mode -> (binding * string option * mixfix) option * string ->
    46     local_theory -> local_theory
    47   val type_notation: bool -> Syntax.mode -> (typ * mixfix) list -> local_theory -> local_theory
    48   val type_notation_cmd: bool -> Syntax.mode -> (string * mixfix) list -> local_theory -> local_theory
    49   val notation: bool -> Syntax.mode -> (term * mixfix) list -> local_theory -> local_theory
    50   val notation_cmd: bool -> Syntax.mode -> (string * mixfix) list -> local_theory -> local_theory
    51   val theorems: string ->
    52     (Attrib.binding * (thm list * Attrib.src list) list) list ->
    53     local_theory -> (string * thm list) list * local_theory
    54   val theorems_cmd: string ->
    55     (Attrib.binding * (Facts.ref * Attrib.src list) list) list ->
    56     local_theory -> (string * thm list) list * local_theory
    57   val theorem: string -> Method.text option ->
    58     (thm list list -> local_theory -> local_theory) -> Attrib.binding ->
    59     Element.context_i list -> Element.statement_i ->
    60     bool -> local_theory -> Proof.state
    61   val theorem_cmd: string -> Method.text option ->
    62     (thm list list -> local_theory -> local_theory) -> Attrib.binding ->
    63     Element.context list -> Element.statement ->
    64     bool -> local_theory -> Proof.state
    65   val schematic_theorem: string -> Method.text option ->
    66     (thm list list -> local_theory -> local_theory) -> Attrib.binding ->
    67     Element.context_i list -> Element.statement_i ->
    68     bool -> local_theory -> Proof.state
    69   val schematic_theorem_cmd: string -> Method.text option ->
    70     (thm list list -> local_theory -> local_theory) -> Attrib.binding ->
    71     Element.context list -> Element.statement ->
    72     bool -> local_theory -> Proof.state
    73   val add_theorem_hook: (bool -> Proof.state -> Proof.state) -> Context.generic -> Context.generic
    74 end;
    75 
    76 structure Specification: SPECIFICATION =
    77 struct
    78 
    79 (* diagnostics *)
    80 
    81 fun print_consts _ _ [] = ()
    82   | print_consts ctxt pred cs = Pretty.writeln (Proof_Display.pretty_consts ctxt pred cs);
    83 
    84 
    85 (* prepare specification *)
    86 
    87 local
    88 
    89 fun close_forms ctxt i xs As =
    90   let
    91     fun add_free (Free (x, _)) = if Variable.is_fixed ctxt x then I else insert (op =) x
    92       | add_free _ = I;
    93 
    94     val commons = map #1 xs;
    95     val _ =
    96       (case duplicates (op =) commons of [] => ()
    97       | dups => error ("Duplicate local variables " ^ commas_quote dups));
    98     val frees = rev ((fold o fold_aterms) add_free As (rev commons));
    99     val types = map (Type_Infer.param i o rpair []) (Name.invents Name.context Name.aT (length frees));
   100     val uniform_typing = the o AList.lookup (op =) (frees ~~ types);
   101 
   102     fun abs_body lev y (Abs (x, T, b)) = Abs (x, T, abs_body (lev + 1) y b)
   103       | abs_body lev y (t $ u) = abs_body lev y t $ abs_body lev y u
   104       | abs_body lev y (t as Free (x, T)) =
   105           if x = y then Type_Infer.constrain (uniform_typing x) (Type_Infer.constrain T (Bound lev))
   106           else t
   107       | abs_body _ _ a = a;
   108     fun close (y, U) B =
   109       let val B' = abs_body 0 y (Term.incr_boundvars 1 B)
   110       in if Term.loose_bvar1 (B', 0) then Term.all dummyT $ Abs (y, U, B') else B end;
   111     fun close_form A =
   112       let
   113         val occ_frees = rev (fold_aterms add_free A []);
   114         val bounds = xs @ map (rpair dummyT) (subtract (op =) commons occ_frees);
   115       in fold_rev close bounds A end;
   116   in map close_form As end;
   117 
   118 fun prepare prep_vars parse_prop prep_att do_close raw_vars raw_specss ctxt =
   119   let
   120     val thy = ProofContext.theory_of ctxt;
   121 
   122     val (vars, vars_ctxt) = ctxt |> prep_vars raw_vars;
   123     val (xs, params_ctxt) = vars_ctxt |> ProofContext.add_fixes vars;
   124 
   125     val Asss = (map o map) (map (parse_prop params_ctxt) o snd) raw_specss;
   126     val names = Variable.names_of (params_ctxt |> (fold o fold o fold) Variable.declare_term Asss)
   127       |> fold Name.declare xs;
   128     val Asss' = #1 ((fold_map o fold_map o fold_map) Term.free_dummy_patterns Asss names);
   129     val idx = (fold o fold o fold) Term.maxidx_term Asss' ~1 + 1;
   130     val specs =
   131       (if do_close then
   132         #1 (fold_map
   133             (fn Ass => fn i => (burrow (close_forms params_ctxt i []) Ass, i + 1)) Asss' idx)
   134       else Asss')
   135       |> flat |> burrow (Syntax.check_props params_ctxt);
   136     val specs_ctxt = params_ctxt |> (fold o fold) Variable.declare_term specs;
   137 
   138     val Ts = specs_ctxt |> fold_map ProofContext.inferred_param xs |> fst;
   139     val params = map2 (fn (b, _, mx) => fn T => ((b, T), mx)) vars Ts;
   140     val name_atts = map (fn ((name, atts), _) => (name, map (prep_att thy) atts)) (flat raw_specss);
   141   in ((params, name_atts ~~ specs), specs_ctxt) end;
   142 
   143 
   144 fun single_spec (a, prop) = [(a, [prop])];
   145 fun the_spec (a, [prop]) = (a, prop);
   146 
   147 fun prep_spec prep_vars parse_prop prep_att do_close vars specs =
   148   prepare prep_vars parse_prop prep_att do_close
   149     vars (map single_spec specs) #>> apsnd (map the_spec);
   150 
   151 in
   152 
   153 fun check_spec x = prep_spec ProofContext.cert_vars (K I) (K I) true x;
   154 fun read_spec x = prep_spec ProofContext.read_vars Syntax.parse_prop Attrib.intern_src true x;
   155 
   156 fun check_free_spec x = prep_spec ProofContext.cert_vars (K I) (K I) false x;
   157 fun read_free_spec x = prep_spec ProofContext.read_vars Syntax.parse_prop Attrib.intern_src false x;
   158 
   159 fun check_specification vars specs =
   160   prepare ProofContext.cert_vars (K I) (K I) true vars [specs];
   161 
   162 fun read_specification vars specs =
   163   prepare ProofContext.read_vars Syntax.parse_prop Attrib.intern_src true vars [specs];
   164 
   165 end;
   166 
   167 
   168 (* axiomatization -- within global theory *)
   169 
   170 fun gen_axioms do_print prep raw_vars raw_specs thy =
   171   let
   172     val ((vars, specs), _) = prep raw_vars raw_specs (ProofContext.init_global thy);
   173     val xs = map (fn ((b, T), _) => (Name.of_binding b, T)) vars;
   174 
   175     (*consts*)
   176     val (consts, consts_thy) = thy |> fold_map Theory.specify_const vars;
   177     val subst = Term.subst_atomic (map Free xs ~~ consts);
   178 
   179     (*axioms*)
   180     val (axioms, axioms_thy) = (specs, consts_thy) |-> fold_map (fn ((b, atts), props) =>
   181         fold_map Thm.add_axiom
   182           (map (apfst (fn a => Binding.map_name (K a) b))
   183             (PureThy.name_multi (Name.of_binding b) (map subst props)))
   184         #>> (fn ths => ((b, atts), [(map #2 ths, [])])));
   185 
   186     (*facts*)
   187     val (facts, facts_lthy) = axioms_thy
   188       |> Theory_Target.init NONE
   189       |> Spec_Rules.add Spec_Rules.Unknown (consts, maps (maps #1 o #2) axioms)
   190       |> Local_Theory.notes axioms;
   191 
   192     val _ =
   193       if not do_print then ()
   194       else print_consts facts_lthy (K false) xs;
   195   in ((consts, map #2 facts), Local_Theory.exit_global facts_lthy) end;
   196 
   197 val axiomatization = gen_axioms false check_specification;
   198 val axiomatization_cmd = gen_axioms true read_specification;
   199 
   200 fun axiom (b, ax) = axiomatization [] [(b, [ax])] #>> (hd o hd o snd);
   201 fun axiom_cmd (b, ax) = axiomatization_cmd [] [(b, [ax])] #>> (hd o hd o snd);
   202 
   203 
   204 (* definition *)
   205 
   206 fun gen_def do_print prep (raw_var, raw_spec) lthy =
   207   let
   208     val (vars, [((raw_name, atts), prop)]) = fst (prep (the_list raw_var) [raw_spec] lthy);
   209     val (((x, T), rhs), prove) = Local_Defs.derived_def lthy true prop;
   210     val var as (b, _) =
   211       (case vars of
   212         [] => (Binding.name x, NoSyn)
   213       | [((b, _), mx)] =>
   214           let
   215             val y = Name.of_binding b;
   216             val _ = x = y orelse
   217               error ("Head of definition " ^ quote x ^ " differs from declaration " ^ quote y ^
   218                 Position.str_of (Binding.pos_of b));
   219           in (b, mx) end);
   220     val name = Thm.def_binding_optional b raw_name;
   221     val ((lhs, (_, raw_th)), lthy2) = lthy
   222       |> Local_Theory.define (var, ((Binding.suffix_name "_raw" name, []), rhs));
   223 
   224     val th = prove lthy2 raw_th;
   225     val lthy3 = lthy2 |> Spec_Rules.add Spec_Rules.Equational ([lhs], [th]);
   226 
   227     val ([(def_name, [th'])], lthy4) = lthy3
   228       |> Local_Theory.notes_kind Thm.definitionK
   229         [((name, Code.add_default_eqn_attrib :: atts), [([th], [])])];
   230 
   231     val lhs' = Morphism.term (Local_Theory.target_morphism lthy4) lhs;
   232     val _ =
   233       if not do_print then ()
   234       else print_consts lthy4 (member (op =) (Term.add_frees lhs' [])) [(x, T)];
   235   in ((lhs, (def_name, th')), lthy4) end;
   236 
   237 val definition = gen_def false check_free_spec;
   238 val definition_cmd = gen_def true read_free_spec;
   239 
   240 
   241 (* abbreviation *)
   242 
   243 fun gen_abbrev do_print prep mode (raw_var, raw_prop) lthy =
   244   let
   245     val ((vars, [(_, prop)]), _) =
   246       prep (the_list raw_var) [(Attrib.empty_binding, raw_prop)]
   247         (lthy |> ProofContext.set_mode ProofContext.mode_abbrev);
   248     val ((x, T), rhs) = Local_Defs.abs_def (#2 (Local_Defs.cert_def lthy prop));
   249     val var =
   250       (case vars of
   251         [] => (Binding.name x, NoSyn)
   252       | [((b, _), mx)] =>
   253           let
   254             val y = Name.of_binding b;
   255             val _ = x = y orelse
   256               error ("Head of abbreviation " ^ quote x ^ " differs from declaration " ^ quote y ^
   257                 Position.str_of (Binding.pos_of b));
   258           in (b, mx) end);
   259     val lthy' = lthy
   260       |> ProofContext.set_syntax_mode mode    (* FIXME ?!? *)
   261       |> Local_Theory.abbrev mode (var, rhs) |> snd
   262       |> ProofContext.restore_syntax_mode lthy;
   263 
   264     val _ = if not do_print then () else print_consts lthy' (K false) [(x, T)];
   265   in lthy' end;
   266 
   267 val abbreviation = gen_abbrev false check_free_spec;
   268 val abbreviation_cmd = gen_abbrev true read_free_spec;
   269 
   270 
   271 (* notation *)
   272 
   273 local
   274 
   275 fun gen_type_notation prep_type add mode args lthy =
   276   lthy |> Local_Theory.type_notation add mode (map (apfst (prep_type lthy)) args);
   277 
   278 fun gen_notation prep_const add mode args lthy =
   279   lthy |> Local_Theory.notation add mode (map (apfst (prep_const lthy)) args);
   280 
   281 in
   282 
   283 val type_notation = gen_type_notation (K I);
   284 val type_notation_cmd = gen_type_notation (fn ctxt => ProofContext.read_type_name ctxt false);
   285 
   286 val notation = gen_notation (K I);
   287 val notation_cmd = gen_notation (fn ctxt => ProofContext.read_const ctxt false dummyT);
   288 
   289 end;
   290 
   291 
   292 (* fact statements *)
   293 
   294 fun gen_theorems prep_fact prep_att kind raw_facts lthy =
   295   let
   296     val attrib = prep_att (ProofContext.theory_of lthy);
   297     val facts = raw_facts |> map (fn ((name, atts), bs) =>
   298       ((name, map attrib atts),
   299         bs |> map (fn (b, more_atts) => (prep_fact lthy b, map attrib more_atts))));
   300     val (res, lthy') = lthy |> Local_Theory.notes_kind kind facts;
   301     val _ = Proof_Display.print_results true lthy' ((kind, ""), res);
   302   in (res, lthy') end;
   303 
   304 val theorems = gen_theorems (K I) (K I);
   305 val theorems_cmd = gen_theorems ProofContext.get_fact Attrib.intern_src;
   306 
   307 
   308 (* complex goal statements *)
   309 
   310 local
   311 
   312 fun prep_statement prep_att prep_stmt elems concl ctxt =
   313   (case concl of
   314     Element.Shows shows =>
   315       let
   316         val (propp, elems_ctxt) = prep_stmt elems (map snd shows) ctxt;
   317         val prems = Assumption.local_prems_of elems_ctxt ctxt;
   318         val stmt = Attrib.map_specs prep_att (map fst shows ~~ propp);
   319         val goal_ctxt = fold (fold (Variable.auto_fixes o fst)) propp elems_ctxt;
   320       in ((prems, stmt, NONE), goal_ctxt) end
   321   | Element.Obtains obtains =>
   322       let
   323         val case_names = obtains |> map_index (fn (i, (b, _)) =>
   324           if Binding.is_empty b then string_of_int (i + 1) else Name.of_binding b);
   325         val constraints = obtains |> map (fn (_, (vars, _)) =>
   326           Element.Constrains
   327             (vars |> map_filter (fn (x, SOME T) => SOME (Name.of_binding x, T) | _ => NONE)));
   328 
   329         val raw_propp = obtains |> map (fn (_, (_, props)) => map (rpair []) props);
   330         val (propp, elems_ctxt) = prep_stmt (elems @ constraints) raw_propp ctxt;
   331 
   332         val thesis = Object_Logic.fixed_judgment (ProofContext.theory_of ctxt) Auto_Bind.thesisN;
   333 
   334         fun assume_case ((name, (vars, _)), asms) ctxt' =
   335           let
   336             val bs = map fst vars;
   337             val xs = map Name.of_binding bs;
   338             val props = map fst asms;
   339             val (Ts, _) = ctxt'
   340               |> fold Variable.declare_term props
   341               |> fold_map ProofContext.inferred_param xs;
   342             val asm = Term.list_all_free (xs ~~ Ts, Logic.list_implies (props, thesis));
   343           in
   344             ctxt' |> (snd o ProofContext.add_fixes (map (fn b => (b, NONE, NoSyn)) bs));
   345             ctxt' |> Variable.auto_fixes asm
   346             |> ProofContext.add_assms_i Assumption.assume_export
   347               [((name, [Context_Rules.intro_query NONE]), [(asm, [])])]
   348             |>> (fn [(_, [th])] => th)
   349           end;
   350 
   351         val atts = map (Attrib.internal o K)
   352           [Rule_Cases.consumes (~ (length obtains)), Rule_Cases.case_names case_names];
   353         val prems = Assumption.local_prems_of elems_ctxt ctxt;
   354         val stmt = [((Binding.empty, atts), [(thesis, [])])];
   355 
   356         val (facts, goal_ctxt) = elems_ctxt
   357           |> (snd o ProofContext.add_fixes [(Binding.name Auto_Bind.thesisN, NONE, NoSyn)])
   358           |> fold_map assume_case (obtains ~~ propp)
   359           |-> (fn ths =>
   360             ProofContext.note_thmss "" [((Binding.name Obtain.thatN, []), [(ths, [])])] #>
   361             #2 #> pair ths);
   362       in ((prems, stmt, SOME facts), goal_ctxt) end);
   363 
   364 structure TheoremHook = Generic_Data
   365 (
   366   type T = ((bool -> Proof.state -> Proof.state) * stamp) list;
   367   val empty = [];
   368   val extend = I;
   369   fun merge hooks : T = Library.merge (eq_snd op =) hooks;
   370 );
   371 
   372 fun gen_theorem schematic prep_att prep_stmt
   373     kind before_qed after_qed (name, raw_atts) raw_elems raw_concl int lthy =
   374   let
   375     val _ = Local_Theory.affirm lthy;
   376     val thy = ProofContext.theory_of lthy;
   377 
   378     val attrib = prep_att thy;
   379     val atts = map attrib raw_atts;
   380     val elems = raw_elems |> map (Element.map_ctxt_attrib attrib);
   381     val ((prems, stmt, facts), goal_ctxt) =
   382       prep_statement attrib prep_stmt elems raw_concl lthy;
   383 
   384     fun after_qed' results goal_ctxt' =
   385       let val results' =
   386         burrow (map Goal.norm_result o ProofContext.export goal_ctxt' lthy) results
   387       in
   388         lthy
   389         |> Local_Theory.notes_kind kind
   390           (map2 (fn (a, _) => fn ths => (a, [(ths, [])])) stmt results')
   391         |> (fn (res, lthy') =>
   392           if Binding.is_empty name andalso null atts then
   393             (Proof_Display.print_results true lthy' ((kind, ""), res); lthy')
   394           else
   395             let
   396               val ([(res_name, _)], lthy'') = lthy'
   397                 |> Local_Theory.notes_kind kind [((name, atts), [(maps #2 res, [])])];
   398               val _ = Proof_Display.print_results true lthy' ((kind, res_name), res);
   399             in lthy'' end)
   400         |> after_qed results'
   401       end;
   402   in
   403     goal_ctxt
   404     |> ProofContext.note_thmss "" [((Binding.name Auto_Bind.assmsN, []), [(prems, [])])]
   405     |> snd
   406     |> Proof.theorem before_qed after_qed' (map snd stmt)
   407     |> (case facts of NONE => I | SOME ths => Proof.refine_insert ths)
   408     |> tap (fn state => not schematic andalso Proof.schematic_goal state andalso
   409         error "Illegal schematic goal statement")
   410     |> Library.apply (map (fn (f, _) => f int) (rev (TheoremHook.get (Context.Proof goal_ctxt))))
   411   end;
   412 
   413 in
   414 
   415 val theorem = gen_theorem false (K I) Expression.cert_statement;
   416 val theorem_cmd = gen_theorem false Attrib.intern_src Expression.read_statement;
   417 
   418 val schematic_theorem = gen_theorem true (K I) Expression.cert_statement;
   419 val schematic_theorem_cmd = gen_theorem true Attrib.intern_src Expression.read_statement;
   420 
   421 fun add_theorem_hook f = TheoremHook.map (cons (f, stamp ()));
   422 
   423 end;
   424 
   425 end;