src/Pure/Isar/theory_target.ML
author wenzelm
Sun Oct 25 19:18:59 2009 +0100 (2009-10-25)
changeset 33167 f02b804305d6
parent 32785 ec5292653aff
child 33173 b8ca12f6681a
permissions -rw-r--r--
maintain group via name space, not tags;
     1 (*  Title:      Pure/Isar/theory_target.ML
     2     Author:     Makarius
     3     Author:     Florian Haftmann, TU Muenchen
     4 
     5 Common theory/locale/class/instantiation/overloading targets.
     6 *)
     7 
     8 signature THEORY_TARGET =
     9 sig
    10   val peek: local_theory -> {target: string, is_locale: bool,
    11     is_class: bool, instantiation: string list * (string * sort) list * sort,
    12     overloading: (string * (string * typ) * bool) list}
    13   val init: string option -> theory -> local_theory
    14   val begin: string -> Proof.context -> local_theory
    15   val context: xstring -> theory -> local_theory
    16   val instantiation: string list * (string * sort) list * sort -> theory -> local_theory
    17   val instantiation_cmd: xstring list * xstring list * xstring -> theory -> local_theory
    18   val overloading: (string * (string * typ) * bool) list -> theory -> local_theory
    19   val overloading_cmd: (string * string * bool) list -> theory -> local_theory
    20 end;
    21 
    22 structure TheoryTarget: THEORY_TARGET =
    23 struct
    24 
    25 (* context data *)
    26 
    27 datatype target = Target of {target: string, is_locale: bool,
    28   is_class: bool, instantiation: string list * (string * sort) list * sort,
    29   overloading: (string * (string * typ) * bool) list};
    30 
    31 fun make_target target is_locale is_class instantiation overloading =
    32   Target {target = target, is_locale = is_locale,
    33     is_class = is_class, instantiation = instantiation, overloading = overloading};
    34 
    35 val global_target = make_target "" false false ([], [], []) [];
    36 
    37 structure Data = ProofDataFun
    38 (
    39   type T = target;
    40   fun init _ = global_target;
    41 );
    42 
    43 val peek = (fn Target args => args) o Data.get;
    44 
    45 
    46 (* pretty *)
    47 
    48 fun pretty_thy ctxt target is_class =
    49   let
    50     val thy = ProofContext.theory_of ctxt;
    51     val target_name = (if is_class then "class " else "locale ") ^ Locale.extern thy target;
    52     val fixes =
    53       map (fn (x, T) => (Binding.name x, SOME T, NoSyn)) (#1 (ProofContext.inferred_fixes ctxt));
    54     val assumes =
    55       map (fn A => (Attrib.empty_binding, [(Thm.term_of A, [])])) (Assumption.all_assms_of ctxt);
    56     val elems =
    57       (if null fixes then [] else [Element.Fixes fixes]) @
    58       (if null assumes then [] else [Element.Assumes assumes]);
    59   in
    60     if target = "" then []
    61     else if null elems then [Pretty.str target_name]
    62     else [Pretty.big_list (target_name ^ " =")
    63       (map (Pretty.chunks o Element.pretty_ctxt ctxt) elems)]
    64   end;
    65 
    66 fun pretty (Target {target, is_class, instantiation, overloading, ...}) ctxt =
    67   Pretty.block [Pretty.str "theory", Pretty.brk 1,
    68       Pretty.str (Context.theory_name (ProofContext.theory_of ctxt))] ::
    69     (if not (null overloading) then [Overloading.pretty ctxt]
    70      else if not (null (#1 instantiation)) then [Class_Target.pretty_instantiation ctxt]
    71      else pretty_thy ctxt target is_class);
    72 
    73 
    74 (* target declarations *)
    75 
    76 fun target_decl add (Target {target, ...}) d lthy =
    77   let
    78     val d' = Morphism.transform (LocalTheory.target_morphism lthy) d;
    79     val d0 = Morphism.form d';
    80   in
    81     if target = "" then
    82       lthy
    83       |> LocalTheory.theory (Context.theory_map d0)
    84       |> LocalTheory.target (Context.proof_map d0)
    85     else
    86       lthy
    87       |> LocalTheory.target (add target d')
    88   end;
    89 
    90 val type_syntax = target_decl Locale.add_type_syntax;
    91 val term_syntax = target_decl Locale.add_term_syntax;
    92 val declaration = target_decl Locale.add_declaration;
    93 
    94 fun class_target (Target {target, ...}) f =
    95   LocalTheory.raw_theory f #>
    96   LocalTheory.target (Class_Target.refresh_syntax target);
    97 
    98 
    99 (* notes *)
   100 
   101 fun import_export_proof ctxt (name, raw_th) =
   102   let
   103     val thy = ProofContext.theory_of ctxt;
   104     val thy_ctxt = ProofContext.init thy;
   105     val certT = Thm.ctyp_of thy;
   106     val cert = Thm.cterm_of thy;
   107 
   108     (*export assumes/defines*)
   109     val th = Goal.norm_result raw_th;
   110     val (defs, th') = LocalDefs.export ctxt thy_ctxt th;
   111     val concl_conv = MetaSimplifier.rewrite true defs (Thm.cprop_of th);
   112     val assms = map (MetaSimplifier.rewrite_rule defs o Thm.assume) (Assumption.all_assms_of ctxt);
   113     val nprems = Thm.nprems_of th' - Thm.nprems_of th;
   114 
   115     (*export fixes*)
   116     val tfrees = map TFree (Thm.fold_terms Term.add_tfrees th' []);
   117     val frees = map Free (Thm.fold_terms Term.add_frees th' []);
   118     val (th'' :: vs) = (th' :: map (Drule.mk_term o cert) (map Logic.mk_type tfrees @ frees))
   119       |> Variable.export ctxt thy_ctxt
   120       |> Drule.zero_var_indexes_list;
   121 
   122     (*thm definition*)
   123     val result = PureThy.name_thm true true Position.none name th'';
   124 
   125     (*import fixes*)
   126     val (tvars, vars) =
   127       chop (length tfrees) (map (Thm.term_of o Drule.dest_term) vs)
   128       |>> map Logic.dest_type;
   129 
   130     val instT = map_filter (fn (TVar v, T) => SOME (v, T) | _ => NONE) (tvars ~~ tfrees);
   131     val inst = filter (is_Var o fst) (vars ~~ frees);
   132     val cinstT = map (pairself certT o apfst TVar) instT;
   133     val cinst = map (pairself (cert o Term.map_types (Term_Subst.instantiateT instT))) inst;
   134     val result' = Thm.instantiate (cinstT, cinst) result;
   135 
   136     (*import assumes/defines*)
   137     val assm_tac = FIRST' (map (fn assm => Tactic.compose_tac (false, assm, 0)) assms);
   138     val result'' =
   139       (case SINGLE (Seq.INTERVAL assm_tac 1 nprems) result' of
   140         NONE => raise THM ("Failed to re-import result", 0, [result'])
   141       | SOME res => LocalDefs.trans_props ctxt [res, Thm.symmetric concl_conv])
   142       |> Goal.norm_result
   143       |> PureThy.name_thm false false Position.none name;
   144 
   145   in (result'', result) end;
   146 
   147 fun notes (Target {target, is_locale, ...}) kind facts lthy =
   148   let
   149     val thy = ProofContext.theory_of lthy;
   150     val facts' = facts
   151       |> map (fn (a, bs) => (a, PureThy.burrow_fact (PureThy.name_multi
   152           (LocalTheory.full_name lthy (fst a))) bs))
   153       |> PureThy.map_facts (import_export_proof lthy);
   154     val local_facts = PureThy.map_facts #1 facts'
   155       |> Attrib.map_facts (Attrib.attribute_i thy);
   156     val target_facts = PureThy.map_facts #1 facts'
   157       |> is_locale ? Element.facts_map (Element.morph_ctxt (LocalTheory.target_morphism lthy));
   158     val global_facts = PureThy.map_facts #2 facts'
   159       |> Attrib.map_facts (if is_locale then K I else Attrib.attribute_i thy);
   160   in
   161     lthy
   162     |> LocalTheory.theory (PureThy.note_thmss kind global_facts #> snd)
   163     |> not is_locale ? LocalTheory.target (ProofContext.note_thmss kind global_facts #> snd)
   164     |> is_locale ? LocalTheory.target (Locale.add_thmss target kind target_facts)
   165     |> ProofContext.note_thmss kind local_facts
   166   end;
   167 
   168 
   169 (* declare_const *)
   170 
   171 fun fork_mixfix (Target {is_locale, is_class, ...}) mx =
   172   if not is_locale then (NoSyn, NoSyn, mx)
   173   else if not is_class then (NoSyn, mx, NoSyn)
   174   else (mx, NoSyn, NoSyn);
   175 
   176 fun locale_const (Target {target, is_class, ...}) (prmode as (mode, _)) ((b, mx), rhs) phi =
   177   let
   178     val b' = Morphism.binding phi b;
   179     val rhs' = Morphism.term phi rhs;
   180     val arg = (b', Term.close_schematic_term rhs');
   181     val similar_body = Type.similar_types (rhs, rhs');
   182     (* FIXME workaround based on educated guess *)
   183     val prefix' = Binding.prefix_of b';
   184     val class_global = Binding.eq_name (b, b')
   185       andalso not (null prefix')
   186       andalso (fst o snd o split_last) prefix' = Class_Target.class_prefix target;
   187   in
   188     not (is_class andalso (similar_body orelse class_global)) ?
   189       (Context.mapping_result
   190         (Sign.add_abbrev PrintMode.internal [] arg)
   191         (ProofContext.add_abbrev PrintMode.internal [] arg)
   192       #-> (fn (lhs' as Const (d, _), _) =>
   193           similar_body ?
   194             (Context.mapping (Sign.revert_abbrev mode d) (ProofContext.revert_abbrev mode d) #>
   195              Morphism.form (ProofContext.target_notation true prmode [(lhs', mx)]))))
   196   end;
   197 
   198 fun syntax_error c = error ("Illegal mixfix syntax for overloaded constant " ^ quote c);
   199 
   200 fun declare_const (ta as Target {target, is_locale, is_class, ...}) depends ((b, T), mx) lthy =
   201   let
   202     val xs = filter depends (#1 (ProofContext.inferred_fixes (LocalTheory.target_of lthy)));
   203     val U = map #2 xs ---> T;
   204     val (mx1, mx2, mx3) = fork_mixfix ta mx;
   205     val declare_const =
   206       (case Class_Target.instantiation_param lthy b of
   207         SOME c' =>
   208           if mx3 <> NoSyn then syntax_error c'
   209           else LocalTheory.theory_result (AxClass.declare_overloaded (c', U))
   210             ##> Class_Target.confirm_declaration b
   211         | NONE =>
   212             (case Overloading.operation lthy b of
   213               SOME (c', _) =>
   214                 if mx3 <> NoSyn then syntax_error c'
   215                 else LocalTheory.theory_result (Overloading.declare (c', U))
   216                   ##> Overloading.confirm b
   217             | NONE => LocalTheory.theory_result (Sign.declare_const [] ((b, U), mx3))));
   218     val (const, lthy') = lthy |> declare_const;
   219     val t = Term.list_comb (const, map Free xs);
   220   in
   221     lthy'
   222     |> is_locale ? term_syntax ta (locale_const ta Syntax.mode_default ((b, mx2), t))
   223     |> is_class ? class_target ta (Class_Target.declare target [] ((b, mx1), t))
   224     |> LocalDefs.add_def ((b, NoSyn), t)
   225   end;
   226 
   227 
   228 (* abbrev *)
   229 
   230 fun abbrev (ta as Target {target, is_locale, is_class, ...}) prmode ((b, mx), t) lthy =
   231   let
   232     val thy_ctxt = ProofContext.init (ProofContext.theory_of lthy);
   233     val target_ctxt = LocalTheory.target_of lthy;
   234 
   235     val (mx1, mx2, mx3) = fork_mixfix ta mx;
   236     val t' = Assumption.export_term lthy target_ctxt t;
   237     val xs = map Free (rev (Variable.add_fixed target_ctxt t' []));
   238     val u = fold_rev lambda xs t';
   239     val global_rhs =
   240       singleton (Variable.export_terms (Variable.declare_term u target_ctxt) thy_ctxt) u;
   241   in
   242     lthy |>
   243      (if is_locale then
   244         LocalTheory.theory_result (Sign.add_abbrev PrintMode.internal [] (b, global_rhs))
   245         #-> (fn (lhs, _) =>
   246           let val lhs' = Term.list_comb (Logic.unvarify lhs, xs) in
   247             term_syntax ta (locale_const ta prmode ((b, mx2), lhs')) #>
   248             is_class ? class_target ta (Class_Target.abbrev target prmode [] ((b, mx1), t'))
   249           end)
   250       else
   251         LocalTheory.theory
   252           (Sign.add_abbrev (#1 prmode) [] (b, global_rhs) #-> (fn (lhs, _) =>
   253            Sign.notation true prmode [(lhs, mx3)])))
   254     |> ProofContext.add_abbrev PrintMode.internal [] (b, t) |> snd
   255     |> LocalDefs.fixed_abbrev ((b, NoSyn), t)
   256   end;
   257 
   258 
   259 (* define *)
   260 
   261 fun define ta kind ((b, mx), ((name, atts), rhs)) lthy =
   262   let
   263     val thy = ProofContext.theory_of lthy;
   264     val thy_ctxt = ProofContext.init thy;
   265 
   266     val name' = Thm.def_binding_optional b name;
   267     val (rhs', rhs_conv) =
   268       LocalDefs.export_cterm lthy thy_ctxt (Thm.cterm_of thy rhs) |>> Thm.term_of;
   269     val xs = Variable.add_fixed (LocalTheory.target_of lthy) rhs' [];
   270     val T = Term.fastype_of rhs;
   271 
   272     (*const*)
   273     val ((lhs, local_def), lthy2) = lthy |> declare_const ta (member (op =) xs) ((b, T), mx);
   274     val (_, lhs') = Logic.dest_equals (Thm.prop_of local_def);
   275 
   276     (*def*)
   277     val (global_def, lthy3) = lthy2
   278       |> LocalTheory.theory_result (case Overloading.operation lthy b of
   279           SOME (_, checked) =>
   280             Overloading.define checked name' ((fst o dest_Const) lhs', rhs')
   281         | NONE =>
   282             if is_none (Class_Target.instantiation_param lthy b)
   283             then Thm.add_def false false (name', Logic.mk_equals (lhs', rhs'))
   284             else AxClass.define_overloaded name' ((fst o dest_Const) lhs', rhs'));
   285     val def = LocalDefs.trans_terms lthy3
   286       [(*c == global.c xs*)     local_def,
   287        (*global.c xs == rhs'*)  global_def,
   288        (*rhs' == rhs*)          Thm.symmetric rhs_conv];
   289 
   290     (*note*)
   291     val ([(res_name, [res])], lthy4) = lthy3
   292       |> notes ta kind [((name', atts), [([def], [])])];
   293   in ((lhs, (res_name, res)), lthy4) end;
   294 
   295 
   296 (* init *)
   297 
   298 local
   299 
   300 fun init_target _ NONE = global_target
   301   | init_target thy (SOME target) = if Locale.defined thy (Locale.intern thy target)
   302       then make_target target true (Class_Target.is_class thy target) ([], [], []) []
   303       else error ("No such locale: " ^ quote target);
   304 
   305 fun init_ctxt (Target {target, is_locale, is_class, instantiation, overloading}) =
   306   if not (null (#1 instantiation)) then Class_Target.init_instantiation instantiation
   307   else if not (null overloading) then Overloading.init overloading
   308   else if not is_locale then ProofContext.init
   309   else if not is_class then Locale.init target
   310   else Class_Target.init target;
   311 
   312 fun init_lthy (ta as Target {target, instantiation, overloading, ...}) =
   313   Data.put ta #>
   314   LocalTheory.init (Long_Name.base_name target)
   315    {pretty = pretty ta,
   316     abbrev = abbrev ta,
   317     define = define ta,
   318     notes = notes ta,
   319     type_syntax = type_syntax ta,
   320     term_syntax = term_syntax ta,
   321     declaration = declaration ta,
   322     reinit = fn lthy => init_lthy_ctxt ta (ProofContext.theory_of lthy),
   323     exit = LocalTheory.target_of o
   324       (if not (null (#1 instantiation)) then Class_Target.conclude_instantiation
   325        else if not (null overloading) then Overloading.conclude
   326        else I)}
   327 and init_lthy_ctxt ta = init_lthy ta o init_ctxt ta;
   328 
   329 fun gen_overloading prep_const raw_ops thy =
   330   let
   331     val ctxt = ProofContext.init thy;
   332     val ops = raw_ops |> map (fn (name, const, checked) =>
   333       (name, Term.dest_Const (prep_const ctxt const), checked));
   334   in thy |> init_lthy_ctxt (make_target "" false false ([], [], []) ops) end;
   335 
   336 in
   337 
   338 fun init target thy = init_lthy_ctxt (init_target thy target) thy;
   339 fun begin target ctxt = init_lthy (init_target (ProofContext.theory_of ctxt) (SOME target)) ctxt;
   340 
   341 fun context "-" thy = init NONE thy
   342   | context target thy = init (SOME (Locale.intern thy target)) thy;
   343 
   344 fun instantiation arities = init_lthy_ctxt (make_target "" false false arities []);
   345 fun instantiation_cmd raw_arities thy =
   346   instantiation (Class_Target.read_multi_arity thy raw_arities) thy;
   347 
   348 val overloading = gen_overloading (fn ctxt => Syntax.check_term ctxt o Const);
   349 val overloading_cmd = gen_overloading Syntax.read_term;
   350 
   351 end;
   352 
   353 end;
   354