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