theory TopoS_Stateful_Policy
imports TopoS_Composition_Theory
begin

section\<open>Stateful Policy\<close>

text\<open>Details described in \cite{diekmann2014esss}.\<close>

text\<open>Algorithm\<close>
term TopoS_Composition_Theory.generate_valid_topology
text\<open>generates a valid high-level topology. Now we discuss how to turn this into
       a stateful policy.\<close>

text\<open>
Example:
  SensorNode produces data and has no security level.
  SensorSink has high security level
  SensorNode -> SensorSink, but not the other way round.
  Implementation: UDP in one direction

  Alice is in internal protected subnet. Google can not arbitrarily access Alice.
  Alice sends requests to google.
  It is desirable that Alice gets the response back
  Implementation: TCP and stateful packet filter that allows, once Alice establishes a connection, to get a response back via this connection.

Result:
  IFS violations undesirable.
  ACS violations may be okay under certain conditions.
\<close>

term all_security_requirements_fulfilled

text\<open>@{term "G = (V, E\<^sub>f\<^sub>i\<^sub>x, E\<^sub>s\<^sub>t\<^sub>a\<^sub>t\<^sub>e)"}\<close>
record 'v stateful_policy =
    hosts :: "'v set" \<comment> \<open>nodes, vertices\<close>
    flows_fix :: "('v \<times>'v) set" \<comment> \<open>edges in high-level policy\<close>
    flows_state :: "('v \<times>'v) set" \<comment> \<open>edges that can have stateful flows, i.e. backflows\<close>

text\<open>All the possible ways packets can travel in a @{typ "'v stateful_policy"}.
        They can either choose the fixed links;
        Or use a stateful link, i.e. establish state.
        Once state is established, packets can flow back via the established link.\<close>
definition all_flows :: "'v stateful_policy \<Rightarrow> ('v \<times> 'v) set" where
  "all_flows \<T> \<equiv> flows_fix \<T> \<union> flows_state \<T> \<union> backflows (flows_state \<T>)"

definition stateful_policy_to_network_graph :: "'v stateful_policy \<Rightarrow> 'v graph" where
  "stateful_policy_to_network_graph \<T> = \<lparr> nodes = hosts \<T>, edges = all_flows \<T> \<rparr>"

text\<open>@{typ "'v stateful_policy"} syntactically well-formed\<close>
locale wf_stateful_policy =
  fixes \<T> :: "'v stateful_policy"
  assumes E_wf: "fst ` (flows_fix \<T>) \<subseteq> (hosts \<T>)"
                   "snd ` (flows_fix \<T>) \<subseteq> (hosts \<T>)"
  and E_state_fix: "flows_state \<T> \<subseteq> flows_fix \<T>"
  and finite_Hosts: "finite (hosts \<T>)"
begin

  lemma finite_fix: "finite (flows_fix \<T>)"
  proof -
    from finite_subset[OF E_wf(1) finite_Hosts] have 1: "finite (fst ` flows_fix \<T>)" .
    from finite_subset[OF E_wf(2) finite_Hosts] have 2: "finite (snd ` flows_fix \<T>)" .
    have s: "flows_fix \<T> \<subseteq> (fst ` flows_fix \<T> \<times> snd ` flows_fix \<T>)" by force
    from finite_cartesian_product[OF 1 2] have "finite (fst ` flows_fix \<T> \<times> snd ` flows_fix \<T>)" .
    from finite_subset[OF s this] show ?thesis .
  qed

  lemma finite_state: "finite (flows_state \<T>)"
    using finite_subset[OF E_state_fix finite_fix] by assumption

  lemma finite_backflows_state: "finite (backflows (flows_state \<T>))"
    using [[simproc add: finite_Collect]] by(simp add: backflows_def finite_state)

  lemma E_state_backflows_wf: "fst ` backflows (flows_state \<T>) \<subseteq> (hosts \<T>)"
                         "snd ` backflows (flows_state \<T>) \<subseteq> (hosts \<T>)"
    by(auto simp add: backflows_def E_state_valid E_state_validD)

end

text\<open>Minimizing stateful flows such that only newly added backflows remain\<close>
  definition filternew_flows_state :: "'v stateful_policy \<Rightarrow> ('v \<times> 'v) set" where
    "filternew_flows_state \<T> \<equiv> {(s, r) \<in> flows_state \<T>. (r, s) \<notin> flows_fix \<T>}"

  lemma filternew_subseteq_flows_state: "filternew_flows_state \<T> \<subseteq> flows_state \<T>"
    by(auto simp add: filternew_flows_state_def)

  \<comment> \<open>alternative definitions, all are equal\<close>
  lemma filternew_flows_state_alt: "filternew_flows_state \<T>  = flows_state \<T> - (backflows (flows_fix \<T>))"
    apply(simp add: backflows_def filternew_flows_state_def)
    apply(rule)
     apply blast+
    done

  lemma stateful_policy_to_network_graph_filternew: "\<lbrakk> wf_stateful_policy \<T> \<rbrakk> \<Longrightarrow>
    stateful_policy_to_network_graph \<T> =
    stateful_policy_to_network_graph \<lparr>hosts = hosts \<T>, flows_fix = flows_fix \<T>, flows_state = filternew_flows_state \<T> \<rparr>"
    apply(drule wf_stateful_policy.E_state_fix)
    apply(simp add: stateful_policy_to_network_graph_def all_flows_def)
    apply(rule Set.equalityI)
     apply(simp add: filternew_flows_state_def backflows_def)
     apply(rule, blast)+
    apply(simp add: filternew_flows_state_def backflows_def)
    apply fastforce
    done

  lemma backflows_filternew_disjunct_flows_fix:
    "\<forall> b \<in> (backflows (filternew_flows_state \<T>)). b \<notin> flows_fix \<T>"
    by(simp add: filternew_flows_state_def backflows_def)

text\<open>Given a high-level policy, we can construct a pretty large syntactically valid low level policy. However, the stateful policy will
       almost certainly violate security requirements!\<close>
  lemma "wf_graph G \<Longrightarrow> wf_stateful_policy \<lparr> hosts = nodes G, flows_fix = nodes G \<times> nodes G, flows_state = nodes G \<times> nodes G \<rparr>"
    by(simp add: wf_stateful_policy_def wf_graph_def)

text\<open>@{const wf_stateful_policy} implies @{term wf_graph}\<close>
  lemma wf_stateful_policy_is_wf_graph: "wf_stateful_policy \<T> \<Longrightarrow> wf_graph \<lparr>nodes = hosts \<T>, edges = all_flows \<T>\<rparr>"
    apply(frule wf_stateful_policy.E_state_backflows_wf)
    apply(frule wf_stateful_policy.E_state_backflows_wf(2))
    apply(frule wf_stateful_policy.E_state_valid)
    apply(frule wf_stateful_policy.E_state_valid(2))
    apply(frule wf_stateful_policy.E_wf)
    apply(frule wf_stateful_policy.E_wf(2))
    apply(simp add: all_flows_def wf_graph_def wf_stateful_policy_def
          wf_stateful_policy.finite_fix wf_stateful_policy.finite_state wf_stateful_policy.finite_backflows_state)
    apply(rule conjI)
     apply (metis image_Un sup.bounded_iff)+
    done

(*we use the second way of writing it in the paper*)
lemma "(\<forall>F \<in> get_offending_flows (get_ACS M) (stateful_policy_to_network_graph \<T> ). F \<subseteq> backflows (filternew_flows_state \<T>)) \<longleftrightarrow>
    \<Union>(get_offending_flows (get_ACS M) (stateful_policy_to_network_graph \<T>)) \<subseteq> (backflows (flows_state \<T>)) - (flows_fix \<T>)"
    by(simp add: filternew_flows_state_alt backflows_minus_backflows, blast)

