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