src/Pure/Isar/specification.ML
author wenzelm
Tue Sep 02 14:10:30 2008 +0200 (2008-09-02)
changeset 28080 4723eb2456ce
parent 27858 d385b67f8439
child 28084 a05ca48ef263
permissions -rw-r--r--
explicit type Name.binding for higher-specification elements;
simplified ProofContext.inferred_param;
     1 (*  Title:      Pure/Isar/specification.ML
     2     ID:         $Id$
     3     Author:     Makarius
     4 
     5 Derived local theory specifications --- with type-inference and
     6 toplevel polymorphism.
     7 *)
     8 
     9 signature SPECIFICATION =
    10 sig
    11   val print_consts: local_theory -> (string * typ -> bool) -> (string * typ) list -> unit
    12   val check_specification: (Name.binding * typ option * mixfix) list ->
    13     ((Name.binding * Attrib.src list) * term list) list list -> Proof.context ->
    14     (((Name.binding * typ) * mixfix) list * ((Name.binding * Attrib.src list) * term list) list) *
    15     Proof.context
    16   val read_specification: (Name.binding * string option * mixfix) list ->
    17     ((Name.binding * Attrib.src list) * string list) list list -> Proof.context ->
    18     (((Name.binding * typ) * mixfix) list * ((Name.binding * Attrib.src list) * term list) list) *
    19     Proof.context
    20   val check_free_specification: (Name.binding * typ option * mixfix) list ->
    21     ((Name.binding * Attrib.src list) * term list) list -> Proof.context ->
    22     (((Name.binding * typ) * mixfix) list * ((Name.binding * Attrib.src list) * term list) list) *
    23     Proof.context
    24   val read_free_specification: (Name.binding * string option * mixfix) list ->
    25     ((Name.binding * Attrib.src list) * string list) list -> Proof.context ->
    26     (((Name.binding * typ) * mixfix) list * ((Name.binding * Attrib.src list) * term list) list) *
    27     Proof.context
    28   val axiomatization: (Name.binding * typ option * mixfix) list ->
    29     ((Name.binding * Attrib.src list) * term list) list -> local_theory ->
    30     (term list * (string * thm list) list) * local_theory
    31   val axiomatization_cmd: (Name.binding * string option * mixfix) list ->
    32     ((Name.binding * Attrib.src list) * string list) list -> local_theory ->
    33     (term list * (string * thm list) list) * local_theory
    34   val definition:
    35     (Name.binding * typ option * mixfix) option * ((Name.binding * Attrib.src list) * term) ->
    36     local_theory -> (term * (string * thm)) * local_theory
    37   val definition_cmd:
    38     (Name.binding * string option * mixfix) option * ((Name.binding * Attrib.src list) * string) ->
    39     local_theory -> (term * (string * thm)) * local_theory
    40   val abbreviation: Syntax.mode -> (Name.binding * typ option * mixfix) option * term ->
    41     local_theory -> local_theory
    42   val abbreviation_cmd: Syntax.mode -> (Name.binding * string option * mixfix) option * string ->
    43     local_theory -> local_theory
    44   val notation: bool -> Syntax.mode -> (term * mixfix) list -> local_theory -> local_theory
    45   val notation_cmd: bool -> Syntax.mode -> (string * mixfix) list -> local_theory -> local_theory
    46   val theorems: string ->
    47     ((Name.binding * Attrib.src list) * (thm list * Attrib.src list) list) list ->
    48     local_theory -> (string * thm list) list * local_theory
    49   val theorems_cmd: string ->
    50     ((Name.binding * Attrib.src list) * (Facts.ref * Attrib.src list) list) list ->
    51     local_theory -> (string * thm list) list * local_theory
    52   val theorem: string -> Method.text option ->
    53     (thm list list -> local_theory -> local_theory) -> Name.binding * Attrib.src list ->
    54     Element.context_i Locale.element list -> Element.statement_i ->
    55     bool -> local_theory -> Proof.state
    56   val theorem_cmd: string -> Method.text option ->
    57     (thm list list -> local_theory -> local_theory) -> Name.binding * Attrib.src list ->
    58     Element.context Locale.element list -> Element.statement ->
    59     bool -> local_theory -> Proof.state
    60   val add_theorem_hook: (bool -> Proof.state -> Proof.state) -> Context.generic -> Context.generic
    61 end;
    62 
    63 structure Specification: SPECIFICATION =
    64 struct
    65 
    66 
    67 (* diagnostics *)
    68 
    69 fun print_consts _ _ [] = ()
    70   | print_consts ctxt pred cs = Pretty.writeln (ProofDisplay.pretty_consts ctxt pred cs);
    71 
    72 
    73 (* prepare specification *)
    74 
    75 local
    76 
    77 fun close_forms ctxt i xs As =
    78   let
    79     fun add_free (Free (x, _)) = if Variable.is_fixed ctxt x then I else insert (op =) x
    80       | add_free _ = I;
    81 
    82     val commons = map #1 xs;
    83     val _ =
    84       (case duplicates (op =) commons of [] => ()
    85       | dups => error ("Duplicate local variables " ^ commas_quote dups));
    86     val frees = rev ((fold o fold_aterms) add_free As (rev commons));
    87     val types = map (TypeInfer.param i o rpair []) (Name.invents Name.context Name.aT (length frees));
    88     val uniform_typing = the o AList.lookup (op =) (frees ~~ types);
    89 
    90     fun abs_body lev y (Abs (x, T, b)) = Abs (x, T, abs_body (lev + 1) y b)
    91       | abs_body lev y (t $ u) = abs_body lev y t $ abs_body lev y u
    92       | abs_body lev y (t as Free (x, T)) =
    93           if x = y then TypeInfer.constrain (uniform_typing x) (TypeInfer.constrain T (Bound lev))
    94           else t
    95       | abs_body _ _ a = a;
    96     fun close (y, U) B =
    97       let val B' = abs_body 0 y (Term.incr_boundvars 1 B)
    98       in if Term.loose_bvar1 (B', 0) then Term.all dummyT $ Abs (y, U, B') else B end;
    99     fun close_form A =
   100       let
   101         val occ_frees = rev (fold_aterms add_free A []);
   102         val bounds = xs @ map (rpair dummyT) (subtract (op =) commons occ_frees);
   103       in fold_rev close bounds A end;
   104   in map close_form As end;
   105 
   106 fun prep_spec prep_vars parse_prop prep_att do_close raw_vars raw_specss ctxt =
   107   let
   108     val thy = ProofContext.theory_of ctxt;
   109 
   110     val (vars, vars_ctxt) = ctxt |> prep_vars raw_vars;
   111     val (xs, params_ctxt) = vars_ctxt |> ProofContext.add_fixes_i vars;
   112 
   113     val Asss = (map o map) (map (parse_prop params_ctxt) o snd) raw_specss;
   114     val names = Variable.names_of (params_ctxt |> (fold o fold o fold) Variable.declare_term Asss)
   115       |> fold Name.declare xs;
   116     val Asss' = #1 ((fold_map o fold_map o fold_map) Term.free_dummy_patterns Asss names);
   117     val idx = (fold o fold o fold) Term.maxidx_term Asss' ~1 + 1;
   118     val specs =
   119       (if do_close then
   120         #1 (fold_map
   121             (fn Ass => fn i => (burrow (close_forms params_ctxt i []) Ass, i + 1)) Asss' idx)
   122       else Asss')
   123       |> flat |> burrow (Syntax.check_props params_ctxt);
   124     val specs_ctxt = params_ctxt |> (fold o fold) Variable.declare_term specs;
   125 
   126     val Ts = specs_ctxt |> fold_map ProofContext.inferred_param xs |> fst;
   127     val params = map2 (fn (b, _, mx) => fn T => ((b, T), mx)) vars Ts;
   128     val name_atts = map (fn ((name, atts), _) => (name, map (prep_att thy) atts)) (flat raw_specss);
   129   in ((params, name_atts ~~ specs), specs_ctxt) end;
   130 
   131 fun read_spec x = prep_spec ProofContext.read_vars Syntax.parse_prop Attrib.intern_src x;
   132 fun check_spec x = prep_spec ProofContext.cert_vars (K I) (K I) x;
   133 
   134 in
   135 
   136 fun read_specification x = read_spec true x;
   137 fun check_specification x = check_spec true x;
   138 fun read_free_specification vars specs = read_spec false vars [specs];
   139 fun check_free_specification vars specs = check_spec false vars [specs];
   140 
   141 end;
   142 
   143 
   144 (* axiomatization *)
   145 
   146 fun gen_axioms do_print prep raw_vars raw_specs lthy =
   147   let
   148     val ((vars, specs), _) = prep raw_vars [raw_specs] lthy;
   149     val ((consts, axioms), lthy') = LocalTheory.axioms Thm.axiomK (vars, specs) lthy;
   150     val consts' = map (Morphism.term (LocalTheory.target_morphism lthy')) consts;
   151     val _ =
   152       if not do_print then ()
   153       else print_consts lthy' (member (op =) (fold Term.add_frees consts' []))
   154         (map (fn ((b, T), _) => (Name.name_of b, T)) vars);
   155   in ((consts, axioms), lthy') end;
   156 
   157 val axiomatization = gen_axioms false check_specification;
   158 val axiomatization_cmd = gen_axioms true read_specification;
   159 
   160 
   161 (* definition *)
   162 
   163 fun gen_def do_print prep (raw_var, (raw_a, raw_prop)) lthy =
   164   let
   165     val (vars, [((raw_name, atts), [prop])]) =
   166       fst (prep (the_list raw_var) [(raw_a, [raw_prop])] lthy);
   167     val (((x, T), rhs), prove) = LocalDefs.derived_def lthy true prop;
   168     val name = Name.map_name (Thm.def_name_optional x) raw_name;
   169     val var =
   170       (case vars of
   171         [] => (Name.binding x, NoSyn)
   172       | [((b, _), mx)] =>
   173           let
   174             val y = Name.name_of b;
   175             val _ = x = y orelse
   176               error ("Head of definition " ^ quote x ^ " differs from declaration " ^ quote y ^
   177                 Position.str_of (Name.pos_of b));
   178           in (b, mx) end);
   179     val ((lhs, (_, th)), lthy2) = lthy |> LocalTheory.define Thm.definitionK
   180         (var, ((Name.map_name (suffix "_raw") name, []), rhs));
   181     val ((def_name, [th']), lthy3) = lthy2 |> LocalTheory.note Thm.definitionK
   182         ((name, Code.add_default_func_attr :: atts), [prove lthy2 th]);
   183 
   184     val lhs' = Morphism.term (LocalTheory.target_morphism lthy3) lhs;
   185     val _ =
   186       if not do_print then ()
   187       else print_consts lthy3 (member (op =) (Term.add_frees lhs' [])) [(x, T)];
   188   in ((lhs, (def_name, th')), lthy3) end;
   189 
   190 val definition = gen_def false check_free_specification;
   191 val definition_cmd = gen_def true read_free_specification;
   192 
   193 
   194 (* abbreviation *)
   195 
   196 fun gen_abbrev do_print prep mode (raw_var, raw_prop) lthy =
   197   let
   198     val ((vars, [(_, [prop])]), _) =
   199       prep (the_list raw_var) [(("", []), [raw_prop])]
   200         (lthy |> ProofContext.set_mode ProofContext.mode_abbrev);
   201     val ((x, T), rhs) = LocalDefs.abs_def (#2 (LocalDefs.cert_def lthy prop));
   202     val var =
   203       (case vars of
   204         [] => (Name.binding x, NoSyn)
   205       | [((b, _), mx)] =>
   206           let
   207             val y = Name.name_of b;
   208             val _ = x = y orelse
   209               error ("Head of abbreviation " ^ quote x ^ " differs from declaration " ^ quote y ^
   210                 Position.str_of (Name.pos_of b));
   211           in (b, mx) end);
   212     val lthy' = lthy
   213       |> ProofContext.set_syntax_mode mode    (* FIXME ?!? *)
   214       |> LocalTheory.abbrev mode (var, rhs) |> snd
   215       |> ProofContext.restore_syntax_mode lthy;
   216 
   217     val _ = if not do_print then () else print_consts lthy' (K false) [(x, T)];
   218   in lthy' end;
   219 
   220 val abbreviation = gen_abbrev false check_free_specification;
   221 val abbreviation_cmd = gen_abbrev true read_free_specification;
   222 
   223 
   224 (* notation *)
   225 
   226 fun gen_notation prep_const add mode args lthy =
   227   lthy |> LocalTheory.notation add mode (map (apfst (prep_const lthy)) args);
   228 
   229 val notation = gen_notation (K I);
   230 val notation_cmd = gen_notation ProofContext.read_const;
   231 
   232 
   233 (* fact statements *)
   234 
   235 fun gen_theorems prep_fact prep_att kind raw_facts lthy =
   236   let
   237     val attrib = prep_att (ProofContext.theory_of lthy);
   238     val facts = raw_facts |> map (fn ((name, atts), bs) =>
   239       ((name, map attrib atts),
   240         bs |> map (fn (b, more_atts) => (prep_fact lthy b, map attrib more_atts))));
   241     val (res, lthy') = lthy |> LocalTheory.notes kind facts;
   242     val _ = ProofDisplay.theory_results lthy' ((kind, ""), res);
   243   in (res, lthy') end;
   244 
   245 val theorems = gen_theorems (K I) (K I);
   246 val theorems_cmd = gen_theorems ProofContext.get_fact Attrib.intern_src;
   247 
   248 
   249 (* complex goal statements *)
   250 
   251 local
   252 
   253 fun subtract_prems ctxt1 ctxt2 =
   254   Library.drop (length (Assumption.prems_of ctxt1), Assumption.prems_of ctxt2);
   255 
   256 fun prep_statement prep_att prep_stmt elems concl ctxt =
   257   (case concl of
   258     Element.Shows shows =>
   259       let
   260         val (_, loc_ctxt, elems_ctxt, propp) = prep_stmt elems (map snd shows) ctxt;
   261         val prems = subtract_prems loc_ctxt elems_ctxt;
   262         val stmt = Attrib.map_specs prep_att (map fst shows ~~ propp);
   263         val goal_ctxt = fold (fold (Variable.auto_fixes o fst)) propp elems_ctxt;
   264       in ((prems, stmt, []), goal_ctxt) end
   265   | Element.Obtains obtains =>
   266       let
   267         val case_names = obtains |> map_index (fn (i, (binding, _)) =>
   268           let val name = Name.name_of binding
   269           in if name = "" then string_of_int (i + 1) else name end);
   270         val constraints = obtains |> map (fn (_, (vars, _)) =>
   271           Locale.Elem (Element.Constrains
   272             (vars |> map_filter (fn (x, SOME T) => SOME (Name.name_of x, T) | _ => NONE))));
   273 
   274         val raw_propp = obtains |> map (fn (_, (_, props)) => map (rpair []) props);
   275         val (_, loc_ctxt, elems_ctxt, propp) = prep_stmt (elems @ constraints) raw_propp ctxt;
   276 
   277         val thesis = ObjectLogic.fixed_judgment (ProofContext.theory_of ctxt) AutoBind.thesisN;
   278 
   279         fun assume_case ((name, (vars, _)), asms) ctxt' =
   280           let
   281             val bs = map fst vars;
   282             val xs = map Name.name_of bs;
   283             val props = map fst asms;
   284             val (Ts, _) = ctxt'
   285               |> fold Variable.declare_term props
   286               |> fold_map ProofContext.inferred_param xs;
   287             val asm = Term.list_all_free (xs ~~ Ts, Logic.list_implies (props, thesis));
   288           in
   289             ctxt' |> (snd o ProofContext.add_fixes_i (map (fn b => (b, NONE, NoSyn)) bs));
   290             ctxt' |> Variable.auto_fixes asm
   291             |> ProofContext.add_assms_i Assumption.assume_export
   292               [((name, [ContextRules.intro_query NONE]), [(asm, [])])]
   293             |>> (fn [(_, [th])] => th)
   294           end;
   295 
   296         val atts = map (Attrib.internal o K)
   297           [RuleCases.consumes (~ (length obtains)), RuleCases.case_names case_names];
   298         val prems = subtract_prems loc_ctxt elems_ctxt;
   299         val stmt = [((Name.no_binding, atts), [(thesis, [])])];
   300 
   301         val (facts, goal_ctxt) = elems_ctxt
   302           |> (snd o ProofContext.add_fixes_i [(Name.binding AutoBind.thesisN, NONE, NoSyn)])
   303           |> fold_map assume_case (obtains ~~ propp)
   304           |-> (fn ths => ProofContext.note_thmss_i Thm.assumptionK
   305                 [((Name.binding Obtain.thatN, []), [(ths, [])])] #> #2 #> pair ths);
   306       in ((prems, stmt, facts), goal_ctxt) end);
   307 
   308 structure TheoremHook = GenericDataFun
   309 (
   310   type T = ((bool -> Proof.state -> Proof.state) * stamp) list;
   311   val empty = [];
   312   val extend = I;
   313   fun merge _ hooks : T = Library.merge (eq_snd op =) hooks;
   314 );
   315 
   316 fun gen_theorem prep_att prep_stmt
   317     kind before_qed after_qed (name, raw_atts) raw_elems raw_concl int lthy0 =
   318   let
   319     val _ = LocalTheory.affirm lthy0;
   320     val thy = ProofContext.theory_of lthy0;
   321 
   322     val (loc, ctxt, lthy) =
   323       (case (TheoryTarget.peek lthy0, exists (fn Locale.Expr _ => true | _ => false) raw_elems) of
   324         ({target, is_locale = true, ...}, true) =>
   325           (*temporary workaround for non-modularity of in/includes*)  (* FIXME *)
   326           (SOME target, ProofContext.init thy, LocalTheory.restore lthy0)
   327       | _ => (NONE, lthy0, lthy0));
   328 
   329     val attrib = prep_att thy;
   330     val atts = map attrib raw_atts;
   331 
   332     val elems = raw_elems |> map (Locale.map_elem (Element.map_ctxt_attrib attrib));
   333     val ((prems, stmt, facts), goal_ctxt) =
   334       prep_statement attrib (prep_stmt loc) elems raw_concl ctxt;
   335 
   336     fun after_qed' results goal_ctxt' =
   337       let val results' =
   338         burrow (map Goal.norm_result o ProofContext.export goal_ctxt' lthy) results
   339       in
   340         lthy
   341         |> LocalTheory.notes kind (map2 (fn (a, _) => fn ths => (a, [(ths, [])])) stmt results')
   342         |> (fn (res, lthy') =>
   343           if Name.name_of name = "" andalso null atts then
   344             (ProofDisplay.theory_results lthy' ((kind, ""), res); lthy')
   345           else
   346             let
   347               val ([(res_name, _)], lthy'') = lthy'
   348                 |> LocalTheory.notes kind [((name, atts), [(maps #2 res, [])])];
   349               val _ = ProofDisplay.theory_results lthy' ((kind, res_name), res);
   350             in lthy'' end)
   351         |> after_qed results'
   352       end;
   353   in
   354     goal_ctxt
   355     |> ProofContext.note_thmss_i Thm.assumptionK
   356       [((Name.binding AutoBind.assmsN, []), [(prems, [])])]
   357     |> snd
   358     |> Proof.theorem_i before_qed after_qed' (map snd stmt)
   359     |> Proof.refine_insert facts
   360     |> Library.apply (map (fn (f, _) => f int) (rev (TheoremHook.get (Context.Proof goal_ctxt))))
   361   end;
   362 
   363 in
   364 
   365 val theorem = gen_theorem (K I) Locale.cert_context_statement;
   366 val theorem_cmd = gen_theorem Attrib.intern_src Locale.read_context_statement_i;
   367 
   368 fun add_theorem_hook f = TheoremHook.map (cons (f, stamp ()));
   369 
   370 end;
   371 
   372 end;