author ballarin
Wed, 19 Nov 2008 16:58:33 +0100
changeset 28849 9458d7a6388a
parent 28834 66d31ca2c5af
child 28861 f53abb0733ee
permissions -rw-r--r--
Enable switching to new locales during session.

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

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

signature THEORY_TARGET =
  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

structure TheoryTarget: THEORY_TARGET =

(* new locales *)

fun locale_extern x = if !new_locales then NewLocale.extern x else Locale.extern x;
fun locale_add_type_syntax x = if !new_locales then NewLocale.add_type_syntax x else Locale.add_type_syntax x;
fun locale_add_term_syntax x = if !new_locales then NewLocale.add_term_syntax x else Locale.add_term_syntax x;
fun locale_add_declaration x = if !new_locales then NewLocale.add_declaration x else Locale.add_declaration x;
fun locale_add_thmss x = if !new_locales then NewLocale.add_thmss x else Locale.add_thmss x;
fun locale_init x = if !new_locales then NewLocale.init x else Locale.init x;
fun locale_intern x = if !new_locales then NewLocale.intern x else Locale.intern x;

(* 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 =
    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]);
    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)]

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 =
    val d' = Morphism.transform (LocalTheory.target_morphism lthy) d;
    val d0 = Morphism.form d';
    if target = "" then
      |> LocalTheory.theory (Context.theory_map d0)
      |> (Context.proof_map d0)
      |> (add target d')

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 #> (Class.refresh_syntax target);

(* notes *)

fun import_export_proof ctxt (name, raw_th) =
    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 =
  |> ProofContext.qualified_names
  |> ProofContext.note_thmss_i kind facts
  ||> ProofContext.restore_naming ctxt;

fun notes (Target {target, is_locale, is_class, ...}) kind facts lthy =
    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);
    lthy |> LocalTheory.theory
        #> PureThy.note_thmss_grouped kind (LocalTheory.group_of lthy) global_facts #> snd
        #> Sign.restore_naming thy)
    |> not is_locale ? (note_local kind global_facts #> snd)
    |> is_locale ? (locale_add_thmss target kind target_facts)
    |> note_local kind local_facts

(* 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 =
    val c' = phi c;
    val rhs' = Morphism.term phi rhs;
    val name' = Name.name_with_prefix 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.name_of c = Name.name_of c'
      andalso not (null (Name.prefix_of c'))
      andalso (fst o snd o split_last) (Name.prefix_of c') = Class.class_prefix target;
    not (is_class andalso (similar_body orelse class_global)) ?
        (fn thy => thy |> 
          |> Sign.add_abbrev PrintMode.internal tags legacy_arg
          ||> Sign.restore_naming thy)
        (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)]))))

fun declare_const (ta as Target {target, is_locale, is_class, ...}) depends ((b, T), mx) lthy =
    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 ((b, U), mx3))));
    val (const, lthy') = lthy |> declare_const;
    val t = Term.list_comb (const, map Free xs);
    |> 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)

(* abbrev *)

fun abbrev (ta as Target {target, is_locale, is_class, ...}) prmode ((b, mx), t) lthy =
    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;
    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'))
          (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)

(* define *)

fun define (ta as Target {target, is_locale, is_class, ...})
    kind ((b, mx), ((name, atts), rhs)) lthy =
    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;

    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);

    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];

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

(* init *)


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,
    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 =
    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;


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;