theory Fv
imports "Nominal2_Atoms" "Abs" "Perm" "Rsp"
begin

(* Bindings are given as a list which has a length being equal
   to the length of the number of constructors.

   Each element is a list whose length is equal to the number
   of arguents.

   Every element specifies bindings of this argument given as
   a tuple: function, bound argument.

  Eg:
nominal_datatype

   C1
 | C2 x y z bind x in z
 | C3 x y z bind f x in z bind g y in z

yields:
[
 [],
 [[], [], [(NONE, 0)]],
 [[], [], [(SOME (Const f), 0), (Some (Const g), 1)]]]

A SOME binding has to have a function returning an atom set,
and a NONE binding has to be on an argument that is an atom
or an atom set.

How the procedure works:
  For each of the defined datatypes,
  For each of the constructors,
  It creates a union of free variables for each argument.

  For an argument the free variables are the variables minus
  bound variables.

  The variables are:
    For an atom, a singleton set with the atom itself.
    For an atom set, the atom set itself.
    For a recursive argument, the appropriate fv function applied to it.
    (* TODO: This one is not implemented *)
    For other arguments it should be an appropriate fv function stored
      in the database.
  The bound variables are a union of results of all bindings that
  involve the given argument. For a paricular binding the result is:
    For a function applied to an argument this function with the argument.
    For an atom, a singleton set with the atom itself.
    For an atom set, the atom set itself.
    For a recursive argument, the appropriate fv function applied to it.
    (* TODO: This one is not implemented *)
    For other arguments it should be an appropriate fv function stored
      in the database.
*)

ML {*
fun map2i _ [] [] = []
  | map2i f (x :: xs) (y :: ys) = f x y :: map2i f xs ys
  | map2i f (x :: xs) [] = f x [] :: map2i f xs []
  | map2i _ _ _ = raise UnequalLengths;
*}

ML {*
  open Datatype_Aux; (* typ_of_dtyp, DtRec, ... *);
  (* TODO: It is the same as one in 'nominal_atoms' *)
  fun mk_atom ty = Const (@{const_name atom}, ty --> @{typ atom});
  val noatoms = @{term "{} :: atom set"};
  fun mk_single_atom x = HOLogic.mk_set @{typ atom} [mk_atom (type_of x) $ x];
  fun mk_union sets =
    fold (fn a => fn b =>
      if a = noatoms then b else
      if b = noatoms then a else
      if a = b then a else
      HOLogic.mk_binop @{const_name sup} (a, b)) (rev sets) noatoms;
  val mk_inter = foldr1 (HOLogic.mk_binop @{const_name inf})
  fun mk_conjl props =
    fold (fn a => fn b =>
      if a = @{term True} then b else
      if b = @{term True} then a else
      HOLogic.mk_conj (a, b)) props @{term True};
  fun mk_diff a b =
    if b = noatoms then a else
    if b = a then noatoms else
    HOLogic.mk_binop @{const_name minus} (a, b);
  fun mk_atoms t =
    let
      val ty = fastype_of t;
      val atom_ty = HOLogic.dest_setT ty --> @{typ atom};
      val img_ty = atom_ty --> ty --> @{typ "atom set"};
    in
      (Const (@{const_name image}, img_ty) $ Const (@{const_name atom}, atom_ty) $ t)
    end;
  (* Copy from Term *)
  fun is_funtype (Type ("fun", [_, _])) = true
    | is_funtype _ = false;
  (* Similar to one in USyntax *)
  fun mk_pair (fst, snd) =
    let val ty1 = fastype_of fst
      val ty2 = fastype_of snd
      val c = HOLogic.pair_const ty1 ty2
    in c $ fst $ snd
    end;

*}

ML {* fun add_perm (p1, p2) = Const(@{const_name plus}, @{typ "perm \<Rightarrow> perm \<Rightarrow> perm"}) $ p1 $ p2 *}

