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