text\<open>When is a stateful policy @{term "\<T>"} compliant with a high-level policy @{term "G"} and the security requirements @{term "M"}?\<close>
locale stateful_policy_compliance =
  fixes \<T> :: "('v::vertex) stateful_policy"
  fixes G :: "'v graph"
  fixes M :: "('v) SecurityInvariant_configured list"
  assumes
    \<comment> \<open>the graph must be syntactically valid\<close>
    wfG: "wf_graph G"
    and
    \<comment> \<open>security requirements must be valid\<close>
    validReqs: "valid_reqs M"
    and
    \<comment> \<open>the high-level policy must be valid\<close>
    high_level_policy_valid: "all_security_requirements_fulfilled M G"
    and
    \<comment> \<open>the stateful policy must be syntactically valid\<close>
    stateful_policy_wf:
    "wf_stateful_policy \<T>"
    and
    \<comment> \<open>the stateful policy must talk about the same nodes as the high-level policy\<close>
    hosts_nodes:
    "hosts \<T> = nodes G"
    and
    \<comment> \<open>only flows that are allowed in the high-level policy are allowed in the stateful policy\<close>
    flows_edges:
    "flows_fix \<T> \<subseteq> edges G"
    and
    \<comment> \<open>the low level policy must comply with the high-level policy\<close>
      \<comment> \<open>all information flow strategy requirements must be fulfilled, i.e. no leaks!\<close>
      compliant_stateful_IFS:
        "all_security_requirements_fulfilled (get_IFS M) (stateful_policy_to_network_graph \<T>)"
      and
      \<comment> \<open>No Access Control side effects must occur\<close>
      compliant_stateful_ACS:
        "\<forall>F \<in> get_offending_flows (get_ACS M) (stateful_policy_to_network_graph \<T> ). F \<subseteq> backflows (filternew_flows_state \<T>)"

  begin
    lemma compliant_stateful_ACS_no_side_effects_filternew_helper:
      "\<forall> E \<subseteq> backflows (filternew_flows_state \<T>). \<forall> F \<in> get_offending_flows (get_ACS M) \<lparr> nodes = hosts \<T>, edges = flows_fix \<T> \<union> E \<rparr>. F \<subseteq> E"
    proof(rule, rule)
      fix E
      assume a1: "E \<subseteq> backflows (filternew_flows_state \<T>)"
      from validReqs have valid_ReqsACS: "valid_reqs (get_ACS M)" by(simp add: get_ACS_def valid_reqs_def)

      from compliant_stateful_ACS stateful_policy_to_network_graph_filternew[OF stateful_policy_wf] have compliant_stateful_ACS_only_state_violations_filternew:
      "\<forall>F \<in> get_offending_flows (get_ACS M) (stateful_policy_to_network_graph \<lparr>hosts = hosts \<T>, flows_fix = flows_fix \<T>, flows_state = filternew_flows_state \<T> \<rparr>). F \<subseteq> backflows (filternew_flows_state \<T>)" by simp

      from wf_stateful_policy_is_wf_graph[OF stateful_policy_wf] have wfGfilternew:
        "wf_graph \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> filternew_flows_state \<T> \<union> backflows (filternew_flows_state \<T>)\<rparr>"
        apply(simp add: all_flows_def filternew_flows_state_alt backflows_minus_backflows)
        by(auto simp add: wf_graph_def)

      from wf_stateful_policy.E_state_fix[OF stateful_policy_wf] filternew_subseteq_flows_state have flows_fix_un_filternew_simp: "flows_fix \<T> \<union> filternew_flows_state \<T> = flows_fix \<T>" by blast

      from compliant_stateful_ACS_only_state_violations_filternew have
        "\<And>m. m \<in> set (get_ACS M) \<Longrightarrow>
        \<Union>(c_offending_flows m \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> filternew_flows_state \<T> \<union> backflows (filternew_flows_state \<T>)\<rparr>) \<subseteq> backflows (filternew_flows_state \<T>)"
        by(simp add: stateful_policy_to_network_graph_def all_flows_def get_offending_flows_def, blast)

      \<comment> \<open>idea: use @{thm compliant_stateful_ACS} with the @{thm configured_SecurityInvariant.Un_set_offending_flows_bound_minus_subseteq}
        lemma and substract @{term "backflows (filternew_flows_state \<T>) - E"}, on the right hand side @{term E} remains, as Graph's edges @{term "flows_fix \<T>  \<union> E"} remains\<close>

      from configured_SecurityInvariant.Un_set_offending_flows_bound_minus_subseteq[where X="backflows (filternew_flows_state \<T>)", OF _ wfGfilternew this]
        \<open>valid_reqs (get_ACS M)\<close>
        have
        "\<And> m E. m \<in> set (get_ACS M) \<Longrightarrow>
        \<forall>F\<in>c_offending_flows m \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> filternew_flows_state \<T> \<union> backflows (filternew_flows_state \<T>) - E\<rparr>. F \<subseteq> backflows (filternew_flows_state \<T>) - E"
        by(auto simp add: all_flows_def valid_reqs_def)
      from this flows_fix_un_filternew_simp have rule:
        "\<And> m E. m \<in> set (get_ACS M) \<Longrightarrow>
        \<forall>F\<in>c_offending_flows m \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> backflows (filternew_flows_state \<T>) - E\<rparr>. F \<subseteq> backflows (filternew_flows_state \<T>) - E"
        by simp

      from  backflows_finite rev_finite_subset[OF wf_stateful_policy.finite_state[OF stateful_policy_wf] filternew_subseteq_flows_state] have
        "finite (backflows (filternew_flows_state \<T>))" by blast
      from a1 this have "finite E" by (metis rev_finite_subset)

      from a1 obtain E' where E'_prop1: "backflows (filternew_flows_state \<T>) - E' = E" and E'_prop2: "E' = backflows (filternew_flows_state \<T>) - E" by blast
      from E'_prop2 \<open>finite (backflows (filternew_flows_state \<T>))\<close> \<open>finite E\<close> have "finite E'" by blast

      from Set.double_diff[where B="backflows (filternew_flows_state \<T>)" and C="backflows (filternew_flows_state \<T>)" and A="E", OF a1, simplified] have Ebackflowssimp:
        "backflows (filternew_flows_state \<T>) - (backflows (filternew_flows_state \<T>) - E) = E" .

      have "flows_fix \<T> \<union> backflows (filternew_flows_state \<T>) - (backflows (filternew_flows_state \<T>) - E) =
          (flows_fix \<T> - (backflows (filternew_flows_state \<T>))) \<union> E"
          apply(simp add: Set.Un_Diff)
          apply(simp add: Ebackflowssimp)
          by blast
      also have "(flows_fix \<T> - (backflows (filternew_flows_state \<T>))) \<union> E = flows_fix \<T>  \<union> E" using backflows_filternew_disjunct_flows_fix by blast
      finally have flows_E_simp: "flows_fix \<T> \<union> backflows (filternew_flows_state \<T>) - (backflows (filternew_flows_state \<T>) - E) = flows_fix \<T>  \<union> E" .

      from rule[simplified E'_prop1 E'_prop2] have
      "\<And>m. m \<in> set (get_ACS M) \<Longrightarrow>
      \<forall>F\<in>c_offending_flows m \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> backflows (filternew_flows_state \<T>) - (backflows (filternew_flows_state \<T>) - E)\<rparr>.
       F \<subseteq> backflows (filternew_flows_state \<T>) - (backflows (filternew_flows_state \<T>) - E)"
       by(simp)
      from this Ebackflowssimp flows_E_simp have
      "\<And>m. m \<in> set (get_ACS M) \<Longrightarrow>
        \<forall>F\<in>c_offending_flows m \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> E\<rparr>. F \<subseteq> E"
       by simp
      thus  "\<forall>F\<in>get_offending_flows (get_ACS M) \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> E\<rparr>. F \<subseteq> E"
        by(simp add: get_offending_flows_def)
      qed

    theorem compliant_stateful_ACS_no_side_effects:
      "\<forall> E \<subseteq> backflows (flows_state \<T>). \<forall> F \<in> get_offending_flows(get_ACS M) \<lparr> nodes = hosts \<T>, edges = flows_fix \<T> \<union> E \<rparr>. F \<subseteq> E"
    proof -
      from compliant_stateful_ACS stateful_policy_to_network_graph_filternew[OF stateful_policy_wf] have a1:
      "\<forall>F \<in> get_offending_flows (get_ACS M) (stateful_policy_to_network_graph \<lparr>hosts = hosts \<T>, flows_fix = flows_fix \<T>, flows_state = filternew_flows_state \<T> \<rparr>). F \<subseteq> backflows (filternew_flows_state \<T>)" by simp

      have backflows_split: "backflows (filternew_flows_state \<T>) \<union> (backflows (flows_state \<T>) - backflows (filternew_flows_state \<T>)) = backflows (flows_state \<T>)"
        by (metis Diff_subset Un_Diff_cancel Un_absorb1 backflows_minus_backflows filternew_flows_state_alt)

      have
        "\<forall>E\<subseteq>backflows (filternew_flows_state \<T>) \<union> (backflows (flows_state \<T>) - backflows (filternew_flows_state \<T>)).
             \<forall>F\<in>get_offending_flows (get_ACS M) \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> E\<rparr>. F \<subseteq> E"
        proof(rule allI, rule impI)
          fix E
          assume h1: "E \<subseteq> backflows (filternew_flows_state \<T>) \<union> (backflows (flows_state \<T>) - backflows (filternew_flows_state \<T>))"

          have "\<exists> E1 E2. E1 \<subseteq> backflows (filternew_flows_state \<T>) \<and> E2 \<subseteq> (backflows (flows_state \<T>) - backflows (filternew_flows_state \<T>)) \<and> E1 \<union> E2 = E \<and> E1 \<inter> E2 = {}"
            apply(rule_tac x="{e \<in> E. e \<in> backflows (filternew_flows_state \<T>)}" in exI)
            apply(rule_tac x="{e \<in> E. e \<in>(backflows (flows_state \<T>) - backflows (filternew_flows_state \<T>))}" in exI)
            apply(simp)
            apply(rule)
             apply blast
            apply(rule)
             apply blast
            apply(rule)
             using h1 apply blast
            using backflows_filternew_disjunct_flows_fix by blast

          from this obtain E1 E2 where E1_prop: "E1 \<subseteq> backflows (filternew_flows_state \<T>)" and E2_prop: "E2 \<subseteq> (backflows (flows_state \<T>) - backflows (filternew_flows_state \<T>))" and "E = E1 \<union> E2" and "E1 \<inter> E2 = {}" by blast

          \<comment> \<open>the stateful flows are @{text "\<subseteq>"} fix flows. If substracting the new stateful flows, onyly the existing fix flows remain\<close>
          from E2_prop filternew_flows_state_alt have "E2 \<subseteq> flows_fix \<T>" by (metis (hide_lams, no_types) Diff_subset_conv Un_Diff_cancel2 backflows_minus_backflows inf_sup_ord(3) order.trans)
          \<comment> \<open>hence, E2 disappears\<close>
          from Set.Un_absorb1[OF this] have E2_absorb: "flows_fix \<T> \<union> E2 = flows_fix \<T>" by blast

          from \<open>E = E1 \<union> E2\<close> have E2E1eq: "E2 \<union> E1 = E" by blast

          from \<open>E = E1 \<union> E2\<close> \<open>E1 \<inter> E2 = {}\<close> have "E1 \<subseteq> E" by simp

          from compliant_stateful_ACS_no_side_effects_filternew_helper E1_prop have "\<forall>F\<in>get_offending_flows (get_ACS M) \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> E1 \<rparr>. F \<subseteq> E1" by simp
          hence "\<forall>F\<in>get_offending_flows (get_ACS M) \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> E2 \<union> E1 \<rparr>. F \<subseteq> E1" using E2_absorb[symmetric] by simp
          hence "\<forall>F\<in>get_offending_flows (get_ACS M) \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> E \<rparr>. F \<subseteq> E1" using E2E1eq by (metis Un_assoc)

          from this \<open>E1 \<subseteq> E\<close> show "\<forall>F\<in>get_offending_flows (get_ACS M) \<lparr>nodes = hosts \<T>, edges = flows_fix \<T> \<union> E\<rparr>. F \<subseteq> E" by blast
        qed

      from this backflows_split show ?thesis by presburger
    qed

    corollary compliant_stateful_ACS_no_side_effects': "\<forall> E \<subseteq> backflows (flows_state \<T>). \<forall> F \<in> get_offending_flows(get_ACS M) \<lparr> nodes = hosts \<T>, edges = flows_fix \<T> \<union> flows_state \<T> \<union> E \<rparr>. F \<subseteq> E"
      using compliant_stateful_ACS_no_side_effects wf_stateful_policy.E_state_fix[OF stateful_policy_wf] by (metis Un_absorb2)

    text\<open>The high level graph generated from the low level policy is a valid graph\<close>
    lemma valid_stateful_policy: "wf_graph \<lparr>nodes = hosts \<T>, edges = all_flows \<T>\<rparr>"
      by(rule wf_stateful_policy_is_wf_graph,fact stateful_policy_wf)

    text\<open>The security requirements are definitely fulfilled if we consider only the fixed flows and the
           normal direction of the stateful flows (i.e. no backflows).
           I.e. considering no states, everything must be fulfilled\<close>
    lemma compliant_stateful_ACS_static_valid: "all_security_requirements_fulfilled (get_ACS M) \<lparr> nodes = hosts \<T>, edges = flows_fix \<T>  \<rparr>"
    proof -
      from validReqs have valid_ReqsACS: "valid_reqs (get_ACS M)" by(simp add: get_ACS_def valid_reqs_def)
      from wfG hosts_nodes[symmetric] have wfG': "wf_graph \<lparr> nodes = hosts \<T>, edges = edges G  \<rparr>" by(case_tac G, simp)
      from high_level_policy_valid have "all_security_requirements_fulfilled (get_ACS M) G"
        by(simp add: get_ACS_def all_security_requirements_fulfilled_def)
      from this hosts_nodes[symmetric] have "all_security_requirements_fulfilled (get_ACS M) \<lparr> nodes = hosts \<T>, edges = edges G  \<rparr>"
        by(case_tac G, simp)
      from all_security_requirements_fulfilled_mono[OF valid_ReqsACS flows_edges wfG' this] show ?thesis .
    qed
    theorem compliant_stateful_ACS_static_valid':
      "all_security_requirements_fulfilled M \<lparr> nodes = hosts \<T>, edges = flows_fix \<T> \<union> flows_state \<T>  \<rparr>"
      proof -
        from validReqs have valid_ReqsIFS: "valid_reqs (get_IFS M)" by(simp add: get_IFS_def valid_reqs_def)

        \<comment> \<open>show that it holds for IFS, by monotonicity as it holds for more in IFS\<close>
        from all_security_requirements_fulfilled_mono[OF valid_ReqsIFS _ valid_stateful_policy compliant_stateful_IFS[unfolded stateful_policy_to_network_graph_def]] have
          goalIFS: "all_security_requirements_fulfilled (get_IFS M) \<lparr> nodes = hosts \<T>, edges = flows_fix \<T> \<union> flows_state \<T>  \<rparr>" by(simp add: all_flows_def)

        from wf_stateful_policy.E_state_fix[OF stateful_policy_wf] have "flows_fix \<T> \<union> flows_state \<T> =  flows_fix \<T>" by blast
        from this compliant_stateful_ACS_static_valid have goalACS:
          "all_security_requirements_fulfilled (get_ACS M) \<lparr> nodes = hosts \<T>, edges = flows_fix \<T> \<union> flows_state \<T>  \<rparr>" by simp

        \<comment> \<open>ACS and IFS together form M, we know it holds for ACS\<close>
        from goalACS goalIFS show ?thesis
          apply(simp add: all_security_requirements_fulfilled_def get_IFS_def get_ACS_def)
          by fastforce
    qed

    text\<open>The flows with state are a subset of the flows allowed by the policy\<close>
    theorem flows_state_edges: "flows_state \<T> \<subseteq> edges G"
      using wf_stateful_policy.E_state_fix[OF stateful_policy_wf] flows_edges by simp

    text\<open>All offending flows are subsets of the reveres stateful flows\<close>
    lemma compliant_stateful_ACS_only_state_violations:
      "\<forall>F \<in> get_offending_flows (get_ACS M) (stateful_policy_to_network_graph \<T>). F \<subseteq> backflows (flows_state \<T>)"
      proof -
        have "backflows (filternew_flows_state \<T>) \<subseteq> backflows (flows_state \<T>)" by (metis Diff_subset backflows_minus_backflows filternew_flows_state_alt)
        from compliant_stateful_ACS this have
          "\<forall> F \<in> get_offending_flows (get_ACS M) (stateful_policy_to_network_graph \<T>). F \<subseteq> backflows (flows_state \<T>)"
          by (metis subset_trans)
        thus ?thesis .
      qed
    theorem compliant_stateful_ACS_only_state_violations': "\<forall>F \<in> get_offending_flows M (stateful_policy_to_network_graph \<T>). F \<subseteq> backflows (flows_state \<T>)"
      proof -
        from validReqs have valid_ReqsIFS: "valid_reqs (get_IFS M)" by(simp add: get_IFS_def valid_reqs_def)
        have offending_split: "\<And>G. get_offending_flows M G = (get_offending_flows (get_IFS M) G \<union> get_offending_flows (get_ACS M) G)"
          apply(simp add: get_offending_flows_def get_IFS_def get_ACS_def) by blast
       show ?thesis
        apply(subst offending_split)
        using compliant_stateful_ACS_only_state_violations
              all_security_requirements_fulfilled_imp_get_offending_empty[OF valid_ReqsIFS compliant_stateful_IFS]
        by auto
      qed

    text \<open>All violations are backflows of valid flows\<close>
    corollary compliant_stateful_ACS_only_state_violations_union: "\<Union>(get_offending_flows (get_ACS M) (stateful_policy_to_network_graph \<T>)) \<subseteq> backflows (flows_state \<T>)"
    using compliant_stateful_ACS_only_state_violations by fastforce

    corollary compliant_stateful_ACS_only_state_violations_union': "\<Union>(get_offending_flows M (stateful_policy_to_network_graph \<T>)) \<subseteq> backflows (flows_state \<T>)"
    using compliant_stateful_ACS_only_state_violations' by fastforce

    text\<open>All individual flows cause no side effects, i.e. each backflow causes at most itself as violation, no other
           side-effect violations are induced.\<close>
    lemma  compliant_stateful_ACS_no_state_singleflow_side_effect:
      "\<forall> (v\<^sub>1, v\<^sub>2) \<in> backflows (flows_state \<T>).
       \<Union>(get_offending_flows(get_ACS M) \<lparr> nodes = hosts \<T>, edges = flows_fix \<T> \<union> flows_state \<T> \<union> {(v\<^sub>1, v\<^sub>2)} \<rparr>) \<subseteq> {(v\<^sub>1, v\<^sub>2)}"
    using compliant_stateful_ACS_no_side_effects' by blast
  end

subsection\<open>Summarizing the important theorems\<close>

  text\<open>No information flow security requirements are violated (including all added stateful flows)\<close>
  thm stateful_policy_compliance.compliant_stateful_IFS

  text\<open>There are not access control side effects when allowing stateful backflows.
          I.e. for all possible subsets of the to-allow backflows, the violations they cause are only these backflows themselves\<close>
  thm stateful_policy_compliance.compliant_stateful_ACS_no_side_effects'

    text\<open>Also, considering all backflows individually, they cause no side effect, i.e. the only violation added is the backflow itself\<close>
    thm stateful_policy_compliance.compliant_stateful_ACS_no_state_singleflow_side_effect

    text\<open>In particular, all introduced offending flows for access control strategies are at most the stateful backflows\<close>
    thm stateful_policy_compliance.compliant_stateful_ACS_only_state_violations_union
    text\<open>Which implies: all introduced offending flows are at most the stateful backflows\<close>
    thm stateful_policy_compliance.compliant_stateful_ACS_only_state_violations_union'

  text\<open>Disregarding the backflows of stateful flows, all security requirements are fulfilled.\<close>
  thm stateful_policy_compliance.compliant_stateful_ACS_static_valid'

end


theory FOLoG
  imports Rule Com Varnames "HOL-Library.AList_Mapping"
begin

\<comment> \<open>quantifier reference\<close>
datatype qref
  = Nref noderef
  | Eref edgeref
  | Lref hostlabel

datatype val
  = Val_MarkNode rulemark_node
  | Val_MarkEdge rulemark_edge
  | Val_Label rulelabel
  | Val_Int nat

datatype tm
  = Term_QVar vname ("\<langle>_\<rangle>" [50] 50)
  | Term_Ref qref
  | Term_Val val
  | Term_Mark tm  ("\<lceil>mark _\<rceil>" [50] 50)
  | Term_Label tm ("\<lceil>label _\<rceil>" [50] 50)
  | Term_Src tm ("\<lceil>src _\<rceil>" [50] 50)
  | Term_Trg tm ("\<lceil>trg _\<rceil>" [50] 50)
  | Term_Indeg  tm ("\<lceil>indeg _\<rceil>"  [50] 50)
  | Term_Outdeg tm ("\<lceil>outdeg _\<rceil>" [50] 50)

abbreviation ref_nref :: "noderef \<Rightarrow> tm" ("\<leadsto>\<^sub>V _" [50] 50) where
"ref_nref nid \<equiv> Term_Ref (Nref nid)"

abbreviation ref_eref :: "noderef \<Rightarrow> tm" ("\<leadsto>\<^sub>E _" [50] 50) where
"ref_eref eid \<equiv> Term_Ref (Eref eid)"

abbreviation val_markv :: "rulemark_node \<Rightarrow> tm" ("\<triangleright>\<^sub>V _" [50] 50) where
"val_markv m \<equiv> Term_Val (Val_MarkNode m)"

abbreviation val_marke :: "rulemark_edge \<Rightarrow> tm" ("\<triangleright>\<^sub>E _" [50] 50) where
"val_marke m \<equiv> Term_Val (Val_MarkEdge m)"

abbreviation val_label :: "rulelabel \<Rightarrow> tm" ("\<triangleright>\<^sub>L _" [50] 50) where
"val_label l \<equiv> Term_Val (Val_Label l)"

abbreviation val_int :: "nat \<Rightarrow> tm" ("\<triangleright>\<^sub>I _" [50] 50) where
"val_int i \<equiv> Term_Val (Val_Int i)"

datatype qty = Edge | Node | Label

datatype form
  = T
  | Not form ("\<lceil>\<not>\<rceil> _" [40] 40)
  | Conj form form (infixr "\<lceil>\<and>\<rceil>" 35)
  | Disj form form (infixr "\<lceil>\<or>\<rceil>" 30)
  | Exi vname qty form ("\<lceil>\<exists> _ : _\<rceil> _" [0, 0, 10] 10)
  | Rooted tm ("\<lceil>rooted _\<rceil>" [50] 50)
  | Typed tm lty (infixr "\<lceil>::\<rceil>" 45)
  | Eq tm tm (infixl "\<lceil>=\<rceil>" 40)

fun form_size :: "form \<Rightarrow> nat" where
  "form_size (Not t) = 1 + form_size t"
| "form_size (Conj a b) = 1 + form_size a + form_size b"
| "form_size (Disj a b) = 1 + form_size a + form_size b"
| "form_size (Exi _ _ t) = 1 + form_size t"
| "form_size _ = 0"

abbreviation not_eq :: "tm \<Rightarrow> tm \<Rightarrow> form" (infixl "\<lceil>\<noteq>\<rceil>" 40) where
"not_eq a b \<equiv> \<lceil>\<not>\<rceil>(a \<lceil>=\<rceil> b)"

abbreviation not_true :: form ("F") where
"not_true \<equiv> \<lceil>\<not>\<rceil>T"

abbreviation unrooted :: "tm \<Rightarrow> form" ("\<lceil>unrooted _\<rceil>" [50] 50) where
"unrooted t \<equiv> \<lceil>\<not>\<rceil>\<lceil>rooted t\<rceil>"

abbreviation form_impl :: "form \<Rightarrow> form \<Rightarrow> form" (infixr "\<lceil>\<longrightarrow>\<rceil>" 25) where
"form_impl l r \<equiv> (\<lceil>\<not>\<rceil>l) \<lceil>\<or>\<rceil> r"

abbreviation form_equality :: "form \<Rightarrow> form \<Rightarrow> form" (infixr "\<lceil>\<longleftrightarrow>\<rceil>" 25) where
"form_equality l r \<equiv> (l \<lceil>\<longrightarrow>\<rceil> r) \<lceil>\<and>\<rceil> (r \<lceil>\<longrightarrow>\<rceil> l)"

abbreviation forall_form :: "vname \<Rightarrow> qty \<Rightarrow> form \<Rightarrow> form" ("\<lceil>\<forall> _ : _\<rceil> _" [0, 0, 10] 10) where
"forall_form v q f \<equiv> \<lceil>\<not>\<rceil>(\<lceil>\<exists> v : q\<rceil> (\<lceil>\<not>\<rceil>f))"

type_synonym state = "vname \<Rightarrow> qref"

fun etm :: "hostgraph \<Rightarrow> state \<Rightarrow> tm \<Rightarrow> tm" where
  "etm _ _ (Term_Val v) = Term_Val v"
| "etm _ _ (Term_Ref v) = Term_Ref v"
| "etm _ s (Term_QVar v) = Term_Ref (s v)"

| "etm g s (Term_Mark t) = (case etm g s t of
    Term_Ref (Nref n) \<Rightarrow> Term_Val (Val_MarkNode (conv_mark_node (node_mark (the (Mapping.lookup (nodes g) n)))))
  | Term_Ref (Eref e) \<Rightarrow> Term_Val (Val_MarkEdge (conv_mark_edge (edge_mark (the (Mapping.lookup (edges g) e))))))"

