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