src/Pure/Isar/theory_target.ML
author haftmann
Mon Oct 08 22:03:21 2007 +0200 (2007-10-08)
changeset 24914 95cda5dd58d5
parent 24911 4efb68e5576d
child 24935 a033971c63a0
permissions -rw-r--r--
added proper subclass concept; improved class target
     1 (*  Title:      Pure/Isar/theory_target.ML
     2     ID:         $Id$
     3     Author:     Makarius
     4 
     5 Common theory/locale targets.
     6 *)
     7 
     8 signature THEORY_TARGET =
     9 sig
    10   val peek: local_theory -> string option
    11   val begin: bstring -> Proof.context -> local_theory
    12   val init: xstring option -> theory -> local_theory
    13   val init_i: string option -> theory -> local_theory
    14 end;
    15 
    16 structure TheoryTarget: THEORY_TARGET =
    17 struct
    18 
    19 (** locale targets **)
    20 
    21 (* context data *)
    22 
    23 structure Data = ProofDataFun
    24 (
    25   type T = string option;
    26   fun init _ = NONE;
    27 );
    28 
    29 val peek = Data.get;
    30 
    31 
    32 (* pretty *)
    33 
    34 fun pretty loc ctxt =
    35   let
    36     val thy = ProofContext.theory_of ctxt;
    37     val fixes = map (fn (x, T) => (x, SOME T, NoSyn)) (#1 (ProofContext.inferred_fixes ctxt));
    38     val assumes = map (fn A => (("", []), [(A, [])])) (map Thm.term_of (Assumption.assms_of ctxt));
    39     val elems =
    40       (if null fixes then [] else [Element.Fixes fixes]) @
    41       (if null assumes then [] else [Element.Assumes assumes]);
    42   in
    43     if loc = "" then
    44       [Pretty.block
    45         [Pretty.str "theory", Pretty.brk 1, Pretty.str (Context.theory_name thy),
    46           Pretty.str " =", Pretty.brk 1, ThyInfo.pretty_theory thy]]
    47     else if null elems then [Pretty.str ("locale " ^ Locale.extern thy loc)]
    48     else
    49       [Pretty.big_list ("locale " ^ Locale.extern thy loc ^ " =")
    50         (map (Pretty.chunks o Element.pretty_ctxt ctxt) elems)]
    51   end;
    52 
    53 
    54 (* target declarations *)
    55 
    56 fun target_morphism loc lthy =
    57   ProofContext.export_morphism lthy (LocalTheory.target_of lthy) $>
    58   Morphism.thm_morphism Goal.norm_result;
    59 
    60 fun target_decl add loc d lthy =
    61   let
    62     val d' = Morphism.transform (target_morphism loc lthy) d;
    63     val d0 = Morphism.form d';
    64   in
    65     if loc = "" then
    66       lthy
    67       |> LocalTheory.theory (Context.theory_map d0)
    68       |> LocalTheory.target (Context.proof_map d0)
    69     else
    70       lthy
    71       |> LocalTheory.target (add loc d')
    72   end;
    73 
    74 val type_syntax = target_decl Locale.add_type_syntax;
    75 val term_syntax = target_decl Locale.add_term_syntax;
    76 val declaration = target_decl Locale.add_declaration;
    77 
    78 fun target_naming loc lthy =
    79   (if loc = "" then Sign.naming_of (ProofContext.theory_of lthy)
    80    else ProofContext.naming_of (LocalTheory.target_of lthy))
    81   |> NameSpace.qualified_names;
    82 
    83 
    84 (* consts *)
    85 
    86 fun target_abbrev prmode ((c, mx), rhs) phi =
    87   let
    88     val c' = Morphism.name phi c;
    89     val rhs' = Morphism.term phi rhs;
    90     val arg' = (c', rhs');
    91     val eq_heads =
    92       (case pairself Term.head_of (rhs, rhs') of
    93         (Const (a, _), Const (a', _)) => a = a'
    94       | _ => false);
    95   in
    96     eq_heads ? (Context.mapping_result
    97       (Sign.add_abbrev Syntax.internalM [] arg') (ProofContext.add_abbrev Syntax.internalM [] arg')
    98     #-> (fn (lhs, _) =>
    99       Term.equiv_types (rhs, rhs') ?
   100         Morphism.form (ProofContext.target_notation prmode [(lhs, mx)])))
   101   end;
   102 
   103 fun internal_abbrev prmode ((c, mx), t) lthy = lthy
   104   (* FIXME really permissive *)
   105   |> LocalTheory.term_syntax (perhaps o try o target_abbrev prmode ((c, mx), t))
   106   |> ProofContext.add_abbrev Syntax.internalM (ContextPosition.properties_of lthy) (c, t)
   107   |> snd;
   108 
   109 fun consts is_loc some_class depends decls lthy =
   110   let
   111     val xs = filter depends (#1 (ProofContext.inferred_fixes (LocalTheory.target_of lthy)));
   112 
   113     fun const ((c, T), mx) thy =
   114       let
   115         val U = map #2 xs ---> T;
   116         val t = Term.list_comb (Const (Sign.full_name thy c, U), map Free xs);
   117         val (mx1, mx2) = Class.fork_mixfix is_loc some_class mx;
   118         val mx3 = if is_loc then NoSyn else mx1;
   119         val thy' = Sign.add_consts_authentic (ContextPosition.properties_of lthy) [(c, U, mx3)] thy;
   120       in (((c, mx2), t), thy') end;
   121     fun const_class (SOME class) ((c, _), mx) (_, t) =
   122           LocalTheory.raw_theory_result
   123             (Class.add_const_in_class class ((c, t), mx))
   124           #-> (fn c => Class.remove_constraint [class] c)
   125       | const_class NONE _ _ = I;
   126     fun hide_abbrev (SOME class) abbrs thy =
   127           let
   128             val raw_cs = map (fst o fst) abbrs;
   129             val prfx = (Logic.const_of_class o NameSpace.base) class;
   130             fun mk_name c =
   131               let
   132                 val n1 = Sign.full_name thy c;
   133                 val n2 = NameSpace.qualifier n1;
   134                 val n3 = NameSpace.base n1;
   135               in NameSpace.implode [n2, prfx, prfx, n3] end;
   136             val cs = map mk_name raw_cs;
   137           in
   138             Sign.hide_consts_i true cs thy
   139           end
   140       | hide_abbrev NONE _ thy = thy;
   141 
   142     val (abbrs, lthy') = lthy
   143       |> LocalTheory.theory_result (fold_map const decls)
   144     val defs = map (apsnd (pair ("", []))) abbrs;
   145 
   146   in
   147     lthy'
   148     |> fold2 (const_class some_class) decls abbrs
   149     |> is_loc ? fold (internal_abbrev Syntax.default_mode) abbrs
   150     |> LocalTheory.raw_theory (hide_abbrev some_class abbrs)
   151         (*FIXME abbreviations should never occur*)
   152     |> LocalDefs.add_defs defs
   153     |>> map (apsnd snd)
   154   end;
   155 
   156 
   157 (* abbrev *)
   158 
   159 fun occ_params ctxt ts =
   160   #1 (ProofContext.inferred_fixes ctxt)
   161   |> filter (member (op =) (fold (Variable.add_fixed ctxt) ts []));
   162 
   163 fun local_abbrev (x, rhs) =
   164   Variable.add_fixes [x] #-> (fn [x'] =>
   165     let
   166       val T = Term.fastype_of rhs;
   167       val lhs = Free (x', T);
   168     in
   169       Variable.declare_term lhs #>
   170       Variable.declare_term rhs #>
   171       Assumption.add_assms (K (K (I, Envir.expand_term_frees [((x', T), rhs)]))) [] #> snd #>
   172       pair (lhs, rhs)
   173     end);
   174 
   175 fun abbrev is_loc some_class prmode ((raw_c, mx), raw_t) lthy =
   176   let
   177     val thy_ctxt = ProofContext.init (ProofContext.theory_of lthy);
   178     val target = LocalTheory.target_of lthy;
   179     val target_morphism = LocalTheory.target_morphism lthy;
   180 
   181     val c = Morphism.name target_morphism raw_c;
   182     val t = Morphism.term target_morphism raw_t;
   183     val xs = map Free (occ_params target [t]);
   184     val u = fold_rev Term.lambda xs t;
   185     val U = Term.fastype_of u;
   186     val u' = singleton (Variable.export_terms (Variable.declare_term u target) thy_ctxt) u;
   187     val (mx1, mx2) = Class.fork_mixfix is_loc some_class mx;
   188     val mx3 = if is_loc then NoSyn else mx1;
   189     fun add_abbrev_in_class (SOME class) abbr =
   190           LocalTheory.raw_theory_result (Class.add_abbrev_in_class class prmode abbr)
   191           #-> (fn c => Class.remove_constraint [class] c)
   192       | add_abbrev_in_class NONE _ = I;
   193   in
   194     lthy
   195     |> LocalTheory.theory_result
   196         (Sign.add_abbrev (#1 prmode) (ContextPosition.properties_of lthy) (c, u'))
   197     |-> (fn (lhs as Const (full_c, _), rhs) => LocalTheory.theory (Sign.add_notation prmode [(lhs, mx3)])
   198     #> is_loc ? internal_abbrev prmode ((c, mx2), Term.list_comb (Const (full_c, U), xs))
   199     #> add_abbrev_in_class some_class ((c, Term.list_comb (Const (full_c, U), xs)), mx1)
   200     #> local_abbrev (c, rhs))
   201   end;
   202 
   203 
   204 (* defs *)
   205 
   206 local
   207 
   208 fun expand_term ctxt t =
   209   let
   210     val thy = ProofContext.theory_of ctxt;
   211     val thy_ctxt = ProofContext.init thy;
   212     val ct = Thm.cterm_of thy t;
   213     val (defs, ct') = LocalDefs.export ctxt thy_ctxt (Drule.mk_term ct) ||> Drule.dest_term;
   214   in (Thm.term_of ct', MetaSimplifier.rewrite true defs ct) end;
   215 
   216 fun add_def (name, prop) thy =
   217   let
   218     val tfrees = rev (map TFree (Term.add_tfrees prop []));
   219     val tfrees' = map (fn a => TFree (a, [])) (Name.invents Name.context Name.aT (length tfrees));
   220     val strip_sorts = tfrees ~~ tfrees';
   221     val recover_sorts = map (pairself (Thm.ctyp_of thy o Logic.varifyT)) (tfrees' ~~ tfrees);
   222 
   223     val prop' = Term.map_types (Term.map_atyps (perhaps (AList.lookup (op =) strip_sorts))) prop;
   224     val thy' = Theory.add_defs_i false false [(name, prop')] thy;
   225     val axm' = Thm.get_axiom_i thy' (Sign.full_name thy' name);
   226     val def = Thm.instantiate (recover_sorts, []) axm';
   227   in (Drule.unvarify def, thy') end;
   228 
   229 in
   230 
   231 fun defs kind args lthy0 =
   232   let
   233     fun def ((c, mx), ((name, atts), rhs)) lthy1 =
   234       let
   235         val (rhs', rhs_conv) = expand_term lthy0 rhs;
   236         val xs = Variable.add_fixed (LocalTheory.target_of lthy0) rhs' [];
   237         val T = Term.fastype_of rhs;
   238 
   239         val ([(lhs, lhs_def)], lthy2) = lthy1
   240           |> LocalTheory.consts (member (op =) xs) [((c, T), mx)];
   241         val lhs' = #2 (Logic.dest_equals (Thm.prop_of lhs_def));
   242 
   243         val name' = Thm.def_name_optional c name;
   244         val (def, lthy3) = lthy2
   245           |> LocalTheory.theory_result (add_def (name', Logic.mk_equals (lhs', rhs')));
   246         val eq = LocalDefs.trans_terms lthy3
   247           [(*c == loc.c xs*) lhs_def,
   248            (*lhs' == rhs'*)  def,
   249            (*rhs' == rhs*)   Thm.symmetric rhs_conv];
   250       in ((lhs, ((name', atts), [([eq], [])])), lthy3) end;
   251 
   252     val ((lhss, facts), lthy') = lthy0 |> fold_map def args |>> split_list;
   253     val (res, lthy'') = lthy' |> LocalTheory.notes kind facts;
   254 
   255   in (lhss ~~ map (apsnd the_single) res, lthy'') end;
   256 
   257 end;
   258 
   259 
   260 (* axioms *)
   261 
   262 local
   263 
   264 fun add_axiom hyps (name, prop) thy =
   265   let
   266     val name' = if name = "" then "axiom_" ^ serial_string () else name;
   267     val prop' = Logic.list_implies (hyps, prop);
   268     val thy' = thy |> Theory.add_axioms_i [(name', prop')];
   269     val axm = Drule.unvarify (Thm.get_axiom_i thy' (Sign.full_name thy' name'));
   270     val prems = map (Thm.assume o Thm.cterm_of thy') hyps;
   271   in (Drule.implies_elim_list axm prems, thy') end;
   272 
   273 in
   274 
   275 fun axioms kind specs lthy =
   276   let
   277     val hyps = map Thm.term_of (Assumption.assms_of lthy);
   278     fun axiom ((name, atts), props) thy = thy
   279       |> fold_map (add_axiom hyps) (PureThy.name_multi name props)
   280       |-> (fn ths => pair ((name, atts), [(ths, [])]));
   281   in
   282     lthy
   283     |> fold (fold Variable.declare_term o snd) specs
   284     |> LocalTheory.theory_result (fold_map axiom specs)
   285     |-> LocalTheory.notes kind
   286   end;
   287 
   288 end;
   289 
   290 
   291 (* notes *)
   292 
   293 fun import_export_proof ctxt (name, raw_th) =
   294   let
   295     val thy = ProofContext.theory_of ctxt;
   296     val thy_ctxt = ProofContext.init thy;
   297     val certT = Thm.ctyp_of thy;
   298     val cert = Thm.cterm_of thy;
   299 
   300     (*export assumes/defines*)
   301     val th = Goal.norm_result raw_th;
   302     val (defs, th') = LocalDefs.export ctxt thy_ctxt th;
   303     val concl_conv = MetaSimplifier.rewrite true defs (Thm.cprop_of th);
   304     val assms = map (MetaSimplifier.rewrite_rule defs o Thm.assume) (Assumption.assms_of ctxt);
   305     val nprems = Thm.nprems_of th' - Thm.nprems_of th;
   306 
   307     (*export fixes*)
   308     val tfrees = map TFree (Thm.fold_terms Term.add_tfrees th' []);
   309     val frees = map Free (Thm.fold_terms Term.add_frees th' []);
   310     val (th'' :: vs) = (th' :: map (Drule.mk_term o cert) (map Logic.mk_type tfrees @ frees))
   311       |> Variable.export ctxt thy_ctxt
   312       |> Drule.zero_var_indexes_list;
   313 
   314     (*thm definition*)
   315     val result = th''
   316       |> PureThy.name_thm true true ""
   317       |> Goal.close_result
   318       |> fold PureThy.tag_rule (ContextPosition.properties_of ctxt)
   319       |> PureThy.name_thm true true name;
   320 
   321     (*import fixes*)
   322     val (tvars, vars) =
   323       chop (length tfrees) (map (Thm.term_of o Drule.dest_term) vs)
   324       |>> map Logic.dest_type;
   325 
   326     val instT = map_filter (fn (TVar v, T) => SOME (v, T) | _ => NONE) (tvars ~~ tfrees);
   327     val inst = filter (is_Var o fst) (vars ~~ frees);
   328     val cinstT = map (pairself certT o apfst TVar) instT;
   329     val cinst = map (pairself (cert o Term.map_types (TermSubst.instantiateT instT))) inst;
   330     val result' = Thm.instantiate (cinstT, cinst) result;
   331 
   332     (*import assumes/defines*)
   333     val assm_tac = FIRST' (map (fn assm => Tactic.compose_tac (false, assm, 0)) assms);
   334     val result'' =
   335       (case SINGLE (Seq.INTERVAL assm_tac 1 nprems) result' of
   336         NONE => raise THM ("Failed to re-import result", 0, [result'])
   337       | SOME res => LocalDefs.trans_props ctxt [res, Thm.symmetric concl_conv])
   338       |> Goal.norm_result
   339       |> PureThy.name_thm false false name;
   340 
   341   in (result'', result) end;
   342 
   343 fun notes loc kind facts lthy =
   344   let
   345     val is_loc = loc <> "";
   346     val thy = ProofContext.theory_of lthy;
   347     val full = LocalTheory.full_name lthy;
   348 
   349     val facts' = facts
   350       |> map (fn (a, bs) => (a, PureThy.burrow_fact (PureThy.name_multi (full (fst a))) bs))
   351       |> PureThy.map_facts (import_export_proof lthy);
   352     val local_facts = PureThy.map_facts #1 facts'
   353       |> Attrib.map_facts (Attrib.attribute_i thy);
   354     val target_facts = PureThy.map_facts #1 facts'
   355       |> is_loc ? Element.facts_map (Element.morph_ctxt (LocalTheory.target_morphism lthy));
   356     val global_facts = PureThy.map_facts #2 facts'
   357       |> Attrib.map_facts (if is_loc then K I else Attrib.attribute_i thy);
   358   in
   359     lthy |> LocalTheory.theory
   360       (Sign.qualified_names
   361         #> PureThy.note_thmss_i kind global_facts #> snd
   362         #> Sign.restore_naming thy)
   363 
   364     |> is_loc ? LocalTheory.target (Locale.add_thmss loc kind target_facts)
   365 
   366     |> ProofContext.set_stmt true
   367     |> ProofContext.qualified_names
   368     |> ProofContext.note_thmss_i kind local_facts
   369     ||> ProofContext.restore_naming lthy
   370     ||> ProofContext.restore_mode lthy
   371   end;
   372 
   373 
   374 (* init and exit *)
   375 
   376 fun begin loc ctxt =
   377   let
   378     val thy = ProofContext.theory_of ctxt;
   379     val is_loc = loc <> "";
   380     val some_class = Class.class_of_locale thy loc;
   381   in
   382     ctxt
   383     |> Data.put (if is_loc then SOME loc else NONE)
   384     |> the_default I (Option.map Class.init some_class)
   385     |> LocalTheory.init (NameSpace.base loc)
   386      {pretty = pretty loc,
   387       consts = consts is_loc some_class,
   388       axioms = axioms,
   389       abbrev = abbrev is_loc some_class,
   390       defs = defs,
   391       notes = notes loc,
   392       type_syntax = type_syntax loc,
   393       term_syntax = term_syntax loc,
   394       declaration = declaration loc,
   395       target_morphism = target_morphism loc,
   396       target_naming = target_naming loc,
   397       reinit = fn _ =>
   398         (if is_loc then Locale.init loc else ProofContext.init)
   399         #> begin loc,
   400       exit = LocalTheory.target_of }
   401   end;
   402 
   403 fun init_i NONE thy = begin "" (ProofContext.init thy)
   404   | init_i (SOME loc) thy = begin loc (Locale.init loc thy);
   405 
   406 fun init (SOME "-") thy = init_i NONE thy
   407   | init loc thy = init_i (Option.map (Locale.intern thy) loc) thy;
   408 
   409 end;