| "etm g s (Term_Label t) = (case etm g s t of
    Term_Ref (Nref n) \<Rightarrow> Term_Val (Val_Label (conv_label (node_label (the (Mapping.lookup (nodes g) n)))))
  | Term_Ref (Eref e) \<Rightarrow> Term_Val (Val_Label (conv_label (edge_label (the (Mapping.lookup (edges g) e))))))"

\<comment> \<open>src and trg\<close>
| "etm g s (Term_Src t) = (case etm g s t of
    Term_Ref (Eref e) \<Rightarrow> Term_Ref (Nref (edge_src (the (Mapping.lookup (edges g) e)))))"
| "etm g s (Term_Trg t) = (case etm g s t of
    Term_Ref (Eref e) \<Rightarrow> Term_Ref (Nref (edge_trg (the (Mapping.lookup (edges g) e)))))"

\<comment> \<open>indegree and outdegree\<close>
| "etm g s (Term_Indeg t) = (case etm g s t of
    Term_Ref (Nref n) \<Rightarrow> Term_Val (Val_Int (indeg g n)))"
| "etm g s (Term_Outdeg t) = (case etm g s t of
    Term_Ref (Nref n) \<Rightarrow> Term_Val (Val_Int (outdeg g n)))"

fun eval :: "hostgraph \<Rightarrow> state \<Rightarrow> form \<Rightarrow> bool" where
  "eval _ _ T           = True"
| "eval g s (Not f)     = (\<not>eval g s f)"
| "eval g s (Conj a b)  = (eval g s a \<and> eval g s b)"
| "eval g s (Disj a b)  = (eval g s a \<or> eval g s b)"

\<comment> \<open>existential quantification\<close>
| "eval g s (Exi v Node  f) = (\<exists>n \<in> Mapping.keys (nodes g). eval g (s(v := Nref n)) f)"
| "eval g s (Exi v Edge  f) = (\<exists>e \<in> Mapping.keys (edges g). eval g (s(v := Eref e)) f)"
| "eval g s (Exi v Label f) = (\<exists>l \<in> UNIV. eval g (s(v := Lref l)) f)"

| "eval g s (Rooted t) = (case etm g s t of
    Term_Ref (Nref n) \<Rightarrow> node_rooted (the (Mapping.lookup (nodes g) n)))"

| "eval g s (Typed t ty) = undefined" \<comment> \<open>just on I and S, ...., or with variables?\<close>

| "eval g s (Eq l r) = (case (etm g s l, etm g s r) of
    (Term_Val (Val_MarkNode l'), Term_Val (Val_MarkNode r')) \<Rightarrow> mark_eq_node l' r'
  | (Term_Val (Val_MarkEdge l'), Term_Val (Val_MarkEdge r')) \<Rightarrow> mark_eq_edge l' r'
  | (l', r') \<Rightarrow> (l' = r'))"

section \<open>Generalized rule schema\<close>

type_synonym grule = "ruleschema \<times> form \<times> form"

\<comment> \<open>TODO: convertion of c to form\<close>
fun rule_to_grule :: "rule \<Rightarrow> grule" ("_\<^sup>\<or>") where
"rule_to_grule (r, c) = (r, T, T)"

section \<open>Example r1 and r2 \<close>
definition r1 :: rule where
"r1 = (\<lparr>rule_ty = Mapping [(0,Lty), (1,Lty),(2,Lty), (3,Ity), (4,Ity)]
      ,rule_lhs = \<lparr>nodes = Mapping
                           [(1, \<lparr>node_mark = RuleMarkNode_None, node_label = [Var 0], node_rooted = False\<rparr>)
                           ,(2, \<lparr>node_mark = RuleMarkNode_None, node_label = [Var 1], node_rooted = False\<rparr>)
                           ,(3, \<lparr>node_mark = RuleMarkNode_None, node_label = [Var 2], node_rooted = False\<rparr>)]
                  ,edges = Mapping
                           [(1, \<lparr>edge_src = 1, edge_trg = 2, edge_mark = RuleMarkEdge_None, edge_label = [Var 3]\<rparr>)
                           ,(2, \<lparr>edge_src = 1, edge_trg = 3, edge_mark = RuleMarkEdge_None, edge_label = [Var 4]\<rparr>)]\<rparr>
      ,rule_rhs = \<lparr>nodes = Mapping
                           [(1, \<lparr>node_mark = RuleMarkNode_Red , node_label = [Var 0], node_rooted = False\<rparr>)
                           ,(2, \<lparr>node_mark = RuleMarkNode_None, node_label = [Var 1], node_rooted = False\<rparr>)]
                  ,edges = Mapping
                          [(1,  \<lparr>edge_src = 1, edge_trg = 2, edge_mark = RuleMarkEdge_None, edge_label = [Add (Var 3) (Var 4)]\<rparr>)]\<rparr>
      ,rule_interf = {1,2}\<rparr>, cond.T)"

definition q1 :: form where
"q1 = (\<lceil>\<not>\<rceil>(\<lceil>\<exists> 0 : Edge\<rceil> \<lceil>mark \<lceil>src \<langle>0\<rangle>\<rceil>\<rceil> \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None))"

definition r2 :: rule where
"r2 = (\<lparr>rule_ty = Mapping [(0, Lty)]
      ,rule_lhs = \<lparr>nodes = Mapping [(1, \<lparr>node_mark = RuleMarkNode_None, node_label = [Var 0], node_rooted = True\<rparr>)]
                  ,edges = Mapping.empty\<rparr>
      ,rule_rhs = \<lparr>nodes = Mapping
                           [(1, \<lparr>node_mark = RuleMarkNode_None, node_label = [Var 0], node_rooted = False\<rparr>)
                           ,(2, \<lparr>node_mark = RuleMarkNode_None, node_label = [Var 0], node_rooted = True\<rparr>)]
                  ,edges = Mapping [(1, \<lparr>edge_src = 1, edge_trg = 2, edge_mark = RuleMarkEdge_Dashed, edge_label = []\<rparr>)]\<rparr>
      ,rule_interf = {1}\<rparr>, cond.T)"

