src/Pure/Isar/theory_target.ML
author wenzelm
Tue, 02 Sep 2008 22:20:21 +0200
changeset 28094 5f340fb49b90
parent 28084 a05ca48ef263
child 28115 cd0d170d4dc6
permissions -rw-r--r--
tuned;

(*  Title:      Pure/Isar/theory_target.ML
    ID:         $Id$
    Author:     Makarius

Common theory/locale/class/instantiation/overloading targets.
*)

signature THEORY_TARGET =
sig
  val peek: local_theory -> {target: string, is_locale: bool,
    is_class: bool, instantiation: string list * (string * sort) list * sort,
    overloading: (string * (string * typ) * bool) list}
  val init: string option -> theory -> local_theory
  val begin: string -> Proof.context -> local_theory
  val context: xstring -> theory -> local_theory
  val instantiation: string list * (string * sort) list * sort -> theory -> local_theory
  val overloading: (string * (string * typ) * bool) list -> theory -> local_theory
  val overloading_cmd: (string * string * bool) list -> theory -> local_theory
end;

structure TheoryTarget: THEORY_TARGET =
struct

(* context data *)

datatype target = Target of {target: string, is_locale: bool,
  is_class: bool, instantiation: string list * (string * sort) list * sort,
  overloading: (string * (string * typ) * bool) list};

fun make_target target is_locale is_class instantiation overloading =
  Target {target = target, is_locale = is_locale,
    is_class = is_class, instantiation = instantiation, overloading = overloading};

val global_target = make_target "" false false ([], [], []) [];

structure Data = ProofDataFun
(
  type T = target;
  fun init _ = global_target;
);

val peek = (fn Target args => args) o Data.get;


(* pretty *)