(* TODO: Notice datatypes without bindings and replace alpha with equality *)
ML {*
fun define_fv_alpha (dt_info : Datatype_Aux.info) bindsall lthy =
let
  val thy = ProofContext.theory_of lthy;
  val {descr, sorts, ...} = dt_info;
  fun nth_dtyp i = typ_of_dtyp descr sorts (DtRec i);
  val fv_names = Datatype_Prop.indexify_names (map (fn (i, _) =>
    "fv_" ^ name_of_typ (nth_dtyp i)) descr);
  val fv_types = map (fn (i, _) => nth_dtyp i --> @{typ "atom set"}) descr;
  val fv_frees = map Free (fv_names ~~ fv_types);
  val alpha_names = Datatype_Prop.indexify_names (map (fn (i, _) =>
    "alpha_" ^ name_of_typ (nth_dtyp i)) descr);
  val alpha_types = map (fn (i, _) => nth_dtyp i --> nth_dtyp i --> @{typ bool}) descr;
  val alpha_frees = map Free (alpha_names ~~ alpha_types);
  fun fv_alpha_constr ith_dtyp (cname, dts) bindcs =
    let
      val Ts = map (typ_of_dtyp descr sorts) dts;
      val bindslen = length bindcs
      val pi_strs_same = replicate bindslen "pi"
      val pi_strs = Name.variant_list [] pi_strs_same;
      val pis = map (fn ps => Free (ps, @{typ perm})) pi_strs;
      val bind_pis = bindcs ~~ pis;
      val names = Name.variant_list pi_strs (Datatype_Prop.make_tnames Ts);
      val args = map Free (names ~~ Ts);
      val names2 = Name.variant_list (pi_strs @ names) (Datatype_Prop.make_tnames Ts);
      val args2 = map Free (names2 ~~ Ts);
      val c = Const (cname, Ts ---> (nth_dtyp ith_dtyp));
      val fv_c = nth fv_frees ith_dtyp;
      val alpha = nth alpha_frees ith_dtyp;
      val arg_nos = 0 upto (length dts - 1)
      fun fv_bind args (NONE, i, _) =
            if is_rec_type (nth dts i) then (nth fv_frees (body_index (nth dts i))) $ (nth args i) else
            (* TODO we assume that all can be 'atomized' *)
            if (is_funtype o fastype_of) (nth args i) then mk_atoms (nth args i) else
            mk_single_atom (nth args i)
        | fv_bind args (SOME f, i, _) = f $ (nth args i);
      fun fv_binds args relevant = mk_union (map (fv_bind args) relevant)
      fun fv_arg ((dt, x), arg_no) =
        let
          val arg =
            if is_rec_type dt then nth fv_frees (body_index dt) $ x else
            (* TODO: we just assume everything can be 'atomized' *)
            if (is_funtype o fastype_of) x then mk_atoms x else
            HOLogic.mk_set @{typ atom} [mk_atom (fastype_of x) $ x];
          (* If i = j then we generate it only once *)
          val relevant = filter (fn (_, i, j) => ((i = arg_no) orelse (j = arg_no))) bindcs;
          val sub = fv_binds args relevant
        in
          mk_diff arg sub
        end;
      val fv_eq = HOLogic.mk_Trueprop (HOLogic.mk_eq
        (fv_c $ list_comb (c, args), mk_union (map fv_arg  (dts ~~ args ~~ arg_nos))))
      val alpha_rhs =
        HOLogic.mk_Trueprop (alpha $ (list_comb (c, args)) $ (list_comb (c, args2)));
      fun alpha_arg ((dt, arg_no), (arg, arg2)) =
        let
          val relevant = filter (fn ((_, i, j), _) => i = arg_no orelse j = arg_no) bind_pis;
        in
          if relevant = [] then (
            if is_rec_type dt then (nth alpha_frees (body_index dt) $ arg $ arg2)
            else (HOLogic.mk_eq (arg, arg2)))
          else
            if is_rec_type dt then let
              (* THE HARD CASE *)
              val (rbinds, rpis) = split_list relevant
              val lhs_binds = fv_binds args rbinds
              val lhs = mk_pair (lhs_binds, arg);
              val rhs_binds = fv_binds args2 rbinds;
              val rhs = mk_pair (rhs_binds, arg2);
              val alpha = nth alpha_frees (body_index dt);
              val fv = nth fv_frees (body_index dt);
              val pi = foldr1 add_perm rpis;
              val alpha_gen_pre = Const (@{const_name alpha_gen}, dummyT) $ lhs $ alpha $ fv $ pi $ rhs;
              val alpha_gen = Syntax.check_term lthy alpha_gen_pre
              val pi_supps = map ((curry op $) @{term "supp :: perm \<Rightarrow> atom set"}) rpis;
              val pi_supps_eq = HOLogic.mk_eq (mk_inter pi_supps, @{term "{} :: atom set"})
            in
              (*if length pi_supps > 1 then
                HOLogic.mk_conj (alpha_gen, pi_supps_eq) else*) alpha_gen
            (* TODO Add some test that is makes sense *)
            end else @{term "True"}
        end
      val alphas = map alpha_arg (dts ~~ arg_nos ~~ (args ~~ args2))
      val alpha_lhss = mk_conjl alphas
      val alpha_lhss_ex =
        fold (fn pi_str => fn t => HOLogic.mk_exists (pi_str, @{typ perm}, t)) pi_strs alpha_lhss
      val alpha_eq = Logic.mk_implies (HOLogic.mk_Trueprop alpha_lhss_ex, alpha_rhs)
    in
      (fv_eq, alpha_eq)
    end;
  fun fv_alpha_eq (i, (_, _, constrs)) binds = map2i (fv_alpha_constr i) constrs binds;
  val (fv_eqs, alpha_eqs) = split_list (flat (map2i fv_alpha_eq descr bindsall))
  val add_binds = map (fn x => (Attrib.empty_binding, x))
  val (fvs, lthy') = (Primrec.add_primrec
    (map (fn s => (Binding.name s, NONE, NoSyn)) fv_names) (add_binds fv_eqs) lthy)
  val (alphas, lthy'') = (Inductive.add_inductive_i
     {quiet_mode = true, verbose = false, alt_name = Binding.empty,
      coind = false, no_elim = false, no_ind = false, skip_mono = true, fork_mono = false}
     (map2 (fn x => fn y => ((Binding.name x, y), NoSyn)) alpha_names alpha_types) []
     (add_binds alpha_eqs) [] lthy')
in
  ((fvs, alphas), lthy'')
end
*}

(* tests
atom_decl name

datatype ty =
  Var "name set"

ML {* Syntax.check_term @{context} (mk_atoms @{term "a :: name set"}) *}

local_setup {* define_fv_alpha "Fv.ty" [[[[]]]] *}
print_theorems


datatype rtrm1 =
  rVr1 "name"
| rAp1 "rtrm1" "rtrm1"
| rLm1 "name" "rtrm1"        --"name is bound in trm1"
| rLt1 "bp" "rtrm1" "rtrm1"   --"all variables in bp are bound in the 2nd trm1"
and bp =
  BUnit
| BVr "name"
| BPr "bp" "bp"

(* to be given by the user *)

primrec 
  bv1
where
  "bv1 (BUnit) = {}"
| "bv1 (BVr x) = {atom x}"
| "bv1 (BPr bp1 bp2) = (bv1 bp1) \<union> (bv1 bp1)"

setup {* snd o define_raw_perms ["rtrm1", "bp"] ["Fv.rtrm1", "Fv.bp"] *}

local_setup {* define_fv_alpha "Fv.rtrm1"
  [[[[]], [[], []], [[(NONE, 0)], [(NONE, 0)]], [[(SOME @{term bv1}, 0)], [], [(SOME @{term bv1}, 0)]]],
   [[], [[]], [[], []]]] *}
print_theorems
*)


ML {*
fun alpha_inj_tac dist_inj intrs elims =
  SOLVED' (asm_full_simp_tac (HOL_ss addsimps intrs)) ORELSE'
  (rtac @{thm iffI} THEN' RANGE [
     (eresolve_tac elims THEN_ALL_NEW
       asm_full_simp_tac (HOL_ss addsimps dist_inj)
     ),
     asm_full_simp_tac (HOL_ss addsimps intrs)])
*}