definition q2 :: form where
"q2 = (\<lceil>\<exists> 0 : Node\<rceil> \<lceil>unrooted \<langle>0\<rangle>\<rceil>)"

section \<open>Term substitution\<close>

fun subst_term_term :: "tm \<Rightarrow> tm \<Rightarrow> tm \<Rightarrow> tm" where
"subst_term_term i a x = (if i = x then a else case i of
    Term_Mark   t \<Rightarrow> Term_Mark   (subst_term_term t a x)
  | Term_Label  t \<Rightarrow> Term_Label  (subst_term_term t a x)
  | Term_Src    t \<Rightarrow> Term_Src    (subst_term_term t a x)
  | Term_Trg    t \<Rightarrow> Term_Trg    (subst_term_term t a x)
  | Term_Indeg  t \<Rightarrow> Term_Indeg  (subst_term_term t a x)
  | Term_Outdeg t \<Rightarrow> Term_Outdeg (subst_term_term t a x)
  | a \<Rightarrow> a)"

lemma "subst_term_term (\<leadsto>\<^sub>V 1) (\<leadsto>\<^sub>V 2) (\<leadsto>\<^sub>V 1) = (\<leadsto>\<^sub>V 2)"
  by simp

fun subst_term :: "form \<Rightarrow> tm \<Rightarrow> tm \<Rightarrow> form" ("_[_'/_]" [19] 20) where
  "subst_term T _ _ = T"
| "subst_term (Not f)      a x = Not (subst_term f a x)"
| "subst_term (Conj l r)   a x = Conj (subst_term l a x) (subst_term r a x)"
| "subst_term (Disj l r )  a x = Disj (subst_term l a x) (subst_term r a x)"

| "subst_term (Exi v ty f) a x = Exi v ty (subst_term f a x)"
\<comment> \<open>subst term\<close>
| "subst_term (Rooted t) a x = Rooted (subst_term_term t a x)"
| "subst_term (Typed t ty) a x = Typed (subst_term_term t a x) ty"
| "subst_term (Eq l r) a x = Eq (subst_term_term l a x) (subst_term_term r a x)"

lemma "((\<leadsto>\<^sub>V 1 \<lceil>=\<rceil> \<leadsto>\<^sub>V 2)[\<leadsto>\<^sub>V 2/\<leadsto>\<^sub>V 1][\<leadsto>\<^sub>V 3/\<leadsto>\<^sub>V 2]) = (\<leadsto>\<^sub>V 3 \<lceil>=\<rceil> \<leadsto>\<^sub>V 3)"
  by simp

lemma form_size_term[simp] :
  "(size (subst_term f a x)) = (size f)"
  apply (induct f rule:form_size.induct)
           apply (simp_all)
  done

section "SLP construction"

subsection \<open>From precondition to left-application condition\<close>

(* Definition 5.1 Condition Dang *)
fun Dang :: "ruleschema \<Rightarrow> form" where
"Dang r = (let vk = Mapping.filter (\<lambda>k v. k \<notin> (rule_interf r)) (nodes (rule_lhs r)) in
  mfold vk (\<lambda>(i, _) a.
        \<lceil>indeg  \<leadsto>\<^sub>V i\<rceil> \<lceil>=\<rceil> \<triangleright>\<^sub>I (indeg  (rule_lhs r) i)
    \<lceil>\<and>\<rceil> \<lceil>outdeg \<leadsto>\<^sub>V i\<rceil> \<lceil>=\<rceil> \<triangleright>\<^sub>I (outdeg (rule_lhs r) i) \<lceil>\<and>\<rceil> a) T)"

value "Dang (fst r1)"

(* Definition 5.3 Transformation Split *)
fun Split :: "form \<Rightarrow> ruleschema \<Rightarrow> form" where
\<comment> \<open>base case\<close>
  "Split T           _ = T"
| "Split (Typed v ty) _ = (Typed v ty)"
| "Split (Eq a b)   _ = (Eq a b)"
| "Split (Rooted t)   _ = (Rooted t)"

\<comment> \<open>inductive case\<close>
| "Split (Conj a b) r = Conj (Split a r) (Split b r)"
| "Split (Disj a b) r = Disj (Split a r) (Split b r)"
| "Split (Not c)    r = Not (Split c r)"

\<comment> \<open>quantification\<close>
 | "Split (Exi vname Node f) r =
    ((mfold (nodes (rule_lhs r)) (\<lambda>(i, _) a. (Split (f[\<leadsto>\<^sub>V i/\<langle>vname\<rangle>]) r) \<lceil>\<or>\<rceil> a) F) \<lceil>\<or>\<rceil>
    (\<lceil>\<exists> vname : Node\<rceil> ((mfold (nodes (rule_lhs r))
      (\<lambda>(i, _) a. \<langle>vname\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V i \<lceil>\<and>\<rceil> a) T) \<lceil>\<and>\<rceil> Split f r)))"

| "Split (Exi vname Edge f) r =
  (let Inc = (mfold (nodes (rule_lhs r)) (\<lambda>(i,_) ia.
        (mfold (nodes (rule_lhs r)) (\<lambda>(j,_) ja. (\<lceil>src \<langle>vname\<rangle>\<rceil> \<lceil>=\<rceil> \<leadsto>\<^sub>V i \<lceil>\<and>\<rceil> \<lceil>trg \<langle>vname\<rangle>\<rceil> \<lceil>=\<rceil> \<leadsto>\<^sub>V j
          \<lceil>\<and>\<rceil> Split (f[\<leadsto>\<^sub>V i/\<lceil>src \<langle>vname\<rangle>\<rceil>][\<leadsto>\<^sub>V j/\<lceil>trg \<langle>vname\<rangle>\<rceil>]) r) \<lceil>\<or>\<rceil> ja) F)

      \<lceil>\<or>\<rceil> (\<lceil>src \<langle>vname\<rangle>\<rceil> \<lceil>=\<rceil> \<leadsto>\<^sub>V i \<lceil>\<and>\<rceil> mfold (nodes (rule_lhs r)) (\<lambda>(j,_) ja. \<lceil>trg \<langle>vname\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V j \<lceil>\<and>\<rceil> ja) T
          \<lceil>\<and>\<rceil> Split (f[\<leadsto>\<^sub>V i/\<lceil>src \<langle>vname\<rangle>\<rceil>]) r)

      \<lceil>\<or>\<rceil> (mfold (nodes (rule_lhs r)) (\<lambda>(j,_) ja. \<lceil>src \<langle>vname\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V j \<lceil>\<and>\<rceil> ja) T
          \<lceil>\<and>\<rceil> \<lceil>trg \<langle>vname\<rangle>\<rceil> \<lceil>=\<rceil> \<leadsto>\<^sub>V i \<lceil>\<and>\<rceil> Split (f[\<leadsto>\<^sub>V i/\<lceil>trg \<langle>vname\<rangle>\<rceil>]) r)

      \<lceil>\<or>\<rceil> ia) F)
   \<lceil>\<or>\<rceil> ((mfold (nodes (rule_lhs r)) (\<lambda>(i,_) ia. \<lceil>src \<langle>vname\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V i \<lceil>\<and>\<rceil> ia) T)
        \<lceil>\<and>\<rceil> (mfold (nodes (rule_lhs r)) (\<lambda>(j,_) ja. \<lceil>trg \<langle>vname\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V j \<lceil>\<and>\<rceil> ja) T)
        \<lceil>\<and>\<rceil> Split f r)
  in
  ((mfold (edges (rule_lhs r)) (\<lambda>(i, _) a. Split (f[\<leadsto>\<^sub>E i/\<langle>vname\<rangle>]) r \<lceil>\<or>\<rceil> a) F) \<lceil>\<or>\<rceil>
    (\<lceil>\<exists> vname : Edge\<rceil> ((mfold (edges (rule_lhs r))
      (\<lambda>(i, _) a. \<langle>vname\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>E i  \<lceil>\<and>\<rceil> a) T) \<lceil>\<and>\<rceil> Inc))))"

 | "Split (Exi vname Label f) r = Exi vname Label (Split f r)"

value "Split q1 (fst r1)"

(* Definition 5.5 Valuation of c *)
fun Val_Term :: "tm \<Rightarrow> ruleschema \<Rightarrow> tm" where
  "Val_Term (Term_Mark (Term_Ref (Nref n))) r = (Term_Val (Val_MarkNode (node_mark (the (Mapping.lookup (nodes (rule_lhs r)) n)))))"
| "Val_Term (Term_Mark (Term_Ref (Eref e))) r = (Term_Val (Val_MarkEdge (edge_mark (the (Mapping.lookup (edges (rule_lhs r)) e)))))"
| "Val_Term (Term_Mark (Term_Src (Term_Ref (Eref e)))) r =
  (Term_Val (Val_MarkNode (node_mark (the (Mapping.lookup (nodes (rule_lhs r)) (edge_src (the (Mapping.lookup (edges (rule_lhs r)) e))))))))"
| "Val_Term (Term_Mark (Term_Trg (Term_Ref (Eref e)))) r =
  (Term_Val (Val_MarkNode (node_mark (the (Mapping.lookup (nodes (rule_lhs r)) (edge_trg (the (Mapping.lookup (edges (rule_lhs r)) e))))))))"
| "Val_Term t r = t"

fun Val :: "form \<Rightarrow> ruleschema \<Rightarrow> form" where
  "Val T           _ = T"
| "Val (Typed v ty) _ = (Typed v ty)"

\<comment> \<open>Check again B(x) for rooted, true if v \<in> rule_lhs otherwise false\<close>
| "Val (Rooted (Term_Ref (Nref n))) r = (case Mapping.lookup (nodes (rule_lhs r)) n of
    None \<Rightarrow> F
  | Some n' \<Rightarrow> if node_rooted n' then T else F)"
| "Val (Rooted t) _ = Rooted t"

| "Val (Eq a b)   r = (Eq (Val_Term a r) (Val_Term b r))"

\<comment> \<open>inductive case\<close>
| "Val (Conj a b) r = Conj (Val a r) (Val b r)"
| "Val (Disj a b) r = Disj (Val a r) (Val b r)"
| "Val (Not c)    r = Not (Val c r)"

| "Val (Exi vname ty f) r = Exi vname ty (Val f r)"

(* Definition 5.7 Transformation Lift *)
fun Lift :: "form \<Rightarrow> grule \<Rightarrow> form" where
"Lift c (r, acL, _) = Val (Split (c \<lceil>\<and>\<rceil> acL) r \<lceil>\<and>\<rceil> Dang r) r"

subsection \<open>From left application condition to right application condition\<close>

(* Definition 5.9 Adjustment *)
fun Adj :: "form \<Rightarrow> ruleschema \<Rightarrow> form" where
  "Adj T _ = T"
| "Adj (Not c) r = Not (Adj c r)"
| "Adj (Conj a b) r = Conj (Adj a r) (Adj b r)"
| "Adj (Disj a b) r = Disj (Adj a r) (Adj b r)"

| "Adj (Exi vname Node c) r =
   (let vk = Mapping.filter (\<lambda>k v. k \<notin> (rule_interf r)) (nodes (rule_rhs r)) ;
        f = mfold vk (\<lambda>(i,_) a. \<langle>vname\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V i \<lceil>\<and>\<rceil> a) T
   in Exi vname Node (f \<lceil>\<and>\<rceil> Adj c r))"

  \<comment> \<open>Note: what does R-K reflect for edges?\<close>
(* | "Adj (Exi vname Edge c) r = Exi vname Edge (Adj c r)" *)
| "Adj (Exi vname Edge c) r =
   (let vk = Mapping.filter (\<lambda>_ v. edge_src v \<notin> (rule_interf r)
                                \<and>  edge_trg v \<notin> (rule_interf r)) (edges (rule_rhs r)) ;
        f = mfold vk (\<lambda>(i,_) a. \<langle>vname\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>E i \<lceil>\<and>\<rceil> a) T
   in Exi vname Edge (f \<lceil>\<and>\<rceil> Adj c r))"

| "Adj (Exi vname Label c) r = Exi vname Label (Adj c r)"
| "Adj (Rooted t) _ = Rooted t"
| "Adj (Typed t ty) _ = Typed t ty"

\<comment> \<open>Check equal case, a \<in> VL - VL \<union> EL TODO: adjust c' by replacing incon...\<close>
| "Adj (Eq a b) r = (case (a,b) of
    _ \<Rightarrow> Eq a b)"