fun pretty_thy ctxt target is_locale is_class =
  let
    val thy = ProofContext.theory_of ctxt;
    val target_name = (if is_class then "class " else "locale ") ^ Locale.extern thy target;
    val fixes = map (fn (x, T) => (Name.binding x, SOME T, NoSyn))
      (#1 (ProofContext.inferred_fixes ctxt));
    val assumes = map (fn A => (Attrib.no_binding, [(Thm.term_of A, [])]))
      (Assumption.assms_of ctxt);
    val elems =
      (if null fixes then [] else [Element.Fixes fixes]) @
      (if null assumes then [] else [Element.Assumes assumes]);
  in
    if target = "" then []
    else if null elems then [Pretty.str target_name]
    else [Pretty.big_list (target_name ^ " =")
      (map (Pretty.chunks o Element.pretty_ctxt ctxt) elems)]
  end;

fun pretty (Target {target, is_locale, is_class, instantiation, overloading}) ctxt =
  Pretty.block [Pretty.str "theory", Pretty.brk 1,
      Pretty.str (Context.theory_name (ProofContext.theory_of ctxt))] ::
    (if not (null overloading) then [Overloading.pretty ctxt]
     else if not (null (#1 instantiation)) then [Class.pretty_instantiation ctxt]
     else pretty_thy ctxt target is_locale is_class);


(* target declarations *)

fun target_decl add (Target {target, is_class, ...}) d lthy =
  let
    val d' = Morphism.transform (LocalTheory.target_morphism lthy) d;
    val d0 = Morphism.form d';
  in
    if target = "" then
      lthy
      |> LocalTheory.theory (Context.theory_map d0)
      |> LocalTheory.target (Context.proof_map d0)
    else
      lthy
      |> LocalTheory.target (add target d')
      (*|> is_class ? LocalTheory.raw_theory (Class.declaration target d')*)
  end;

val type_syntax = target_decl Locale.add_type_syntax;
val term_syntax = target_decl Locale.add_term_syntax;
val declaration = target_decl Locale.add_declaration;

fun class_target (Target {target, ...}) f =
  LocalTheory.raw_theory f #>
  LocalTheory.target (Class.refresh_syntax target);


(* notes *)

fun import_export_proof ctxt (name, raw_th) =
  let
    val thy = ProofContext.theory_of ctxt;
    val thy_ctxt = ProofContext.init thy;
    val certT = Thm.ctyp_of thy;
    val cert = Thm.cterm_of thy;

    (*export assumes/defines*)
    val th = Goal.norm_result raw_th;
    val (defs, th') = LocalDefs.export ctxt thy_ctxt th;
    val concl_conv = MetaSimplifier.rewrite true defs (Thm.cprop_of th);
    val assms = map (MetaSimplifier.rewrite_rule defs o Thm.assume) (Assumption.assms_of ctxt);
    val nprems = Thm.nprems_of th' - Thm.nprems_of th;

    (*export fixes*)
    val tfrees = map TFree (Thm.fold_terms Term.add_tfrees th' []);
    val frees = map Free (Thm.fold_terms Term.add_frees th' []);
    val (th'' :: vs) = (th' :: map (Drule.mk_term o cert) (map Logic.mk_type tfrees @ frees))
      |> Variable.export ctxt thy_ctxt
      |> Drule.zero_var_indexes_list;

    (*thm definition*)
    val result = PureThy.name_thm true true Position.none name th'';

    (*import fixes*)
    val (tvars, vars) =
      chop (length tfrees) (map (Thm.term_of o Drule.dest_term) vs)
      |>> map Logic.dest_type;

    val instT = map_filter (fn (TVar v, T) => SOME (v, T) | _ => NONE) (tvars ~~ tfrees);
    val inst = filter (is_Var o fst) (vars ~~ frees);
    val cinstT = map (pairself certT o apfst TVar) instT;
    val cinst = map (pairself (cert o Term.map_types (TermSubst.instantiateT instT))) inst;
    val result' = Thm.instantiate (cinstT, cinst) result;

    (*import assumes/defines*)
    val assm_tac = FIRST' (map (fn assm => Tactic.compose_tac (false, assm, 0)) assms);
    val result'' =
      (case SINGLE (Seq.INTERVAL assm_tac 1 nprems) result' of
        NONE => raise THM ("Failed to re-import result", 0, [result'])
      | SOME res => LocalDefs.trans_props ctxt [res, Thm.symmetric concl_conv])
      |> Goal.norm_result
      |> PureThy.name_thm false false Position.none name;

  in (result'', result) end;

fun note_local kind facts ctxt =
  ctxt
  |> ProofContext.qualified_names
  |> ProofContext.note_thmss_i kind facts
  ||> ProofContext.restore_naming ctxt;

fun notes (Target {target, is_locale, is_class, ...}) kind facts lthy =
  let
    val thy = ProofContext.theory_of lthy;
    val full = LocalTheory.full_name lthy;

    val facts' = facts
      |> map (fn (a, bs) =>
        (a, PureThy.burrow_fact (PureThy.name_multi (full (Name.name_of (fst a)))) bs))
      |> PureThy.map_facts (import_export_proof lthy);
    val local_facts = PureThy.map_facts #1 facts'
      |> Attrib.map_facts (Attrib.attribute_i thy);
    val target_facts = PureThy.map_facts #1 facts'
      |> is_locale ? Element.facts_map (Element.morph_ctxt (LocalTheory.target_morphism lthy));
    val global_facts = PureThy.map_facts #2 facts'
      |> Attrib.map_facts (if is_locale then K I else Attrib.attribute_i thy);
  in
    lthy |> LocalTheory.theory
      (Sign.qualified_names
        #> PureThy.note_thmss_grouped kind (LocalTheory.group_of lthy) global_facts #> snd
        #> Sign.restore_naming thy)
    |> not is_locale ? LocalTheory.target (note_local kind global_facts #> snd)
    |> is_locale ? LocalTheory.target (Locale.add_thmss target kind target_facts)
    (*|> is_class ? LocalTheory.raw_theory (Class.note target kind target_facts #> snd)*)
    |> note_local kind local_facts
  end;


(* declare_const *)

fun fork_mixfix (Target {is_locale, is_class, ...}) mx =
  if not is_locale then (NoSyn, NoSyn, mx)
  else if not is_class then (NoSyn, mx, NoSyn)
  else (mx, NoSyn, NoSyn);

fun locale_const (Target {target, is_class, ...}) (prmode as (mode, _)) tags ((c, mx), rhs) phi =
  let
    val c' = Morphism.name phi c;
    val rhs' = Morphism.term phi rhs;
    val name = Name.name_of c;
    val name' = Name.name_of c'
    val legacy_arg = (name', Term.close_schematic_term (Logic.legacy_varify rhs'));
    val arg = (name', Term.close_schematic_term rhs');
    val similar_body = Type.similar_types (rhs, rhs');
    (* FIXME workaround based on educated guess *)
    val class_global = name' = NameSpace.qualified (Class.class_prefix target) name;
  in
    not (is_class andalso (similar_body orelse class_global)) ?
      (Context.mapping_result
        (Sign.add_abbrev PrintMode.internal tags legacy_arg)
        (ProofContext.add_abbrev PrintMode.internal tags arg)
      #-> (fn (lhs' as Const (d, _), _) =>
          similar_body ?
            (Context.mapping (Sign.revert_abbrev mode d) (ProofContext.revert_abbrev mode d) #>
             Morphism.form (ProofContext.target_notation true prmode [(lhs', mx)]))))
  end;

fun declare_const (ta as Target {target, is_locale, is_class, ...}) depends ((b, T), mx) lthy =
  let
    val c = Name.name_of b;
    val tags = LocalTheory.group_position_of lthy;
    val xs = filter depends (#1 (ProofContext.inferred_fixes (LocalTheory.target_of lthy)));
    val U = map #2 xs ---> T;
    val (mx1, mx2, mx3) = fork_mixfix ta mx;
    fun syntax_error c = error ("Illegal mixfix syntax for overloaded constant " ^ quote c);
    val declare_const =
      (case Class.instantiation_param lthy c of
        SOME c' =>
          if mx3 <> NoSyn then syntax_error c'
          else LocalTheory.theory_result (AxClass.declare_overloaded (c', U))
            ##> Class.confirm_declaration c
        | NONE =>
            (case Overloading.operation lthy c of
              SOME (c', _) =>
                if mx3 <> NoSyn then syntax_error c'
                else LocalTheory.theory_result (Overloading.declare (c', U))
                  ##> Overloading.confirm c
            | NONE => LocalTheory.theory_result (Sign.declare_const tags (c, U, mx3))));
    val (const, lthy') = lthy |> declare_const;
    val t = Term.list_comb (const, map Free xs);
  in
    lthy'
    |> is_locale ? term_syntax ta (locale_const ta Syntax.mode_default tags ((b, mx2), t))
    |> is_class ? class_target ta (Class.declare target tags ((c, mx1), t))
    |> LocalDefs.add_def ((b, NoSyn), t)
  end;


(* abbrev *)

fun abbrev (ta as Target {target, is_locale, is_class, ...}) prmode ((b, mx), t) lthy =
  let
    val c = Name.name_of b;
    val tags = LocalTheory.group_position_of lthy;
    val thy_ctxt = ProofContext.init (ProofContext.theory_of lthy);
    val target_ctxt = LocalTheory.target_of lthy;

    val (mx1, mx2, mx3) = fork_mixfix ta mx;
    val t' = Assumption.export_term lthy target_ctxt t;
    val xs = map Free (rev (Variable.add_fixed target_ctxt t' []));
    val u = fold_rev lambda xs t';
    val global_rhs =
      singleton (Variable.export_terms (Variable.declare_term u target_ctxt) thy_ctxt) u;
  in
    lthy |>
     (if is_locale then
        LocalTheory.theory_result (Sign.add_abbrev PrintMode.internal tags (c, global_rhs))
        #-> (fn (lhs, _) =>
          let val lhs' = Term.list_comb (Logic.unvarify lhs, xs) in
            term_syntax ta (locale_const ta prmode tags ((b, mx2), lhs')) #>
            is_class ? class_target ta (Class.abbrev target prmode tags ((c, mx1), t'))
          end)
      else
        LocalTheory.theory
          (Sign.add_abbrev (#1 prmode) tags (c, global_rhs) #-> (fn (lhs, _) =>
           Sign.notation true prmode [(lhs, mx3)])))
    |> ProofContext.add_abbrev PrintMode.internal tags (c, t) |> snd
    |> LocalDefs.fixed_abbrev ((b, NoSyn), t)
  end;


(* define *)

fun define (ta as Target {target, is_locale, is_class, ...})
    kind ((b, mx), ((name, atts), rhs)) lthy =
  let
    val thy = ProofContext.theory_of lthy;
    val thy_ctxt = ProofContext.init thy;

    val c = Name.name_of b;
    val name' = Name.map_name (Thm.def_name_optional c) name;
    val (rhs', rhs_conv) =
      LocalDefs.export_cterm lthy thy_ctxt (Thm.cterm_of thy rhs) |>> Thm.term_of;
    val xs = Variable.add_fixed (LocalTheory.target_of lthy) rhs' [];
    val T = Term.fastype_of rhs;

    (*const*)
    val ((lhs, local_def), lthy2) = lthy |> declare_const ta (member (op =) xs) ((b, T), mx);
    val (_, lhs') = Logic.dest_equals (Thm.prop_of local_def);

    (*def*)
    val define_const =
      (case Overloading.operation lthy c of
        SOME (_, checked) =>
          (fn name => fn (Const (c, _), rhs) => Overloading.define checked name (c, rhs))
      | NONE =>
          if is_none (Class.instantiation_param lthy c)
          then (fn name => fn eq => Thm.add_def false false (name, Logic.mk_equals eq))
          else (fn name => fn (Const (c, _), rhs) => AxClass.define_overloaded name (c, rhs)));
    val (global_def, lthy3) = lthy2
      |> LocalTheory.theory_result (define_const (Name.name_of name') (lhs', rhs'));
    val def = LocalDefs.trans_terms lthy3
      [(*c == global.c xs*)     local_def,
       (*global.c xs == rhs'*)  global_def,
       (*rhs' == rhs*)          Thm.symmetric rhs_conv];

    (*note*)
    val ([(res_name, [res])], lthy4) = lthy3
      |> notes ta kind [((name', atts), [([def], [])])];
  in ((lhs, (res_name, res)), lthy4) end;


(* axioms *)

fun axioms ta kind (vars, specs) lthy =
  let
    val thy_ctxt = ProofContext.init (ProofContext.theory_of lthy);
    val expanded_props = map (Assumption.export_term lthy thy_ctxt) (maps snd specs);
    val xs = fold Term.add_frees expanded_props [];

    (*consts*)
    val (consts, lthy') = fold_map (declare_const ta (member (op =) xs)) vars lthy;
    val global_consts = map (Term.dest_Const o Term.head_of o Thm.term_of o Thm.rhs_of o #2) consts;

    (*axioms*)
    val hyps = map Thm.term_of (Assumption.assms_of lthy');
    fun axiom ((name, atts), props) thy = thy
      |> fold_map (Thm.add_axiom hyps) (PureThy.name_multi (Name.name_of name) props)
      |-> (fn ths => pair ((name, atts), [(ths, [])]));
  in
    lthy'
    |> fold Variable.declare_term expanded_props
    |> LocalTheory.theory (fold (fn c => Theory.add_deps "" c []) global_consts)
    |> LocalTheory.theory_result (fold_map axiom specs)
    |-> notes ta kind
    |>> pair (map #1 consts)
  end;


(* init *)

local

fun init_target _ NONE = global_target
  | init_target thy (SOME target) =
      make_target target true (Class.is_class thy target) ([], [], []) [];

fun init_ctxt (Target {target, is_locale, is_class, instantiation, overloading}) =
  if not (null (#1 instantiation)) then Class.init_instantiation instantiation
  else if not (null overloading) then Overloading.init overloading
  else if not is_locale then ProofContext.init
  else if not is_class then Locale.init target
  else Class.init target;

fun init_lthy (ta as Target {target, instantiation, overloading, ...}) =
  Data.put ta #>
  LocalTheory.init (NameSpace.base target)
   {pretty = pretty ta,
    axioms = axioms ta,
    abbrev = abbrev ta,
    define = define ta,
    notes = notes ta,
    type_syntax = type_syntax ta,
    term_syntax = term_syntax ta,
    declaration = declaration ta,
    reinit = fn lthy => init_lthy_ctxt ta (ProofContext.theory_of lthy),
    exit = LocalTheory.target_of o
      (if not (null (#1 instantiation)) then Class.conclude_instantiation
       else if not (null overloading) then Overloading.conclude
       else I)}
and init_lthy_ctxt ta = init_lthy ta o init_ctxt ta;

fun gen_overloading prep_const raw_ops thy =
  let
    val ctxt = ProofContext.init thy;
    val ops = raw_ops |> map (fn (name, const, checked) =>
      (name, Term.dest_Const (prep_const ctxt const), checked));
  in thy |> init_lthy_ctxt (make_target "" false false ([], [], []) ops) end;

in

fun init target thy = init_lthy_ctxt (init_target thy target) thy;
fun begin target ctxt = init_lthy (init_target (ProofContext.theory_of ctxt) (SOME target)) ctxt;

fun context "-" thy = init NONE thy
  | context target thy = init (SOME (Locale.intern thy target)) thy;

fun instantiation arities = init_lthy_ctxt (make_target "" false false arities []);

val overloading = gen_overloading (fn ctxt => Syntax.check_term ctxt o Const);
val overloading_cmd = gen_overloading Syntax.read_term;

end;

end;