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