(* Definition 3.23 Specifying a totally labelled graph *)
fun Spec :: "rulegraph \<Rightarrow> tyenv \<Rightarrow> form" where
"Spec g ty =
   (let n = mfold (nodes g) (\<lambda>(i,v) a.
                \<lceil>mark \<leadsto>\<^sub>V i\<rceil>  \<lceil>=\<rceil> \<triangleright>\<^sub>V (node_mark v)
            \<lceil>\<and>\<rceil> (if (node_rooted v) then \<lceil>rooted  \<leadsto>\<^sub>V i\<rceil> else \<lceil>unrooted  \<leadsto>\<^sub>V i\<rceil>)
            \<lceil>\<and>\<rceil> a) T;
       e = mfold (edges g) (\<lambda>(i,v) a.
                \<lceil>src \<leadsto>\<^sub>E i\<rceil>   \<lceil>=\<rceil> \<leadsto>\<^sub>V (edge_src v)
            \<lceil>\<and>\<rceil> \<lceil>trg \<leadsto>\<^sub>E i\<rceil>   \<lceil>=\<rceil> \<leadsto>\<^sub>V (edge_trg v)
            \<lceil>\<and>\<rceil> \<lceil>mark \<leadsto>\<^sub>E i\<rceil>  \<lceil>=\<rceil> \<triangleright>\<^sub>E (edge_mark v)
            \<lceil>\<and>\<rceil> a) T
  in n \<lceil>\<and>\<rceil> e)"
(* "Spec g ty =
   (let n = mfold (nodes g) (\<lambda>(i,v) a.
                \<lceil>label \<leadsto>\<^sub>V i\<rceil> \<lceil>=\<rceil> \<triangleright>\<^sub>L (node_label v)
            \<lceil>\<and>\<rceil> \<lceil>mark \<leadsto>\<^sub>V i\<rceil>  \<lceil>=\<rceil> \<triangleright>\<^sub>V (node_mark v)
            \<lceil>\<and>\<rceil> (if (node_rooted v) then \<lceil>rooted  \<leadsto>\<^sub>V i\<rceil> else \<lceil>unrooted  \<leadsto>\<^sub>V i\<rceil>)
            \<lceil>\<and>\<rceil> a) T;
       e = mfold (edges g) (\<lambda>(i,v) a.
                \<lceil>src \<leadsto>\<^sub>E i\<rceil>   \<lceil>=\<rceil> \<leadsto>\<^sub>V (edge_src v)
            \<lceil>\<and>\<rceil> \<lceil>trg \<leadsto>\<^sub>E i\<rceil>   \<lceil>=\<rceil> \<leadsto>\<^sub>V (edge_trg v)
            \<lceil>\<and>\<rceil> \<lceil>label \<leadsto>\<^sub>E i\<rceil> \<lceil>=\<rceil> \<triangleright>\<^sub>L (edge_label v)
            \<lceil>\<and>\<rceil> \<lceil>mark \<leadsto>\<^sub>E i\<rceil>  \<lceil>=\<rceil> \<triangleright>\<^sub>E (edge_mark v)
            \<lceil>\<and>\<rceil> a) T
  in n \<lceil>\<and>\<rceil> e)" *)

(* Definition 5.12 Shifting *)
fun Shift :: "grule \<Rightarrow> form" where
"Shift (r, acl, acr) = (Adj acl r \<lceil>\<and>\<rceil> acr \<lceil>\<and>\<rceil> Spec (rule_rhs r) (rule_ty r) \<lceil>\<and>\<rceil>
                           Dang (ruleschema_inverse r))"

subsection \<open>From rigth application condition to postcondition\<close>

fun fconst :: "form \<Rightarrow> tm list" where
  "fconst T = []"
| "fconst (Not f) = fconst f"
| "fconst (Conj a b) = fconst a @ fconst b"
| "fconst (Disj a b) = fconst a @ fconst b"
| "fconst (Exi _ _ f) = fconst f"
| "fconst (Rooted tm) = (case tm of
    Term_Ref (Nref nid) \<Rightarrow> [Term_Ref (Nref nid)]
    | _ \<Rightarrow> [])"

| "fconst (Typed _ _) = []"
| "fconst (Eq a b) = (let f = (\<lambda>v. case v of
    Term_Ref (Nref nid) \<Rightarrow> [Term_Ref (Nref nid)]
  | Term_Ref (Eref eid) \<Rightarrow> [Term_Ref (Eref eid)]
  | _ \<Rightarrow> []) in f a @ f b)"

fun qconst :: "form \<Rightarrow> vname set" where
  "qconst T = {}"
| "qconst (Not f) = qconst f"
| "qconst (Conj a b) = qconst a \<union> qconst b"
| "qconst (Disj a b) = qconst a \<union> qconst b"
| "qconst (Exi v _ f) = {v} \<union> qconst f"
| "qconst _ = {}"

(* Definition 5.14 Formula Post and Definition 3.25 Variablisation of a condition over a graph *)
fun Post :: "form \<Rightarrow> form" where
"Post f = (let
  usedvars = qconst f;
  (xs, _) = zipFresh (remdups (fconst f)) usedvars;
  (nids, eids) = partition (\<lambda>(t, _). case t of Term_Ref (Nref n) \<Rightarrow> True | _ \<Rightarrow> False) xs;
  cn = foldr (\<lambda>(ref, vn) a. a[\<langle>vn\<rangle>/ref]) nids f;
  ce = foldr (\<lambda>(ref, vn) a. a[\<langle>vn\<rangle>/ref]) eids cn;
  uniqn= foldr (\<lambda>(x,y) a. \<langle>x\<rangle> \<lceil>\<noteq>\<rceil> \<langle>y\<rangle> \<lceil>\<and>\<rceil> a) [(x,y) . (_, x) \<leftarrow> nids, (_, y) \<leftarrow> nids, x \<noteq> y] T;
  uniqe= foldr (\<lambda>(x,y) a. \<langle>x\<rangle> \<lceil>\<noteq>\<rceil> \<langle>y\<rangle> \<lceil>\<and>\<rceil> a) [(x,y) . (_, x) \<leftarrow> eids, (_, y) \<leftarrow> eids, x \<noteq> y] T;
  qe = foldr (\<lambda>(_,v) a. \<lceil>\<exists> v: Edge\<rceil> a) eids (uniqn \<lceil>\<and>\<rceil> uniqe \<lceil>\<and>\<rceil> ce);
  qn = foldr (\<lambda>(_,v) a. \<lceil>\<exists> v: Node\<rceil> a) nids qe
  in qn)"

fun Slp where
"Slp c r = Post (Shift (fst r, Lift c (r\<^sup>\<or>), T))"

\<comment> \<open>Dang(r1) = indeg(3) = 1 \<and> outdeg(3) = 0\<close>
value "Dang (fst r1)"
lemma "(eval g undefined (Dang (fst r1))) = eval g undefined (\<lceil>indeg  \<leadsto>\<^sub>V 3\<rceil> \<lceil>=\<rceil> \<triangleright>\<^sub>I 1 \<lceil>\<and>\<rceil> \<lceil>outdeg  \<leadsto>\<^sub>V 3\<rceil> \<lceil>=\<rceil> \<triangleright>\<^sub>I 0)"
  apply code_simp
  by simp

lemma "eval g undefined ((Dang (fst r1)) \<lceil>\<longleftrightarrow>\<rceil> (\<lceil>indeg  \<leadsto>\<^sub>V 3\<rceil> \<lceil>=\<rceil> \<triangleright>\<^sub>I 1 \<lceil>\<and>\<rceil> \<lceil>outdeg  \<leadsto>\<^sub>V 3\<rceil> \<lceil>=\<rceil> \<triangleright>\<^sub>I 0))"
  apply code_simp
  apply(simp add: r1_def)
  by (metis (no_types, lifting) foldr_conv_fold gr0I)

lemma "eval g undefined (Dang (fst r2))"
  by (code_simp)

lemma "wf_ruleschema (fst r1)" by (simp add: r1_def)
lemma "wf_ruleschema (fst r2)" by (simp add: r2_def)

\<comment> \<open>Example 6 (Transformation Split)\<close>

lemma "eval g undefined (Split q1 (fst r1) \<lceil>\<longleftrightarrow>\<rceil> (\<lceil>\<not>\<rceil> Split (\<lceil>\<exists> 0 : Edge\<rceil> (\<lceil>mark \<lceil>src \<langle>0\<rangle>\<rceil>\<rceil> \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None)) (fst r1)))"
  by (metis Split.simps(7) eval.simps(2) eval.simps(3) eval.simps(4) q1_def)

(* lemma split_q1_r1[simp]: "\<lbrakk> wf_graph g; wf_ruleschema (fst r1)\<rbrakk> \<Longrightarrow> eval g undefined (Split q1 (fst r1) \<lceil>\<longleftrightarrow>\<rceil>
  (\<lceil>\<not>\<rceil>(\<lceil>mark \<lceil>src \<leadsto>\<^sub>E 1\<rceil>\<rceil> \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None \<lceil>\<or>\<rceil>
       \<lceil>mark \<lceil>src \<leadsto>\<^sub>E 2\<rceil>\<rceil> \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None \<lceil>\<or>\<rceil>
        (\<lceil>\<exists> 0 : Edge\<rceil> (\<langle>0\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>E 1 \<lceil>\<and>\<rceil> \<langle>0\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>E 2 \<lceil>\<and>\<rceil>
          ((\<lceil>src \<langle>0\<rangle>\<rceil> \<lceil>=\<rceil> \<leadsto>\<^sub>V 1 \<lceil>\<and>\<rceil> \<lceil>mark \<leadsto>\<^sub>V 1\<rceil> \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None)
          \<lceil>\<or>\<rceil> (\<lceil>src \<langle>0\<rangle>\<rceil> \<lceil>=\<rceil> \<leadsto>\<^sub>V 2 \<lceil>\<and>\<rceil> \<lceil>mark \<leadsto>\<^sub>V 2\<rceil> \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None)
          \<lceil>\<or>\<rceil> (\<lceil>src \<langle>0\<rangle>\<rceil> \<lceil>=\<rceil> \<leadsto>\<^sub>V 3 \<lceil>\<and>\<rceil> \<lceil>mark \<leadsto>\<^sub>V 3\<rceil> \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None)
          \<lceil>\<or>\<rceil> (\<lceil>src \<langle>0\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 1 \<lceil>\<and>\<rceil> \<lceil>src \<langle>0\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 2 \<lceil>\<and>\<rceil>
            \<lceil>src \<langle>0\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 3 \<lceil>\<and>\<rceil> \<lceil>mark \<lceil>src \<langle>0\<rangle>\<rceil>\<rceil> \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None)))))))"
  apply (code_simp)
  apply auto
  apply(simp_all add: r1_def q1_def)
  apply (rule conjI)
   apply (rule impI)+
  apply (simp add: dom_def)
  apply (drule spec)
   apply (metis (no_types, lifting))
  apply (simp add: dom_def)
  by blast
 *)

lemma "\<lbrakk> wf_graph g; wf_ruleschema (fst r2)\<rbrakk> \<Longrightarrow> eval g undefined ((Split q2 (fst r2)) \<lceil>\<longleftrightarrow>\<rceil>
  (\<lceil>unrooted \<leadsto>\<^sub>V 1\<rceil> \<lceil>\<or>\<rceil> (\<lceil>\<exists> 0 : Node\<rceil> (\<langle>0\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 1 \<lceil>\<and>\<rceil> \<lceil>unrooted \<langle>0\<rangle>\<rceil>))))"
  apply code_simp
  by auto

lemma "eval g undefined (\<triangleright>\<^sub>V RuleMarkNode_None \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None) \<Longrightarrow> False"
  by simp

lemma "eval g undefined ((Val (Split q1 (fst r1)) (fst r1))  \<lceil>\<longrightarrow>\<rceil>
  (\<lceil>\<not>\<rceil>(\<lceil>\<exists>x : Edge\<rceil> (\<langle>x\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>E 1 \<lceil>\<and>\<rceil> \<langle>x\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>E 2 \<lceil>\<and>\<rceil>
        \<lceil>src \<langle>x\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 1 \<lceil>\<and>\<rceil> \<lceil>src \<langle>x\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 2 \<lceil>\<and>\<rceil> \<lceil>src \<langle>x\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 3 \<lceil>\<and>\<rceil> \<lceil>mark \<lceil>src \<langle>x\<rangle>\<rceil>\<rceil> \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None))))"
  apply code_simp
  by auto

lemma "\<lbrakk> wf_graph g; wf_ruleschema (fst r1)\<rbrakk> \<Longrightarrow> eval g undefined (Val (Split q1 (fst r1)) (fst r1)  \<lceil>\<longleftrightarrow>\<rceil>
  (\<lceil>\<not>\<rceil> (\<lceil>\<exists> x : Edge\<rceil> (\<langle>x\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>E 1 \<lceil>\<and>\<rceil> \<langle>x\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>E 2 \<lceil>\<and>\<rceil>
    (\<lceil>src \<langle>x\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 1 \<lceil>\<and>\<rceil> \<lceil>src \<langle>x\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 2 \<lceil>\<and>\<rceil> \<lceil>src \<langle>x\<rangle>\<rceil> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 3 \<lceil>\<and>\<rceil>
     \<lceil>mark \<lceil>src \<langle>x\<rangle>\<rceil>\<rceil> \<lceil>\<noteq>\<rceil> \<triangleright>\<^sub>V RuleMarkNode_None)))))"
  apply code_simp
  by auto

lemma "eval g undefined (Val (Split q2 (fst r2)) (fst r2) \<lceil>\<longleftrightarrow>\<rceil>
  (\<lceil>\<exists> x : Node\<rceil> (\<langle>x\<rangle> \<lceil>\<noteq>\<rceil> \<leadsto>\<^sub>V 1 \<lceil>\<and>\<rceil> \<lceil>unrooted \<langle>x\<rangle>\<rceil>)))"
  apply code_simp
  by auto

