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