ML {*
fun build_alpha_inj_gl thm =
  let
    val prop = prop_of thm;
    val concl = HOLogic.dest_Trueprop (Logic.strip_imp_concl prop);
    val hyps = map HOLogic.dest_Trueprop (Logic.strip_imp_prems prop);
    fun list_conj l = foldr1 HOLogic.mk_conj l;
  in
    if hyps = [] then concl
    else HOLogic.mk_eq (concl, list_conj hyps)
  end;
*}

ML {*
fun build_alpha_inj intrs dist_inj elims ctxt =
let
  val ((_, thms_imp), ctxt') = Variable.import false intrs ctxt;
  val gls = map (HOLogic.mk_Trueprop o build_alpha_inj_gl) thms_imp;
  fun tac _ = alpha_inj_tac dist_inj intrs elims 1;
  val thms = map (fn gl => Goal.prove ctxt' [] [] gl tac) gls;
in
  Variable.export ctxt' ctxt thms
end
*}

ML {*
fun build_alpha_refl_gl alphas (x, y, z) =
let
  fun build_alpha alpha =
    let
      val ty = domain_type (fastype_of alpha);
      val var = Free(x, ty);
      val var2 = Free(y, ty);
      val var3 = Free(z, ty);
      val symp = HOLogic.mk_imp (alpha $ var $ var2, alpha $ var2 $ var);
      val transp = HOLogic.mk_imp (alpha $ var $ var2,
        HOLogic.mk_all (z, ty,
          HOLogic.mk_imp (alpha $ var2 $ var3, alpha $ var $ var3)))
    in
      ((alpha $ var $ var), (symp, transp))
    end;
  val (refl_eqs, eqs) = split_list (map build_alpha alphas)
  val (sym_eqs, trans_eqs) = split_list eqs
  fun conj l = @{term Trueprop} $ foldr1 HOLogic.mk_conj l
in
  (conj refl_eqs, (conj sym_eqs, conj trans_eqs))
end
*}

ML {*
fun reflp_tac induct inj ctxt =
  rtac induct THEN_ALL_NEW
  simp_tac ((mk_minimal_ss ctxt) addsimps inj) THEN_ALL_NEW
  split_conjs THEN_ALL_NEW REPEAT o rtac @{thm exI[of _ "0 :: perm"]}
  THEN_ALL_NEW split_conjs THEN_ALL_NEW asm_full_simp_tac (HOL_ss addsimps
     @{thms alpha_gen fresh_star_def fresh_zero_perm permute_zero ball_triv
       add_0_left supp_zero_perm Int_empty_left})
*}


lemma exi_neg: "\<exists>(pi :: perm). P pi \<Longrightarrow> (\<And>(p :: perm). P p \<Longrightarrow> Q (- p)) \<Longrightarrow> \<exists>pi. Q pi"
apply (erule exE)
apply (rule_tac x="-pi" in exI)
by auto

ML {*
fun symp_tac induct inj eqvt ctxt =
  ind_tac induct THEN_ALL_NEW
  simp_tac ((mk_minimal_ss ctxt) addsimps inj) THEN_ALL_NEW split_conjs
  THEN_ALL_NEW
  REPEAT o etac @{thm exi_neg}
  THEN_ALL_NEW
  split_conjs THEN_ALL_NEW
  asm_full_simp_tac (HOL_ss addsimps @{thms supp_minus_perm minus_add[symmetric]}) THEN_ALL_NEW
  (rtac @{thm alpha_gen_compose_sym} THEN' RANGE [
    (asm_full_simp_tac (HOL_ss addsimps @{thms plus_perm_eq})),
    (asm_full_simp_tac (HOL_ss addsimps (eqvt @ all_eqvts ctxt)))
  ])
*}

ML {*
fun imp_elim_tac case_rules =
  Subgoal.FOCUS (fn {concl, context, ...} =>
    case term_of concl of
      _ $ (_ $ asm $ _) =>
        let
          fun filter_fn case_rule = (
            case Logic.strip_assums_hyp (prop_of case_rule) of
              ((_ $ asmc) :: _) =>
                let
                  val thy = ProofContext.theory_of context
                in
                  Pattern.matches thy (asmc, asm)
                end
            | _ => false)
          val matching_rules = filter filter_fn case_rules
        in
         (rtac impI THEN' rotate_tac (~1) THEN' eresolve_tac matching_rules) 1
        end
    | _ => no_tac
  )
*}


lemma exi_sum: "\<exists>(pi :: perm). P pi \<Longrightarrow> \<exists>(pi :: perm). Q pi \<Longrightarrow> (\<And>(p :: perm) (pi :: perm). P p \<Longrightarrow> Q pi \<Longrightarrow> R (pi + p)) \<Longrightarrow> \<exists>pi. R pi"
apply (erule exE)+
apply (rule_tac x="pia + pi" in exI)
by auto

ML {*
fun is_ex (Const ("Ex", _) $ Abs _) = true
  | is_ex _ = false;
*}

ML {*
fun eetac rule = Subgoal.FOCUS_PARAMS 
  (fn (focus) =>
     let
       val concl = #concl focus
       val prems = Logic.strip_imp_prems (term_of concl)
       val exs = filter (fn x => is_ex (HOLogic.dest_Trueprop x)) prems
       val cexs = map (SOME o (cterm_of (ProofContext.theory_of (#context focus)))) exs
       val thins = map (fn cex => Drule.instantiate' [] [cex] Drule.thin_rl) cexs
     in
     (etac rule THEN' RANGE[
        atac,
        eresolve_tac thins
     ]) 1
     end
  )
*}

ML {*
fun transp_tac ctxt induct alpha_inj term_inj distinct cases eqvt =
  ind_tac induct THEN_ALL_NEW
  (TRY o rtac allI THEN' imp_elim_tac cases ctxt) THEN_ALL_NEW
  asm_full_simp_tac ((mk_minimal_ss ctxt) addsimps alpha_inj) THEN_ALL_NEW
  split_conjs THEN_ALL_NEW REPEAT o (eetac @{thm exi_sum} ctxt) THEN_ALL_NEW split_conjs
  THEN_ALL_NEW (asm_full_simp_tac (HOL_ss addsimps (term_inj @ distinct)))
  THEN_ALL_NEW split_conjs THEN_ALL_NEW
  TRY o (etac @{thm alpha_gen_compose_trans} THEN' RANGE[atac]) THEN_ALL_NEW
  (asm_full_simp_tac (HOL_ss addsimps (all_eqvts ctxt @ eqvt @ term_inj @ distinct)))
*}

lemma transp_aux:
  "(\<And>xa ya. R xa ya \<longrightarrow> (\<forall>z. R ya z \<longrightarrow> R xa z)) \<Longrightarrow> transp R"
  unfolding transp_def
  by blast

ML {*
fun equivp_tac reflps symps transps =
  simp_tac (HOL_ss addsimps @{thms equivp_reflp_symp_transp reflp_def symp_def})
  THEN' rtac conjI THEN' rtac allI THEN'
  resolve_tac reflps THEN'
  rtac conjI THEN' rtac allI THEN' rtac allI THEN'
  resolve_tac symps THEN'
  rtac @{thm transp_aux} THEN' resolve_tac transps
*}

ML {*
fun build_equivps alphas term_induct alpha_induct term_inj alpha_inj distinct cases eqvt ctxt =
let
  val ([x, y, z], ctxt') = Variable.variant_fixes ["x","y","z"] ctxt;
  val (reflg, (symg, transg)) = build_alpha_refl_gl alphas (x, y, z)
  fun reflp_tac' _ = reflp_tac term_induct alpha_inj ctxt 1;
  fun symp_tac' _ = symp_tac alpha_induct alpha_inj eqvt ctxt 1;
  fun transp_tac' _ = transp_tac ctxt alpha_induct alpha_inj term_inj distinct cases eqvt 1;
  val reflt = Goal.prove ctxt' [] [] reflg reflp_tac';
  val symt = Goal.prove ctxt' [] [] symg symp_tac';
  val transt = Goal.prove ctxt' [] [] transg transp_tac';
  val [refltg, symtg, transtg] = Variable.export ctxt' ctxt [reflt, symt, transt]
  val reflts = HOLogic.conj_elims refltg
  val symts = HOLogic.conj_elims symtg
  val transts = HOLogic.conj_elims transtg
  fun equivp alpha =
    let
      val equivp = Const (@{const_name equivp}, fastype_of alpha --> @{typ bool})
      val goal = @{term Trueprop} $ (equivp $ alpha)
      fun tac _ = equivp_tac reflts symts transts 1
    in
      Goal.prove ctxt [] [] goal tac
    end
in
  map equivp alphas
end
*}

(*
Tests:
prove alpha1_reflp_aux: {* fst (build_alpha_refl_gl [@{term alpha_rtrm1}, @{term alpha_bp}] ("x","y","z")) *}
by (tactic {* reflp_tac @{thm rtrm1_bp.induct} @{thms alpha1_inj} 1 *})

prove alpha1_symp_aux: {* (fst o snd) (build_alpha_refl_gl [@{term alpha_rtrm1}, @{term alpha_bp}] ("x","y","z")) *}
by (tactic {* symp_tac @{thm alpha_rtrm1_alpha_bp.induct} @{thms alpha1_inj} @{thms alpha1_eqvt} 1 *})

prove alpha1_transp_aux: {* (snd o snd) (build_alpha_refl_gl [@{term alpha_rtrm1}, @{term alpha_bp}] ("x","y","z")) *}
by (tactic {* transp_tac @{context} @{thm alpha_rtrm1_alpha_bp.induct} @{thms alpha1_inj} @{thms rtrm1.inject bp.inject} @{thms rtrm1.distinct bp.distinct} @{thms alpha_rtrm1.cases alpha_bp.cases} @{thms alpha1_eqvt} 1 *})

lemma alpha1_equivp:
  "equivp alpha_rtrm1"
  "equivp alpha_bp"
apply (tactic {*
  (simp_tac (HOL_ss addsimps @{thms equivp_reflp_symp_transp reflp_def symp_def})
  THEN' rtac @{thm conjI} THEN' rtac @{thm allI} THEN'
  resolve_tac (HOLogic.conj_elims @{thm alpha1_reflp_aux})
  THEN' rtac @{thm conjI} THEN' rtac @{thm allI} THEN' rtac @{thm allI} THEN'
  resolve_tac (HOLogic.conj_elims @{thm alpha1_symp_aux}) THEN' rtac @{thm transp_aux}
  THEN' resolve_tac (HOLogic.conj_elims @{thm alpha1_transp_aux})
)
1 *})
done*)

ML {*
fun dtyp_no_of_typ _ (TFree (n, _)) = error "dtyp_no_of_typ: Illegal free"
  | dtyp_no_of_typ _ (TVar _) = error "dtyp_no_of_typ: Illegal schematic"
  | dtyp_no_of_typ dts (Type (tname, Ts)) =
      case try (find_index (curry op = tname o fst)) dts of
        NONE => error "dtyp_no_of_typ: Illegal recursion"
      | SOME i => i
*}

end