(* Definition 45 *)
(* \<comment> \<open>Missing condition, add Dang \<lceil>\<and>\<rceil> condition\<close>
fun App :: "rule \<Rightarrow> form" where
"App (rs, c) = Var1 (Spec (rule_lhs rs) (rule_ty rs) \<lceil>\<and>\<rceil> (Dang rs))"
 *)

(* Definition 46 *)
(* function (sequential)
      Slp     :: "form \<Rightarrow> com \<Rightarrow> form"
  and Pre     :: "com \<Rightarrow> form \<Rightarrow> form"
  and Success :: "com \<Rightarrow> form"
  and Fail    :: "com \<Rightarrow> form"
  where
  "Slp c (RuleSet rs) = foldr (\<lambda>a b. Post c (a\<^sup>\<or>) \<lceil>\<or>\<rceil> b) (set_to_list rs) F"
| "Pre (RuleSet rs) c = T"
| "Success (RuleSet rs) = foldr (\<lambda>a b. (App a) \<lceil>\<or>\<rceil> b) (set_to_list rs) F"
| "Fail (RuleSet rs) = (\<lceil>\<not>\<rceil> (Success (RuleSet rs)))"

| "Slp c (P OR Q) = (Slp c P \<lceil>\<or>\<rceil> Slp c Q)"
| "Pre (P OR Q) c = (Pre P c \<lceil>\<or>\<rceil> Pre Q c)"
| "Success (P OR Q) = (Success P \<lceil>\<or>\<rceil> Success Q)"
| "Fail (P OR Q) = (Fail P \<lceil>\<or>\<rceil> Success Q)"

| "Slp c (P ;; Q) = Slp (Slp c P) Q"
| "Pre (P ;; Q) c = Pre P (Pre Q c)"
| "Success (P ;; Q) = Pre P (Success Q)"
| "Fail (P ;; Q) = (Fail P \<lceil>\<or>\<rceil> Pre P (Fail Q))"

| "Slp c (IF C THEN P ELSE Q) = (Slp (c \<lceil>\<and>\<rceil> Success C) P \<lceil>\<or>\<rceil> Slp (c \<lceil>\<and>\<rceil> Fail C) Q)"
| "Pre (IF C THEN P ELSE Q) c = ((Success C \<lceil>\<and>\<rceil> Pre P c) \<lceil>\<or>\<rceil> (Fail C \<lceil>\<and>\<rceil> Pre Q c))"
| "Success (IF C THEN P ELSE Q) = ((Success C \<lceil>\<and>\<rceil> Success P) \<lceil>\<or>\<rceil> (Fail C \<lceil>\<and>\<rceil> Success Q))"
| "Fail (IF C THEN P ELSE Q) = ((Success C \<lceil>\<and>\<rceil> Fail P) \<lceil>\<or>\<rceil> (Fail C \<lceil>\<and>\<rceil> Fail Q))"

| "Slp c (TRY C THEN P ELSE Q) = ((Slp (c \<lceil>\<and>\<rceil> Success C) (C ;; P)) \<lceil>\<or>\<rceil> Slp (c \<lceil>\<and>\<rceil> Fail C) Q)"
| "Pre (TRY C THEN P ELSE Q) c = ((Pre C (Pre P c)) \<lceil>\<or>\<rceil> (Fail C \<lceil>\<and>\<rceil> Pre Q c))"
| "Success (TRY C THEN P ELSE Q) = (Pre C (Success P) \<lceil>\<or>\<rceil> (Fail C \<lceil>\<and>\<rceil> Success Q))"
| "Fail (TRY C THEN P ELSE Q) = (Pre C (Fail P) \<lceil>\<or>\<rceil> (Fail C \<lceil>\<and>\<rceil> Fail Q))"

| "Slp _ _ = F"
| "Pre _ _ = F"
| "Success _ = F"
| "Fail _ = undefined"
  by pat_completeness auto termination by size_change
 *)
(* Definition 43 *)
(* fun Break :: "form \<Rightarrow> com \<Rightarrow> form \<Rightarrow> form" where
"Break _ _ _ = T"
 *)

(*
(* Lemma 17 *)
fun Wlp :: "rule \<Rightarrow> form \<Rightarrow> form" where
"Wlp r d = (\<lceil>\<not>\<rceil>(Slp (\<lceil>\<not>\<rceil>d) (RuleApp r)))"
 *)
