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