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