(*
inductive
  hoare :: "form \<Rightarrow> com \<Rightarrow> form \<Rightarrow> bool" ("\<turnstile> ({(1_)}/ (_)/ {(1_)})" 51)
where
  Ruleapp_slp: "\<turnstile> {c} RuleApp r {Slp c (RuleSet {r})}" |

  Ruleapp_wlp: "\<turnstile> {Wlp r d} RuleApp r {d}" |

  Ruleset: "\<lbrakk>\<forall>r \<in> rs. \<turnstile> {c} RuleApp r {d}\<rbrakk>
            \<Longrightarrow> \<turnstile> {c} RuleSet rs {d}" |

  Skip: "\<turnstile> {c} Skip {c}" |

  Comp: "\<lbrakk>\<turnstile> {c} P {e}; \<turnstile> {e} Q {d} \<rbrakk>
         \<Longrightarrow> \<turnstile> {c} P;;Q {d}" |

  Cons: "\<lbrakk>\<turnstile> {c'} P {d'}; eval g undefined (c \<lceil>\<longrightarrow>\<rceil> c');  eval g undefined (d' \<lceil>\<longrightarrow>\<rceil> d)\<rbrakk>
         \<Longrightarrow> \<turnstile> {c} P {d}" |

  If: "\<lbrakk>\<turnstile> {c \<lceil>\<and>\<rceil> Success C} P {d}; \<turnstile> {c \<lceil>\<and>\<rceil> Fail C} Q {d}\<rbrakk>
       \<Longrightarrow> \<turnstile> {c} IF C THEN P ELSE Q {d}" |

  Try: "\<lbrakk> \<turnstile> {c \<lceil>\<and>\<rceil> Success C} C;;P {d}; \<turnstile> {c \<lceil>\<and>\<rceil> Fail C} Q {d}\<rbrakk>
        \<Longrightarrow> \<turnstile> {c} TRY C THEN P ELSE Q {d}" |

  Alap: "\<lbrakk>\<turnstile> {c} C {c}; eval g undefined (Break c C d)\<rbrakk>
         \<Longrightarrow> \<turnstile> {c} C! {(c \<lceil>\<and>\<rceil> Fail C) \<lceil>\<or>\<rceil> d}" *)

end


(*  Title:      HOL/Statespace/StateSpaceEx.thy
    Author:     Norbert Schirmer, TU Muenchen, 2007
    Author:     Norbert Schirmer, Apple, 2021
*)

section \<open>Examples \label{sec:Examples}\<close>
theory StateSpaceEx
imports StateSpaceLocale StateSpaceSyntax
begin

(*<*)
syntax
 "_statespace_updates" :: "('a \<Rightarrow> 'b) \<Rightarrow> updbinds \<Rightarrow> ('a \<Rightarrow> 'b)" ("_\<langle>_\<rangle>" [900,0] 900)
(*>*)

text \<open>Did you ever dream about records with multiple inheritance?
Then you should definitely have a look at statespaces. They may be
what you are dreaming of. Or at least almost \dots\<close>

text \<open>Isabelle allows to add new top-level commands to the
system. Building on the locale infrastructure, we provide a command
\<^theory_text>\<open>statespace\<close> like this:\<close>

statespace vars =
  n::nat
  b::bool

print_locale vars_namespace
print_locale vars_valuetypes
print_locale vars

text \<open>\noindent This resembles a \<^theory_text>\<open>record\<close> definition,
but introduces sophisticated locale
infrastructure instead of HOL type schemes. The resulting context
postulates two distinct names \<^term>\<open>n\<close> and \<^term>\<open>b\<close> and
projection~/ injection functions that convert from abstract values to
\<^typ>\<open>nat\<close> and \<open>bool\<close>. The logical content of the locale is:\<close>

locale vars' =
  fixes n::'name and b::'name
  assumes "distinct [n, b]"

  fixes project_nat::"'value \<Rightarrow> nat" and inject_nat::"nat \<Rightarrow> 'value"
  assumes "\<And>n. project_nat (inject_nat n) = n"

  fixes project_bool::"'value \<Rightarrow> bool" and inject_bool::"bool \<Rightarrow> 'value"
  assumes "\<And>b. project_bool (inject_bool b) = b"

text \<open>\noindent The HOL predicate \<^const>\<open>distinct\<close> describes
distinctness of all names in the context.  Locale \<open>vars'\<close>
defines the raw logical content that is defined in the state space
locale. We also maintain non-logical context information to support
the user:

\<^item> Syntax for state lookup and updates that automatically inserts
the corresponding projection and injection functions.
\<^item> Setup for the proof tools that exploit the distinctness
information and the cancellation of projections and injections in
deductions and simplifications.

This extra-logical information is added to the locale in form of
declarations, which associate the name of a variable to the
corresponding projection and injection functions to handle the syntax
transformations, and a link from the variable name to the
corresponding distinctness theorem. As state spaces are merged or
extended there are multiple distinctness theorems in the context. Our
declarations take care that the link always points to the strongest
distinctness assumption.  With these declarations in place, a lookup
can be written as \<open>s\<cdot>n\<close>, which is translated to \<open>project_nat (s n)\<close>, and an
update as \<open>s\<langle>n := 2\<rangle>\<close>, which is translated to \<open>s(n := inject_nat 2)\<close>.
We can now establish the
following lemma:\<close>

lemma (in vars) foo: "s<n := 2>\<cdot>b = s\<cdot>b" by simp

text \<open>\noindent Here the simplifier was able to refer to
distinctness of \<^term>\<open>b\<close> and \<^term>\<open>n\<close> to solve the equation.
The resulting lemma is also recorded in locale \<open>vars\<close> for
later use and is automatically propagated to all its interpretations.
Here is another example:\<close>

statespace 'a varsX = NB: vars [n=N, b=B] + vars + x::'a

text \<open>\noindent The state space \<open>varsX\<close> imports two copies
of the state space \<open>vars\<close>, where one has the variables renamed
to upper-case letters, and adds another variable \<^term>\<open>x\<close> of type
\<^typ>\<open>'a\<close>. This type is fixed inside the state space but may get
instantiated later on, analogous to type parameters of an ML-functor.
The distinctness assumption is now \<open>distinct [N, B, n, b, x]\<close>,
from this we can derive both \<^term>\<open>distinct [N,B]\<close> and \<^term>\<open>distinct [n,b]\<close>,
the distinction assumptions for the two versions of
locale \<open>vars\<close> above.  Moreover we have all necessary
projection and injection assumptions available. These assumptions
together allow us to establish state space \<^term>\<open>varsX\<close> as an
interpretation of both instances of locale \<^term>\<open>vars\<close>. Hence we
inherit both variants of theorem \<open>foo\<close>: \<open>s\<langle>N := 2\<rangle>\<cdot>B =
s\<cdot>B\<close> as well as \<open>s\<langle>n := 2\<rangle>\<cdot>b = s\<cdot>b\<close>. These are immediate
consequences of the locale interpretation action.

The declarations for syntax and the distinctness theorems also observe
the morphisms generated by the locale package due to the renaming
\<^term>\<open>n = N\<close>:\<close>

lemma (in varsX) foo: "s\<langle>N := 2\<rangle>\<cdot>x = s\<cdot>x" by simp

text \<open>To assure scalability towards many distinct names, the
distinctness predicate is refined to operate on balanced trees. Thus
we get logarithmic certificates for the distinctness of two names by
the distinctness of the paths in the tree. Asked for the distinctness
of two names, our tool produces the paths of the variables in the tree
(this is implemented in Isabelle/ML, outside the logic) and returns a
certificate corresponding to the different paths. Merging state
spaces requires to prove that the combined distinctness assumption
implies the distinctness assumptions of the components.  Such a proof
is of the order $m \cdot \log n$, where $n$ and $m$ are the number of
nodes in the larger and smaller tree, respectively.\<close>

text \<open>We continue with more examples.\<close>

statespace 'a foo =
  f::"nat\<Rightarrow>nat"
  a::int
  b::nat
  c::'a

lemma (in foo) foo1:
  shows "s\<langle>a := i\<rangle>\<cdot>a = i"
  by simp

lemma (in foo) foo2:
  shows "(s\<langle>a:=i\<rangle>)\<cdot>a = i"
  by simp

lemma (in foo) foo3:
  shows "(s\<langle>a:=i\<rangle>)\<cdot>b = s\<cdot>b"
  by simp

lemma (in foo) foo4:
  shows "(s\<langle>a:=i,b:=j,c:=k,a:=x\<rangle>) = (s\<langle>b:=j,c:=k,a:=x\<rangle>)"
  by simp

statespace bar =
  b::bool
  c::string

lemma (in bar) bar1:
  shows "(s\<langle>b:=True\<rangle>)\<cdot>c = s\<cdot>c"
  by simp

text \<open>You can define a derived state space by inheriting existing state spaces, renaming
of components if you like, and by declaring new components.
\<close>

statespace ('a,'b) loo = 'a foo + bar [b=B,c=C] +
  X::'b

lemma (in loo) loo1:
  shows "s\<langle>a:=i\<rangle>\<cdot>B = s\<cdot>B"
proof -
  thm foo1
  txt \<open>The Lemma @{thm [source] foo1} from the parent state space
         is also available here: \begin{center}@{thm foo1}\end{center}\<close>
  have "s<a:=i>\<cdot>a = i"
    by (rule foo1)
  thm bar1
  txt \<open>Note the renaming of the parameters in Lemma @{thm [source] bar1}:
         \begin{center}@{thm bar1}\end{center}\<close>
  have "s<B:=True>\<cdot>C = s\<cdot>C"
    by (rule bar1)
  show ?thesis
    by simp
qed

statespace 'a dup = FA: 'a foo [f=F, a=A] + 'a foo +
  x::int

lemma (in dup)
 shows "s<a := i>\<cdot>x = s\<cdot>x"
  by simp

lemma (in dup)
 shows "s<A := i>\<cdot>a = s\<cdot>a"
  by simp

lemma (in dup)
 shows "s<A := i>\<cdot>x = s\<cdot>x"
  by simp

text \<open>There were known problems with syntax-declarations. They only
worked when the context is already completely built. This is now overcome. e.g.:\<close>

locale fooX = foo +
 assumes "s<a:=i>\<cdot>b = k"

text \<open>
We can also put statespaces side-by-side by using ordinary @{command locale} expressions
(instead of the @{command statespace}).
\<close>

locale side_by_side = foo + bar where b="B::'a" and c=C for B C

context side_by_side
begin
text \<open>Simplification within one of the statespaces works as expected.\<close>
lemma "s<B := i>\<cdot>C = s\<cdot>C"
  by simp

lemma "s<a := i>\<cdot>b = s\<cdot>b"
  by simp

text \<open>In contrast to the statespace @{locale loo} there is no 'inter' statespace distinctness
between the names of @{locale foo} and @{locale bar}.\<close>
end

text \<open>Sharing of names in side-by-side statespaces is also possible as long as they are mapped
to the same type.\<close>

statespace vars1 = n::nat m::nat
statespace vars2 = n::nat k::nat

locale vars1_vars2 = vars1 + vars2

context vars1_vars2
begin

text \<open>Note that the distinctness theorem for @{locale vars1} is selected here to do the proof.\<close>
lemma "s<n := i>\<cdot>m = s\<cdot>m"
  by simp

text \<open>Note that the distinctness theorem for @{locale vars2} is selected here to do the proof.\<close>
lemma "s<n := i>\<cdot>k = s\<cdot>k"
  by simp

text \<open>Still there is no inter-statespace distinctness.\<close>
lemma "s<k := i>\<cdot>m = s\<cdot>m"
  (* apply simp *)
  oops
end

statespace merge_vars1_vars2 = vars1 + vars2

context merge_vars1_vars2
begin
text \<open>When defining a statespace instead of a side-by-side locale we get the distinctness of
all variables.\<close>
lemma "s<k := i>\<cdot>m = s\<cdot>m"
  by simp
end

subsection \<open>Benchmarks\<close>

text \<open>Here are some bigger examples for benchmarking.\<close>

ML \<open>
  fun make_benchmark n =
    writeln (Active.sendback_markup_command
      ("statespace benchmark" ^ string_of_int n ^ " =\n" ^
        (cat_lines (map (fn i => "A" ^ string_of_int i ^ "::nat") (1 upto n)))));
\<close>

text "0.2s"
statespace benchmark100 = A1::nat A2::nat A3::nat A4::nat A5::nat
A6::nat A7::nat A8::nat A9::nat A10::nat A11::nat A12::nat A13::nat
A14::nat A15::nat A16::nat A17::nat A18::nat A19::nat A20::nat
A21::nat A22::nat A23::nat A24::nat A25::nat A26::nat A27::nat
A28::nat A29::nat A30::nat A31::nat A32::nat A33::nat A34::nat
A35::nat A36::nat A37::nat A38::nat A39::nat A40::nat A41::nat
A42::nat A43::nat A44::nat A45::nat A46::nat A47::nat A48::nat
A49::nat A50::nat A51::nat A52::nat A53::nat A54::nat A55::nat
A56::nat A57::nat A58::nat A59::nat A60::nat A61::nat A62::nat
A63::nat A64::nat A65::nat A66::nat A67::nat A68::nat A69::nat
A70::nat A71::nat A72::nat A73::nat A74::nat A75::nat A76::nat
A77::nat A78::nat A79::nat A80::nat A81::nat A82::nat A83::nat
A84::nat A85::nat A86::nat A87::nat A88::nat A89::nat A90::nat
A91::nat A92::nat A93::nat A94::nat A95::nat A96::nat A97::nat
A98::nat A99::nat A100::nat

text "2.4s"
statespace benchmark500 = A1::nat A2::nat A3::nat A4::nat A5::nat
A6::nat A7::nat A8::nat A9::nat A10::nat A11::nat A12::nat A13::nat
A14::nat A15::nat A16::nat A17::nat A18::nat A19::nat A20::nat
A21::nat A22::nat A23::nat A24::nat A25::nat A26::nat A27::nat
A28::nat A29::nat A30::nat A31::nat A32::nat A33::nat A34::nat
A35::nat A36::nat A37::nat A38::nat A39::nat A40::nat A41::nat
A42::nat A43::nat A44::nat A45::nat A46::nat A47::nat A48::nat
A49::nat A50::nat A51::nat A52::nat A53::nat A54::nat A55::nat
A56::nat A57::nat A58::nat A59::nat A60::nat A61::nat A62::nat
A63::nat A64::nat A65::nat A66::nat A67::nat A68::nat A69::nat
A70::nat A71::nat A72::nat A73::nat A74::nat A75::nat A76::nat
A77::nat A78::nat A79::nat A80::nat A81::nat A82::nat A83::nat
A84::nat A85::nat A86::nat A87::nat A88::nat A89::nat A90::nat
A91::nat A92::nat A93::nat A94::nat A95::nat A96::nat A97::nat
A98::nat A99::nat A100::nat A101::nat A102::nat A103::nat A104::nat
A105::nat A106::nat A107::nat A108::nat A109::nat A110::nat A111::nat
A112::nat A113::nat A114::nat A115::nat A116::nat A117::nat A118::nat
A119::nat A120::nat A121::nat A122::nat A123::nat A124::nat A125::nat
A126::nat A127::nat A128::nat A129::nat A130::nat A131::nat A132::nat
A133::nat A134::nat A135::nat A136::nat A137::nat A138::nat A139::nat
A140::nat A141::nat A142::nat A143::nat A144::nat A145::nat A146::nat
A147::nat A148::nat A149::nat A150::nat A151::nat A152::nat A153::nat
A154::nat A155::nat A156::nat A157::nat A158::nat A159::nat A160::nat
A161::nat A162::nat A163::nat A164::nat A165::nat A166::nat A167::nat
A168::nat A169::nat A170::nat A171::nat A172::nat A173::nat A174::nat
A175::nat A176::nat A177::nat A178::nat A179::nat A180::nat A181::nat
A182::nat A183::nat A184::nat A185::nat A186::nat A187::nat A188::nat
A189::nat A190::nat A191::nat A192::nat A193::nat A194::nat A195::nat
A196::nat A197::nat A198::nat A199::nat A200::nat A201::nat A202::nat
A203::nat A204::nat A205::nat A206::nat A207::nat A208::nat A209::nat
A210::nat A211::nat A212::nat A213::nat A214::nat A215::nat A216::nat
A217::nat A218::nat A219::nat A220::nat A221::nat A222::nat A223::nat
A224::nat A225::nat A226::nat A227::nat A228::nat A229::nat A230::nat
A231::nat A232::nat A233::nat A234::nat A235::nat A236::nat A237::nat
A238::nat A239::nat A240::nat A241::nat A242::nat A243::nat A244::nat
A245::nat A246::nat A247::nat A248::nat A249::nat A250::nat A251::nat
A252::nat A253::nat A254::nat A255::nat A256::nat A257::nat A258::nat
A259::nat A260::nat A261::nat A262::nat A263::nat A264::nat A265::nat
A266::nat A267::nat A268::nat A269::nat A270::nat A271::nat A272::nat
A273::nat A274::nat A275::nat A276::nat A277::nat A278::nat A279::nat
A280::nat A281::nat A282::nat A283::nat A284::nat A285::nat A286::nat
A287::nat A288::nat A289::nat A290::nat A291::nat A292::nat A293::nat
A294::nat A295::nat A296::nat A297::nat A298::nat A299::nat A300::nat
A301::nat A302::nat A303::nat A304::nat A305::nat A306::nat A307::nat
A308::nat A309::nat A310::nat A311::nat A312::nat A313::nat A314::nat
A315::nat A316::nat A317::nat A318::nat A319::nat A320::nat A321::nat
A322::nat A323::nat A324::nat A325::nat A326::nat A327::nat A328::nat
A329::nat A330::nat A331::nat A332::nat A333::nat A334::nat A335::nat
A336::nat A337::nat A338::nat A339::nat A340::nat A341::nat A342::nat
A343::nat A344::nat A345::nat A346::nat A347::nat A348::nat A349::nat
A350::nat A351::nat A352::nat A353::nat A354::nat A355::nat A356::nat
A357::nat A358::nat A359::nat A360::nat A361::nat A362::nat A363::nat
A364::nat A365::nat A366::nat A367::nat A368::nat A369::nat A370::nat
A371::nat A372::nat A373::nat A374::nat A375::nat A376::nat A377::nat
A378::nat A379::nat A380::nat A381::nat A382::nat A383::nat A384::nat
A385::nat A386::nat A387::nat A388::nat A389::nat A390::nat A391::nat
A392::nat A393::nat A394::nat A395::nat A396::nat A397::nat A398::nat
A399::nat A400::nat A401::nat A402::nat A403::nat A404::nat A405::nat
A406::nat A407::nat A408::nat A409::nat A410::nat A411::nat A412::nat
A413::nat A414::nat A415::nat A416::nat A417::nat A418::nat A419::nat
A420::nat A421::nat A422::nat A423::nat A424::nat A425::nat A426::nat
A427::nat A428::nat A429::nat A430::nat A431::nat A432::nat A433::nat
A434::nat A435::nat A436::nat A437::nat A438::nat A439::nat A440::nat
A441::nat A442::nat A443::nat A444::nat A445::nat A446::nat A447::nat
A448::nat A449::nat A450::nat A451::nat A452::nat A453::nat A454::nat
A455::nat A456::nat A457::nat A458::nat A459::nat A460::nat A461::nat
A462::nat A463::nat A464::nat A465::nat A466::nat A467::nat A468::nat
A469::nat A470::nat A471::nat A472::nat A473::nat A474::nat A475::nat
A476::nat A477::nat A478::nat A479::nat A480::nat A481::nat A482::nat
A483::nat A484::nat A485::nat A486::nat A487::nat A488::nat A489::nat
A490::nat A491::nat A492::nat A493::nat A494::nat A495::nat A496::nat
A497::nat A498::nat A499::nat A500::nat

text "9.0s"
statespace benchmark1000 = A1::nat A2::nat A3::nat A4::nat A5::nat
A6::nat A7::nat A8::nat A9::nat A10::nat A11::nat A12::nat A13::nat
A14::nat A15::nat A16::nat A17::nat A18::nat A19::nat A20::nat
A21::nat A22::nat A23::nat A24::nat A25::nat A26::nat A27::nat
A28::nat A29::nat A30::nat A31::nat A32::nat A33::nat A34::nat
A35::nat A36::nat A37::nat A38::nat A39::nat A40::nat A41::nat
A42::nat A43::nat A44::nat A45::nat A46::nat A47::nat A48::nat
A49::nat A50::nat A51::nat A52::nat A53::nat A54::nat A55::nat
A56::nat A57::nat A58::nat A59::nat A60::nat A61::nat A62::nat
A63::nat A64::nat A65::nat A66::nat A67::nat A68::nat A69::nat
A70::nat A71::nat A72::nat A73::nat A74::nat A75::nat A76::nat
A77::nat A78::nat A79::nat A80::nat A81::nat A82::nat A83::nat
A84::nat A85::nat A86::nat A87::nat A88::nat A89::nat A90::nat
A91::nat A92::nat A93::nat A94::nat A95::nat A96::nat A97::nat
A98::nat A99::nat A100::nat A101::nat A102::nat A103::nat A104::nat
A105::nat A106::nat A107::nat A108::nat A109::nat A110::nat A111::nat
A112::nat A113::nat A114::nat A115::nat A116::nat A117::nat A118::nat
A119::nat A120::nat A121::nat A122::nat A123::nat A124::nat A125::nat
A126::nat A127::nat A128::nat A129::nat A130::nat A131::nat A132::nat
A133::nat A134::nat A135::nat A136::nat A137::nat A138::nat A139::nat
A140::nat A141::nat A142::nat A143::nat A144::nat A145::nat A146::nat
A147::nat A148::nat A149::nat A150::nat A151::nat A152::nat A153::nat
A154::nat A155::nat A156::nat A157::nat A158::nat A159::nat A160::nat
A161::nat A162::nat A163::nat A164::nat A165::nat A166::nat A167::nat
A168::nat A169::nat A170::nat A171::nat A172::nat A173::nat A174::nat
A175::nat A176::nat A177::nat A178::nat A179::nat A180::nat A181::nat
A182::nat A183::nat A184::nat A185::nat A186::nat A187::nat A188::nat
A189::nat A190::nat A191::nat A192::nat A193::nat A194::nat A195::nat
A196::nat A197::nat A198::nat A199::nat A200::nat A201::nat A202::nat
A203::nat A204::nat A205::nat A206::nat A207::nat A208::nat A209::nat
A210::nat A211::nat A212::nat A213::nat A214::nat A215::nat A216::nat
A217::nat A218::nat A219::nat A220::nat A221::nat A222::nat A223::nat
A224::nat A225::nat A226::nat A227::nat A228::nat A229::nat A230::nat
A231::nat A232::nat A233::nat A234::nat A235::nat A236::nat A237::nat
A238::nat A239::nat A240::nat A241::nat A242::nat A243::nat A244::nat
A245::nat A246::nat A247::nat A248::nat A249::nat A250::nat A251::nat
A252::nat A253::nat A254::nat A255::nat A256::nat A257::nat A258::nat
A259::nat A260::nat A261::nat A262::nat A263::nat A264::nat A265::nat
A266::nat A267::nat A268::nat A269::nat A270::nat A271::nat A272::nat
A273::nat A274::nat A275::nat A276::nat A277::nat A278::nat A279::nat
A280::nat A281::nat A282::nat A283::nat A284::nat A285::nat A286::nat
A287::nat A288::nat A289::nat A290::nat A291::nat A292::nat A293::nat
A294::nat A295::nat A296::nat A297::nat A298::nat A299::nat A300::nat
A301::nat A302::nat A303::nat A304::nat A305::nat A306::nat A307::nat
A308::nat A309::nat A310::nat A311::nat A312::nat A313::nat A314::nat
A315::nat A316::nat A317::nat A318::nat A319::nat A320::nat A321::nat
A322::nat A323::nat A324::nat A325::nat A326::nat A327::nat A328::nat
A329::nat A330::nat A331::nat A332::nat A333::nat A334::nat A335::nat
A336::nat A337::nat A338::nat A339::nat A340::nat A341::nat A342::nat
A343::nat A344::nat A345::nat A346::nat A347::nat A348::nat A349::nat
A350::nat A351::nat A352::nat A353::nat A354::nat A355::nat A356::nat
A357::nat A358::nat A359::nat A360::nat A361::nat A362::nat A363::nat
A364::nat A365::nat A366::nat A367::nat A368::nat A369::nat A370::nat
A371::nat A372::nat A373::nat A374::nat A375::nat A376::nat A377::nat
A378::nat A379::nat A380::nat A381::nat A382::nat A383::nat A384::nat
A385::nat A386::nat A387::nat A388::nat A389::nat A390::nat A391::nat
A392::nat A393::nat A394::nat A395::nat A396::nat A397::nat A398::nat
A399::nat A400::nat A401::nat A402::nat A403::nat A404::nat A405::nat
A406::nat A407::nat A408::nat A409::nat A410::nat A411::nat A412::nat
A413::nat A414::nat A415::nat A416::nat A417::nat A418::nat A419::nat
A420::nat A421::nat A422::nat A423::nat A424::nat A425::nat A426::nat
A427::nat A428::nat A429::nat A430::nat A431::nat A432::nat A433::nat
A434::nat A435::nat A436::nat A437::nat A438::nat A439::nat A440::nat
A441::nat A442::nat A443::nat A444::nat A445::nat A446::nat A447::nat
A448::nat A449::nat A450::nat A451::nat A452::nat A453::nat A454::nat
A455::nat A456::nat A457::nat A458::nat A459::nat A460::nat A461::nat
A462::nat A463::nat A464::nat A465::nat A466::nat A467::nat A468::nat
A469::nat A470::nat A471::nat A472::nat A473::nat A474::nat A475::nat
A476::nat A477::nat A478::nat A479::nat A480::nat A481::nat A482::nat
A483::nat A484::nat A485::nat A486::nat A487::nat A488::nat A489::nat
A490::nat A491::nat A492::nat A493::nat A494::nat A495::nat A496::nat
A497::nat A498::nat A499::nat A500::nat A501::nat A502::nat A503::nat
A504::nat A505::nat A506::nat A507::nat A508::nat A509::nat A510::nat
A511::nat A512::nat A513::nat A514::nat A515::nat A516::nat A517::nat
A518::nat A519::nat A520::nat A521::nat A522::nat A523::nat A524::nat
A525::nat A526::nat A527::nat A528::nat A529::nat A530::nat A531::nat
A532::nat A533::nat A534::nat A535::nat A536::nat A537::nat A538::nat
A539::nat A540::nat A541::nat A542::nat A543::nat A544::nat A545::nat
A546::nat A547::nat A548::nat A549::nat A550::nat A551::nat A552::nat
A553::nat A554::nat A555::nat A556::nat A557::nat A558::nat A559::nat
A560::nat A561::nat A562::nat A563::nat A564::nat A565::nat A566::nat
A567::nat A568::nat A569::nat A570::nat A571::nat A572::nat A573::nat
A574::nat A575::nat A576::nat A577::nat A578::nat A579::nat A580::nat
A581::nat A582::nat A583::nat A584::nat A585::nat A586::nat A587::nat
A588::nat A589::nat A590::nat A591::nat A592::nat A593::nat A594::nat
A595::nat A596::nat A597::nat A598::nat A599::nat A600::nat A601::nat
A602::nat A603::nat A604::nat A605::nat A606::nat A607::nat A608::nat
A609::nat A610::nat A611::nat A612::nat A613::nat A614::nat A615::nat
A616::nat A617::nat A618::nat A619::nat A620::nat A621::nat A622::nat
A623::nat A624::nat A625::nat A626::nat A627::nat A628::nat A629::nat
A630::nat A631::nat A632::nat A633::nat A634::nat A635::nat A636::nat
A637::nat A638::nat A639::nat A640::nat A641::nat A642::nat A643::nat
A644::nat A645::nat A646::nat A647::nat A648::nat A649::nat A650::nat
A651::nat A652::nat A653::nat A654::nat A655::nat A656::nat A657::nat
A658::nat A659::nat A660::nat A661::nat A662::nat A663::nat A664::nat
A665::nat A666::nat A667::nat A668::nat A669::nat A670::nat A671::nat
A672::nat A673::nat A674::nat A675::nat A676::nat A677::nat A678::nat
A679::nat A680::nat A681::nat A682::nat A683::nat A684::nat A685::nat
A686::nat A687::nat A688::nat A689::nat A690::nat A691::nat A692::nat
A693::nat A694::nat A695::nat A696::nat A697::nat A698::nat A699::nat
A700::nat A701::nat A702::nat A703::nat A704::nat A705::nat A706::nat
A707::nat A708::nat A709::nat A710::nat A711::nat A712::nat A713::nat
A714::nat A715::nat A716::nat A717::nat A718::nat A719::nat A720::nat
A721::nat A722::nat A723::nat A724::nat A725::nat A726::nat A727::nat
A728::nat A729::nat A730::nat A731::nat A732::nat A733::nat A734::nat
A735::nat A736::nat A737::nat A738::nat A739::nat A740::nat A741::nat
A742::nat A743::nat A744::nat A745::nat A746::nat A747::nat A748::nat
A749::nat A750::nat A751::nat A752::nat A753::nat A754::nat A755::nat
A756::nat A757::nat A758::nat A759::nat A760::nat A761::nat A762::nat
A763::nat A764::nat A765::nat A766::nat A767::nat A768::nat A769::nat
A770::nat A771::nat A772::nat A773::nat A774::nat A775::nat A776::nat
A777::nat A778::nat A779::nat A780::nat A781::nat A782::nat A783::nat
A784::nat A785::nat A786::nat A787::nat A788::nat A789::nat A790::nat
A791::nat A792::nat A793::nat A794::nat A795::nat A796::nat A797::nat
A798::nat A799::nat A800::nat A801::nat A802::nat A803::nat A804::nat
A805::nat A806::nat A807::nat A808::nat A809::nat A810::nat A811::nat
A812::nat A813::nat A814::nat A815::nat A816::nat A817::nat A818::nat
A819::nat A820::nat A821::nat A822::nat A823::nat A824::nat A825::nat
A826::nat A827::nat A828::nat A829::nat A830::nat A831::nat A832::nat
A833::nat A834::nat A835::nat A836::nat A837::nat A838::nat A839::nat
A840::nat A841::nat A842::nat A843::nat A844::nat A845::nat A846::nat
A847::nat A848::nat A849::nat A850::nat A851::nat A852::nat A853::nat
A854::nat A855::nat A856::nat A857::nat A858::nat A859::nat A860::nat
A861::nat A862::nat A863::nat A864::nat A865::nat A866::nat A867::nat
A868::nat A869::nat A870::nat A871::nat A872::nat A873::nat A874::nat
A875::nat A876::nat A877::nat A878::nat A879::nat A880::nat A881::nat
A882::nat A883::nat A884::nat A885::nat A886::nat A887::nat A888::nat
A889::nat A890::nat A891::nat A892::nat A893::nat A894::nat A895::nat
A896::nat A897::nat A898::nat A899::nat A900::nat A901::nat A902::nat
A903::nat A904::nat A905::nat A906::nat A907::nat A908::nat A909::nat
A910::nat A911::nat A912::nat A913::nat A914::nat A915::nat A916::nat
A917::nat A918::nat A919::nat A920::nat A921::nat A922::nat A923::nat
A924::nat A925::nat A926::nat A927::nat A928::nat A929::nat A930::nat
A931::nat A932::nat A933::nat A934::nat A935::nat A936::nat A937::nat
A938::nat A939::nat A940::nat A941::nat A942::nat A943::nat A944::nat
A945::nat A946::nat A947::nat A948::nat A949::nat A950::nat A951::nat
A952::nat A953::nat A954::nat A955::nat A956::nat A957::nat A958::nat
A959::nat A960::nat A961::nat A962::nat A963::nat A964::nat A965::nat
A966::nat A967::nat A968::nat A969::nat A970::nat A971::nat A972::nat
A973::nat A974::nat A975::nat A976::nat A977::nat A978::nat A979::nat
A980::nat A981::nat A982::nat A983::nat A984::nat A985::nat A986::nat
A987::nat A988::nat A989::nat A990::nat A991::nat A992::nat A993::nat
A994::nat A995::nat A996::nat A997::nat A998::nat A999::nat A1000::nat

lemma (in benchmark100) test: "s<A1 := a>\<cdot>A100 = s\<cdot>A100" by simp
lemma (in benchmark500) test: "s<A1 := a>\<cdot>A100 = s\<cdot>A100" by simp
lemma (in benchmark1000) test: "s<A1 := a>\<cdot>A100 = s\<cdot>A100" by simp

end


(*  Title:      HOL/Proofs/ex/Proof_Terms.thy
    Author:     Makarius

Basic examples involving proof terms.
*)

theory Proof_Terms
imports Main
begin

text \<open>
  Detailed proof information of a theorem may be retrieved as follows:
\<close>

lemma ex: "A \<and> B \<longrightarrow> B \<and> A"
proof
  assume "A \<and> B"
  then obtain B and A ..
  then show "B \<and> A" ..
qed

ML_val \<open>
  val thm = @{thm ex};

  (*proof body with digest*)
  val body = Proofterm.strip_thm_body (Thm.proof_body_of thm);

  (*proof term only*)
  val prf = Proofterm.proof_of body;

  (*clean output*)
  Pretty.writeln (Proof_Syntax.pretty_standard_proof_of \<^context> false thm);
  Pretty.writeln (Proof_Syntax.pretty_standard_proof_of \<^context> true thm);

  (*all theorems used in the graph of nested proofs*)
  val all_thms =
    Proofterm.fold_body_thms
      (fn {name, ...} => insert (op =) name) [body] [];
\<close>

text \<open>
  The result refers to various basic facts of Isabelle/HOL: @{thm [source]
  HOL.impI}, @{thm [source] HOL.conjE}, @{thm [source] HOL.conjI} etc. The
  combinator \<^ML>\<open>Proofterm.fold_body_thms\<close> recursively explores the graph of
  the proofs of all theorems being used here.

  \<^medskip>
  Alternatively, we may produce a proof term manually, and turn it into a
  theorem as follows:
\<close>

ML_val \<open>
  val thy = \<^theory>;
  val prf =
    Proof_Syntax.read_proof thy true false
      "impI \<cdot> _ \<cdot> _ \<bullet> \
      \   (\<^bold>\<lambda>H: _. \
      \     conjE \<cdot> _ \<cdot> _ \<cdot> _ \<bullet> H \<bullet> \
      \       (\<^bold>\<lambda>(H: _) Ha: _. conjI \<cdot> _ \<cdot> _ \<bullet> Ha \<bullet> H))";
  val thm =
    Proofterm.reconstruct_proof thy \<^prop>\<open>A \<and> B \<longrightarrow> B \<and> A\<close> prf
    |> Proof_Checker.thm_of_proof thy
    |> Drule.export_without_context;
\<close>

end