text
stringlengths 0
3.34M
|
---|
%
function [map, pose] = AddAKeyScan(map,...
gridMap,...
scan,...
pose,...
hits,...
pixelSize,...
bruteResolution,...
tmax,...
rmax)
% First, evaluate the pose & hits, make sure that there is no large error
lastKeyPose = map.keyscans(end).pose;
dp = DiffPose(lastKeyPose, pose);
if abs(dp(1)) > 0.5 || abs(dp(2)) > 0.5 || abs(dp(3)) > pi
disp('Oh no no no nobody but you : So Large Error!');
pose = lastKeyPose;
end
% ToDo: refine the relative pose, estimate the pose's covariance.
% And push them into the map.connections, which will be neede when we close
% a loop (pose graph optimization).
scan_w = Transform(scan, pose);
newPoints = scan_w(hits>1.1, :);
%
if isempty(newPoints)
return;
end
% keyscans
k = length(map.keyscans);
map.keyscans(k+1).pose = pose;
map.keyscans(k+1).iBegin = size(map.points, 1) + 1;
map.keyscans(k+1).iEnd = size(map.points, 1) + size(newPoints, 1);
map.keyscans(k+1).loopTried = false;
map.keyscans(k+1).loopClosed = false;
% points
map.points = [map.points; newPoints];
% connections
% ToDo: Estimate the relative pose and covariance, they will be useful
% when we close a loop (pose graph optimization).
c = length(map.connections);
map.connections(c+1).keyIdPair = [k, k+1];
map.connections(c+1).relativePose = zeros(3,1);
map.connections(c+1).covariance = zeros(3);
|
/- LoVe Exercise 6: Monads -/
import .love06_monads_demo
namespace LoVe
/- Question 1: A State Monad with Failure -/
open LoVe.lawful_monad
/- We introduce a richer notion of lawful monad that provides an `orelse`
operator `<|>` satisfying some laws, given below. `emp` denotes failure.
`x <|> y` tries `x` first, falling back on `y` on failure. -/
class lawful_monad_with_orelse (m : Type → Type)
extends lawful_monad m, has_orelse m :=
(emp {} {α} : m α)
(emp_orelse {α} (a : m α) :
(emp <|> a) = a)
(orelse_emp {α} (a : m α) :
(a <|> emp) = a)
(orelse_assoc {α} (a b c : m α) :
((a <|> b) <|> c) = (a <|> (b <|> c)))
(emp_bind {α β} (f : α → m β) :
(emp >>= f) = emp)
(bind_emp {α β} (f : m α) :
(f >>= (λa, emp : α → m β)) = emp)
open LoVe.lawful_monad_with_orelse
/- We register the laws as simplification rules: -/
attribute [simp]
LoVe.lawful_monad_with_orelse.emp_orelse
LoVe.lawful_monad_with_orelse.orelse_emp
LoVe.lawful_monad_with_orelse.orelse_assoc
LoVe.lawful_monad_with_orelse.emp_bind
LoVe.lawful_monad_with_orelse.bind_emp
/- 1.1. We set up the `option` type constructor to be a
`lawful_monad_with_orelse`. Complete the proofs. -/
namespace option
/- The following line declares some variables as default arguments to
definitions that refer to them. -/
variables {α β γ : Type}
def orelse {α} : option α → option α → option α
| none b := b
| (some a) _ := some a
instance lawful_monad_with_orelse_option : lawful_monad_with_orelse option :=
{ emp := λα, none,
orelse := @option.orelse,
emp_orelse :=
sorry,
orelse_emp :=
assume α a,
match a with
| some a := by refl
| none := by refl
end,
orelse_assoc :=
sorry,
emp_bind :=
assume α β f,
by refl,
bind_emp :=
sorry,
.. LoVe.option.lawful_monad_option }
@[simp] lemma some_bind (a : α) (g : α → option β) :
(some a >>= g) = g a :=
sorry
end option
/- Let us enable some convenient pattern matching syntax, by instantiating
Lean's `monad_fail` type class. (Do not worry if you do not understand what
we are referring to.) -/
instance {m : Type → Type} [lawful_monad_with_orelse m] : monad_fail m :=
⟨λα msg, emp⟩
/- Now we can write definitions such as the following: -/
def first_of_three {m : Type → Type} [lawful_monad_with_orelse m]
(c : m (list ℕ)) : m ℕ :=
do
[n, _, _] ← c, -- look m, this list has three elements!
pure n
#eval first_of_three (some [1])
#eval first_of_three (some [1, 2, 3])
#eval first_of_three (some [1, 2, 3, 4])
/- Using `lawful_monad_with_orelse` and the `monad_fail` syntax, we can give a
consise definition for the `sum_2_5_7` function seen in the lecture. -/
def sum_2_5_7₇ {m : Type → Type} [lawful_monad_with_orelse m]
(c : m (list ℕ)) : m ℕ :=
do
(_ :: n2 :: _ :: _ :: n5 :: _ :: n7 :: _) ← c,
pure (n2 + n5 + n7)
/- 1.2. Now we are ready to define `fstate σ`: a monad with an internal state of
type `σ` that can fail (unlike `state σ`).
We start with defining `fstate σ α`, where `σ` is the type of the internal
state, and `α` is the type of the value stored in the monad. We use `option` to
model failure. This means we can also use the monadic behvior of `option` when
defining the monadic opertions on `fstate`.
**Hint:** Remember that `fstate σ α` is an alias for a function type, so you can
use pattern matching and `λs, …` to define values of type `fstate σ α`.
**Hint:** `fstate` is very similar to `state` in the lecture demonstration. You
can look there for inspiration. -/
def fstate (σ : Type) (α : Type) :=
σ → option (α × σ)
/- 1.3. Define the `get` and `set` function for `fstate`, where `get` returns
the state passed along the state monad and `set s` changes the state to `s`. -/
def get {σ : Type} : fstate σ σ
:= sorry
def set {σ : Type} (s : σ) : fstate σ unit
:= sorry
namespace fstate
/- The following line declares some variables as default arguments to
definitions that refer to them. -/
variables {σ α β γ : Type}
/- 1.4. Define the monadic operator `pure` for `fstate`, in such a way that it
will satisfy the monadic laws. -/
protected def bind (f : fstate σ α) (g : α → fstate σ β) : fstate σ β
| s := f s >>= function.uncurry g
#check function.uncurry
/- We set up the `>>=` syntax on `fstate`: -/
instance : has_bind (fstate σ) := ⟨@fstate.bind σ⟩
@[simp] lemma bind_apply (f : fstate σ α) (g : α → fstate σ β) (s : σ) :
(f >>= g) s = f s >>= function.uncurry g :=
by refl
protected def pure (a : α) : fstate σ α
:= sorry
/- We set up the syntax for `pure` on `fstate`: -/
instance : has_pure (fstate σ) := ⟨@fstate.pure σ⟩
@[simp] lemma pure_apply (a : α) (s : σ) :
(pure a : fstate σ α) s = some (a, s) :=
by refl
/- 1.3. Register `fstate` as a monad.
**Hint:** `pure` and `bind` are introduced using `protected`, so their names are
`fstate.pure` and `fstate.bind`.
**Hint**: The `funext` lemma is useful when you need to prove equality between
two functions.
**Hint**: Sometimes one invocation of `cases` is not enough. In particular,
`uncurry f p` requires that `p` is a pair of the form `(a, b)`.
**Hint**: `cases f s` only works when `f s` appears in your goal, so you may
need to unfold some constants before you can do a `cases`. -/
instance : lawful_monad (fstate σ) :=
{ pure_bind :=
begin
intros α β a f,
apply funext,
intro s,
refl
end,
bind_pure :=
sorry,
bind_assoc :=
sorry,
.. fstate.has_bind, .. fstate.has_pure }
end fstate
/- Question 2: Kleisli Operator
The kleisly operator `>=>` (not to be confused with `>>=`) is useful for
pipelining monadic operations. -/
open monad
/- The following two lines declare some variables as default arguments to
definitions that refer to them. -/
variables {m : Type → Type} [lawful_monad m] {α β γ δ : Type}
variables {f : α → m β} {g : β → m γ} {h : γ → m δ}
def kleisli (f : α → m β) (g : β → m γ) : (α → m γ) :=
λa, f a >>= g
infixr ` >=> `:90 := kleisli
/- 2.1. Prove that `pure` is a left and right unit for the Kleisli operator. -/
lemma pure_kleisli : pure >=> f = f :=
sorry
lemma kleisli_pure : f >=> pure = f :=
sorry
/- 2.2. Prove associativity of the Kleisli operator. -/
lemma kleisli_assoc : (f >=> g) >=> h = f >=> (g >=> h) :=
sorry
end LoVe
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import group_theory.group_action.conj_act
import group_theory.quotient_group
import order.filter.pointwise
import topology.algebra.monoid
import topology.compact_open
import topology.sets.compacts
import topology.algebra.constructions
/-!
# Topological groups
This file defines the following typeclasses:
* `topological_group`, `topological_add_group`: multiplicative and additive topological groups,
i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`;
* `has_continuous_sub G` means that `G` has a continuous subtraction operation.
There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate
typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups.
We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`,
`homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in
groups.
## Tags
topological space, group, topological group
-/
open classical set filter topological_space function
open_locale classical topological_space filter pointwise
universes u v w x
variables {α : Type u} {β : Type v} {G : Type w} {H : Type x}
section continuous_mul_group
/-!
### Groups with continuous multiplication
In this section we prove a few statements about groups with continuous `(*)`.
-/
variables [topological_space G] [group G] [has_continuous_mul G]
/-- Multiplication from the left in a topological group as a homeomorphism. -/
@[to_additive "Addition from the left in a topological additive group as a homeomorphism."]
protected def homeomorph.mul_left (a : G) : G ≃ₜ G :=
{ continuous_to_fun := continuous_const.mul continuous_id,
continuous_inv_fun := continuous_const.mul continuous_id,
.. equiv.mul_left a }
@[simp, to_additive]
lemma homeomorph.coe_mul_left (a : G) : ⇑(homeomorph.mul_left a) = (*) a := rfl
@[to_additive]
lemma homeomorph.mul_left_symm (a : G) : (homeomorph.mul_left a).symm = homeomorph.mul_left a⁻¹ :=
by { ext, refl }
@[to_additive]
lemma is_open_map_mul_left (a : G) : is_open_map (λ x, a * x) :=
(homeomorph.mul_left a).is_open_map
@[to_additive is_open.left_add_coset]
lemma is_open.left_coset {U : set G} (h : is_open U) (x : G) : is_open (left_coset x U) :=
is_open_map_mul_left x _ h
@[to_additive]
lemma is_closed_map_mul_left (a : G) : is_closed_map (λ x, a * x) :=
(homeomorph.mul_left a).is_closed_map
@[to_additive is_closed.left_add_coset]
lemma is_closed.left_coset {U : set G} (h : is_closed U) (x : G) : is_closed (left_coset x U) :=
is_closed_map_mul_left x _ h
/-- Multiplication from the right in a topological group as a homeomorphism. -/
@[to_additive "Addition from the right in a topological additive group as a homeomorphism."]
protected def homeomorph.mul_right (a : G) :
G ≃ₜ G :=
{ continuous_to_fun := continuous_id.mul continuous_const,
continuous_inv_fun := continuous_id.mul continuous_const,
.. equiv.mul_right a }
@[simp, to_additive]
lemma homeomorph.coe_mul_right (a : G) : ⇑(homeomorph.mul_right a) = λ g, g * a := rfl
@[to_additive]
lemma homeomorph.mul_right_symm (a : G) :
(homeomorph.mul_right a).symm = homeomorph.mul_right a⁻¹ :=
by { ext, refl }
@[to_additive]
lemma is_open_map_mul_right (a : G) : is_open_map (λ x, x * a) :=
(homeomorph.mul_right a).is_open_map
@[to_additive is_open.right_add_coset]
lemma is_open.right_coset {U : set G} (h : is_open U) (x : G) : is_open (right_coset U x) :=
is_open_map_mul_right x _ h
@[to_additive]
lemma is_closed_map_mul_right (a : G) : is_closed_map (λ x, x * a) :=
(homeomorph.mul_right a).is_closed_map
@[to_additive is_closed.right_add_coset]
lemma is_closed.right_coset {U : set G} (h : is_closed U) (x : G) : is_closed (right_coset U x) :=
is_closed_map_mul_right x _ h
@[to_additive]
lemma discrete_topology_of_open_singleton_one (h : is_open ({1} : set G)) : discrete_topology G :=
begin
rw ← singletons_open_iff_discrete,
intro g,
suffices : {g} = (λ (x : G), g⁻¹ * x) ⁻¹' {1},
{ rw this, exact (continuous_mul_left (g⁻¹)).is_open_preimage _ h, },
simp only [mul_one, set.preimage_mul_left_singleton, eq_self_iff_true,
inv_inv, set.singleton_eq_singleton_iff],
end
@[to_additive]
lemma discrete_topology_iff_open_singleton_one : discrete_topology G ↔ is_open ({1} : set G) :=
⟨λ h, forall_open_iff_discrete.mpr h {1}, discrete_topology_of_open_singleton_one⟩
end continuous_mul_group
/-!
### `has_continuous_inv` and `has_continuous_neg`
-/
/-- Basic hypothesis to talk about a topological additive group. A topological additive group
over `M`, for example, is obtained by requiring the instances `add_group M` and
`has_continuous_add M` and `has_continuous_neg M`. -/
class has_continuous_neg (G : Type u) [topological_space G] [has_neg G] : Prop :=
(continuous_neg : continuous (λ a : G, -a))
/-- Basic hypothesis to talk about a topological group. A topological group over `M`, for example,
is obtained by requiring the instances `group M` and `has_continuous_mul M` and
`has_continuous_inv M`. -/
@[to_additive]
class has_continuous_inv (G : Type u) [topological_space G] [has_inv G] : Prop :=
(continuous_inv : continuous (λ a : G, a⁻¹))
export has_continuous_inv (continuous_inv)
export has_continuous_neg (continuous_neg)
section continuous_inv
variables [topological_space G] [has_inv G] [has_continuous_inv G]
@[to_additive]
lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s :=
continuous_inv.continuous_on
@[to_additive]
lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x :=
continuous_inv.continuous_within_at
@[to_additive]
lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x :=
continuous_inv.continuous_at
@[to_additive]
lemma tendsto_inv (a : G) : tendsto has_inv.inv (𝓝 a) (𝓝 (a⁻¹)) :=
continuous_at_inv
/-- If a function converges to a value in a multiplicative topological group, then its inverse
converges to the inverse of this value. For the version in normed fields assuming additionally
that the limit is nonzero, use `tendsto.inv'`. -/
@[to_additive]
lemma filter.tendsto.inv {f : α → G} {l : filter α} {y : G} (h : tendsto f l (𝓝 y)) :
tendsto (λ x, (f x)⁻¹) l (𝓝 y⁻¹) :=
(continuous_inv.tendsto y).comp h
variables [topological_space α] {f : α → G} {s : set α} {x : α}
@[continuity, to_additive]
lemma continuous.inv (hf : continuous f) : continuous (λx, (f x)⁻¹) :=
continuous_inv.comp hf
@[to_additive]
lemma continuous_at.inv (hf : continuous_at f x) : continuous_at (λ x, (f x)⁻¹) x :=
continuous_at_inv.comp hf
@[to_additive]
lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s :=
continuous_inv.comp_continuous_on hf
@[to_additive]
lemma continuous_within_at.inv (hf : continuous_within_at f s x) :
continuous_within_at (λ x, (f x)⁻¹) s x :=
hf.inv
@[to_additive]
instance [topological_space H] [has_inv H] [has_continuous_inv H] : has_continuous_inv (G × H) :=
⟨(continuous_inv.comp continuous_fst).prod_mk (continuous_inv.comp continuous_snd)⟩
variable {ι : Type*}
@[to_additive]
instance pi.has_continuous_inv {C : ι → Type*} [∀ i, topological_space (C i)]
[∀ i, has_inv (C i)] [∀ i, has_continuous_inv (C i)] : has_continuous_inv (Π i, C i) :=
{ continuous_inv := continuous_pi (λ i, continuous.inv (continuous_apply i)) }
/-- A version of `pi.has_continuous_inv` for non-dependent functions. It is needed because sometimes
Lean fails to use `pi.has_continuous_inv` for non-dependent functions. -/
@[to_additive "A version of `pi.has_continuous_neg` for non-dependent functions. It is needed
because sometimes Lean fails to use `pi.has_continuous_neg` for non-dependent functions."]
instance pi.has_continuous_inv' : has_continuous_inv (ι → G) :=
pi.has_continuous_inv
@[priority 100, to_additive]
instance has_continuous_inv_of_discrete_topology [topological_space H]
[has_inv H] [discrete_topology H] : has_continuous_inv H :=
⟨continuous_of_discrete_topology⟩
section pointwise_limits
variables (G₁ G₂ : Type*) [topological_space G₂] [t2_space G₂]
@[to_additive] lemma is_closed_set_of_map_inv [has_inv G₁] [has_inv G₂] [has_continuous_inv G₂] :
is_closed {f : G₁ → G₂ | ∀ x, f x⁻¹ = (f x)⁻¹ } :=
begin
simp only [set_of_forall],
refine is_closed_Inter (λ i, is_closed_eq (continuous_apply _) (continuous_apply _).inv),
end
end pointwise_limits
instance additive.has_continuous_neg [h : topological_space H] [has_inv H]
[has_continuous_inv H] : @has_continuous_neg (additive H) h _ :=
{ continuous_neg := @continuous_inv H _ _ _ }
instance multiplicative.has_continuous_inv [h : topological_space H] [has_neg H]
[has_continuous_neg H] : @has_continuous_inv (multiplicative H) h _ :=
{ continuous_inv := @continuous_neg H _ _ _ }
end continuous_inv
section continuous_involutive_inv
variables [topological_space G] [has_involutive_inv G] [has_continuous_inv G] {s : set G}
@[to_additive] lemma is_compact.inv (hs : is_compact s) : is_compact s⁻¹ :=
by { rw [← image_inv], exact hs.image continuous_inv }
variables (G)
/-- Inversion in a topological group as a homeomorphism. -/
@[to_additive "Negation in a topological group as a homeomorphism."]
protected def homeomorph.inv (G : Type*) [topological_space G] [has_involutive_inv G]
[has_continuous_inv G] : G ≃ₜ G :=
{ continuous_to_fun := continuous_inv,
continuous_inv_fun := continuous_inv,
.. equiv.inv G }
@[to_additive] lemma is_open_map_inv : is_open_map (has_inv.inv : G → G) :=
(homeomorph.inv _).is_open_map
@[to_additive] lemma is_closed_map_inv : is_closed_map (has_inv.inv : G → G) :=
(homeomorph.inv _).is_closed_map
variables {G}
@[to_additive] lemma is_open.inv (hs : is_open s) : is_open s⁻¹ := hs.preimage continuous_inv
@[to_additive] lemma is_closed.inv (hs : is_closed s) : is_closed s⁻¹ := hs.preimage continuous_inv
@[to_additive] lemma inv_closure : ∀ s : set G, (closure s)⁻¹ = closure s⁻¹ :=
(homeomorph.inv G).preimage_closure
end continuous_involutive_inv
section lattice_ops
variables {ι' : Sort*} [has_inv G] [has_inv H] {ts : set (topological_space G)}
(h : Π t ∈ ts, @has_continuous_inv G t _) {ts' : ι' → topological_space G}
(h' : Π i, @has_continuous_inv G (ts' i) _) {t₁ t₂ : topological_space G}
(h₁ : @has_continuous_inv G t₁ _) (h₂ : @has_continuous_inv G t₂ _)
{t : topological_space H} [has_continuous_inv H]
@[to_additive] lemma has_continuous_inv_Inf :
@has_continuous_inv G (Inf ts) _ :=
{ continuous_inv := continuous_Inf_rng (λ t ht, continuous_Inf_dom ht
(@has_continuous_inv.continuous_inv G t _ (h t ht))) }
include h'
@[to_additive] lemma has_continuous_inv_infi :
@has_continuous_inv G (⨅ i, ts' i) _ :=
by {rw ← Inf_range, exact has_continuous_inv_Inf (set.forall_range_iff.mpr h')}
omit h'
include h₁ h₂
@[to_additive] lemma has_continuous_inv_inf :
@has_continuous_inv G (t₁ ⊓ t₂) _ :=
by {rw inf_eq_infi, refine has_continuous_inv_infi (λ b, _), cases b; assumption}
end lattice_ops
section topological_group
/-!
### Topological groups
A topological group is a group in which the multiplication and inversion operations are
continuous. Topological additive groups are defined in the same way. Equivalently, we can require
that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous.
-/
/-- A topological (additive) group is a group in which the addition and negation operations are
continuous. -/
class topological_add_group (G : Type u) [topological_space G] [add_group G]
extends has_continuous_add G, has_continuous_neg G : Prop
/-- A topological group is a group in which the multiplication and inversion operations are
continuous.
When you declare an instance that does not already have a `uniform_space` instance,
you should also provide an instance of `uniform_space` and `uniform_group` using
`topological_group.to_uniform_space` and `topological_group_is_uniform`. -/
@[to_additive]
class topological_group (G : Type*) [topological_space G] [group G]
extends has_continuous_mul G, has_continuous_inv G : Prop
section conj
instance conj_act.units_has_continuous_const_smul {M} [monoid M] [topological_space M]
[has_continuous_mul M] :
has_continuous_const_smul (conj_act Mˣ) M :=
⟨λ m, (continuous_const.mul continuous_id).mul continuous_const⟩
/-- we slightly weaken the type class assumptions here so that it will also apply to `ennreal`, but
we nevertheless leave it in the `topological_group` namespace. -/
variables [topological_space G] [has_inv G] [has_mul G] [has_continuous_mul G]
/-- Conjugation is jointly continuous on `G × G` when both `mul` and `inv` are continuous. -/
@[to_additive "Conjugation is jointly continuous on `G × G` when both `mul` and `inv` are
continuous."]
lemma topological_group.continuous_conj_prod [has_continuous_inv G] :
continuous (λ g : G × G, g.fst * g.snd * g.fst⁻¹) :=
continuous_mul.mul (continuous_inv.comp continuous_fst)
/-- Conjugation by a fixed element is continuous when `mul` is continuous. -/
@[to_additive "Conjugation by a fixed element is continuous when `add` is continuous."]
lemma topological_group.continuous_conj (g : G) : continuous (λ (h : G), g * h * g⁻¹) :=
(continuous_mul_right g⁻¹).comp (continuous_mul_left g)
/-- Conjugation acting on fixed element of the group is continuous when both `mul` and
`inv` are continuous. -/
@[to_additive "Conjugation acting on fixed element of the additive group is continuous when both
`add` and `neg` are continuous."]
lemma topological_group.continuous_conj' [has_continuous_inv G]
(h : G) : continuous (λ (g : G), g * h * g⁻¹) :=
(continuous_mul_right h).mul continuous_inv
end conj
variables [topological_space G] [group G] [topological_group G]
[topological_space α] {f : α → G} {s : set α} {x : α}
section zpow
@[continuity, to_additive]
lemma continuous_zpow : ∀ z : ℤ, continuous (λ a : G, a ^ z)
| (int.of_nat n) := by simpa using continuous_pow n
| -[1+n] := by simpa using (continuous_pow (n + 1)).inv
instance add_group.has_continuous_const_smul_int {A} [add_group A] [topological_space A]
[topological_add_group A] : has_continuous_const_smul ℤ A := ⟨continuous_zsmul⟩
instance add_group.has_continuous_smul_int {A} [add_group A] [topological_space A]
[topological_add_group A] : has_continuous_smul ℤ A :=
⟨continuous_uncurry_of_discrete_topology continuous_zsmul⟩
@[continuity, to_additive]
lemma continuous.zpow {f : α → G} (h : continuous f) (z : ℤ) :
continuous (λ b, (f b) ^ z) :=
(continuous_zpow z).comp h
@[to_additive]
lemma continuous_on_zpow {s : set G} (z : ℤ) : continuous_on (λ x, x ^ z) s :=
(continuous_zpow z).continuous_on
@[to_additive]
lemma continuous_at_zpow (x : G) (z : ℤ) : continuous_at (λ x, x ^ z) x :=
(continuous_zpow z).continuous_at
@[to_additive]
lemma filter.tendsto.zpow {α} {l : filter α} {f : α → G} {x : G} (hf : tendsto f l (𝓝 x)) (z : ℤ) :
tendsto (λ x, f x ^ z) l (𝓝 (x ^ z)) :=
(continuous_at_zpow _ _).tendsto.comp hf
@[to_additive]
lemma continuous_within_at.zpow {f : α → G} {x : α} {s : set α} (hf : continuous_within_at f s x)
(z : ℤ) : continuous_within_at (λ x, f x ^ z) s x :=
hf.zpow z
@[to_additive]
lemma continuous_at.zpow {f : α → G} {x : α} (hf : continuous_at f x) (z : ℤ) :
continuous_at (λ x, f x ^ z) x :=
hf.zpow z
@[to_additive continuous_on.zsmul]
lemma continuous_on.zpow {f : α → G} {s : set α} (hf : continuous_on f s) (z : ℤ) :
continuous_on (λ x, f x ^ z) s :=
λ x hx, (hf x hx).zpow z
end zpow
section ordered_comm_group
variables [topological_space H] [ordered_comm_group H] [topological_group H]
@[to_additive] lemma tendsto_inv_nhds_within_Ioi {a : H} :
tendsto has_inv.inv (𝓝[>] a) (𝓝[<] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Iio {a : H} :
tendsto has_inv.inv (𝓝[<] a) (𝓝[>] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Ioi_inv {a : H} :
tendsto has_inv.inv (𝓝[>] (a⁻¹)) (𝓝[<] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ioi _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Iio_inv {a : H} :
tendsto has_inv.inv (𝓝[<] (a⁻¹)) (𝓝[>] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iio _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Ici {a : H} :
tendsto has_inv.inv (𝓝[≥] a) (𝓝[≤] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Iic {a : H} :
tendsto has_inv.inv (𝓝[≤] a) (𝓝[≥] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Ici_inv {a : H} :
tendsto has_inv.inv (𝓝[≥] (a⁻¹)) (𝓝[≤] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ici _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Iic_inv {a : H} :
tendsto has_inv.inv (𝓝[≤] (a⁻¹)) (𝓝[≥] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iic _ _ _ _ (a⁻¹)
end ordered_comm_group
@[instance, to_additive]
instance [topological_space H] [group H] [topological_group H] :
topological_group (G × H) :=
{ continuous_inv := continuous_inv.prod_map continuous_inv }
@[to_additive]
instance pi.topological_group {C : β → Type*} [∀ b, topological_space (C b)]
[∀ b, group (C b)] [∀ b, topological_group (C b)] : topological_group (Π b, C b) :=
{ continuous_inv := continuous_pi (λ i, (continuous_apply i).inv) }
open mul_opposite
@[to_additive]
instance [group α] [has_continuous_inv α] : has_continuous_inv αᵐᵒᵖ :=
{ continuous_inv := continuous_induced_rng $ (@continuous_inv α _ _ _).comp continuous_unop }
/-- If multiplication is continuous in `α`, then it also is in `αᵐᵒᵖ`. -/
@[to_additive "If addition is continuous in `α`, then it also is in `αᵃᵒᵖ`."]
instance [group α] [topological_group α] :
topological_group αᵐᵒᵖ := { }
variable (G)
@[to_additive]
lemma nhds_one_symm : comap has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) :=
((homeomorph.inv G).comap_nhds_eq _).trans (congr_arg nhds inv_one)
/-- The map `(x, y) ↦ (x, xy)` as a homeomorphism. This is a shear mapping. -/
@[to_additive "The map `(x, y) ↦ (x, x + y)` as a homeomorphism.
This is a shear mapping."]
protected def homeomorph.shear_mul_right : G × G ≃ₜ G × G :=
{ continuous_to_fun := continuous_fst.prod_mk continuous_mul,
continuous_inv_fun := continuous_fst.prod_mk $ continuous_fst.inv.mul continuous_snd,
.. equiv.prod_shear (equiv.refl _) equiv.mul_left }
@[simp, to_additive]
lemma homeomorph.shear_mul_right_coe :
⇑(homeomorph.shear_mul_right G) = λ z : G × G, (z.1, z.1 * z.2) :=
rfl
@[simp, to_additive]
lemma homeomorph.shear_mul_right_symm_coe :
⇑(homeomorph.shear_mul_right G).symm = λ z : G × G, (z.1, z.1⁻¹ * z.2) :=
rfl
variables {G}
namespace subgroup
@[to_additive] instance (S : subgroup G) :
topological_group S :=
{ continuous_inv :=
begin
rw embedding_subtype_coe.to_inducing.continuous_iff,
exact continuous_subtype_coe.inv
end,
..S.to_submonoid.has_continuous_mul }
end subgroup
/-- The (topological-space) closure of a subgroup of a space `M` with `has_continuous_mul` is
itself a subgroup. -/
@[to_additive "The (topological-space) closure of an additive subgroup of a space `M` with
`has_continuous_add` is itself an additive subgroup."]
def subgroup.topological_closure (s : subgroup G) : subgroup G :=
{ carrier := closure (s : set G),
inv_mem' := λ g m, by simpa [←set.mem_inv, inv_closure] using m,
..s.to_submonoid.topological_closure }
@[simp, to_additive] lemma subgroup.topological_closure_coe {s : subgroup G} :
(s.topological_closure : set G) = closure s :=
rfl
@[to_additive]
instance subgroup.topological_closure_topological_group (s : subgroup G) :
topological_group (s.topological_closure) :=
{ continuous_inv :=
begin
apply continuous_induced_rng,
change continuous (λ p : s.topological_closure, (p : G)⁻¹),
continuity,
end
..s.to_submonoid.topological_closure_has_continuous_mul}
@[to_additive] lemma subgroup.subgroup_topological_closure (s : subgroup G) :
s ≤ s.topological_closure :=
subset_closure
@[to_additive] lemma subgroup.is_closed_topological_closure (s : subgroup G) :
is_closed (s.topological_closure : set G) :=
by convert is_closed_closure
@[to_additive] lemma subgroup.topological_closure_minimal
(s : subgroup G) {t : subgroup G} (h : s ≤ t) (ht : is_closed (t : set G)) :
s.topological_closure ≤ t :=
closure_minimal h ht
@[to_additive] lemma dense_range.topological_closure_map_subgroup [group H] [topological_space H]
[topological_group H] {f : G →* H} (hf : continuous f) (hf' : dense_range f) {s : subgroup G}
(hs : s.topological_closure = ⊤) :
(s.map f).topological_closure = ⊤ :=
begin
rw set_like.ext'_iff at hs ⊢,
simp only [subgroup.topological_closure_coe, subgroup.coe_top, ← dense_iff_closure_eq] at hs ⊢,
exact hf'.dense_image hf hs
end
/-- The topological closure of a normal subgroup is normal.-/
@[to_additive "The topological closure of a normal additive subgroup is normal."]
lemma subgroup.is_normal_topological_closure {G : Type*} [topological_space G] [group G]
[topological_group G] (N : subgroup G) [N.normal] :
(subgroup.topological_closure N).normal :=
{ conj_mem := λ n hn g,
begin
apply mem_closure_of_continuous (topological_group.continuous_conj g) hn,
intros m hm,
exact subset_closure (subgroup.normal.conj_mem infer_instance m hm g),
end }
@[to_additive] lemma mul_mem_connected_component_one {G : Type*} [topological_space G]
[mul_one_class G] [has_continuous_mul G] {g h : G} (hg : g ∈ connected_component (1 : G))
(hh : h ∈ connected_component (1 : G)) : g * h ∈ connected_component (1 : G) :=
begin
rw connected_component_eq hg,
have hmul: g ∈ connected_component (g*h),
{ apply continuous.image_connected_component_subset (continuous_mul_left g),
rw ← connected_component_eq hh,
exact ⟨(1 : G), mem_connected_component, by simp only [mul_one]⟩ },
simpa [← connected_component_eq hmul] using (mem_connected_component)
end
@[to_additive] lemma inv_mem_connected_component_one {G : Type*} [topological_space G] [group G]
[topological_group G] {g : G} (hg : g ∈ connected_component (1 : G)) :
g⁻¹ ∈ connected_component (1 : G) :=
begin
rw ← inv_one,
exact continuous.image_connected_component_subset continuous_inv _
((set.mem_image _ _ _).mp ⟨g, hg, rfl⟩)
end
/-- The connected component of 1 is a subgroup of `G`. -/
@[to_additive "The connected component of 0 is a subgroup of `G`."]
def subgroup.connected_component_of_one (G : Type*) [topological_space G] [group G]
[topological_group G] : subgroup G :=
{ carrier := connected_component (1 : G),
one_mem' := mem_connected_component,
mul_mem' := λ g h hg hh, mul_mem_connected_component_one hg hh,
inv_mem' := λ g hg, inv_mem_connected_component_one hg }
/-- If a subgroup of a topological group is commutative, then so is its topological closure. -/
@[to_additive "If a subgroup of an additive topological group is commutative, then so is its
topological closure."]
def subgroup.comm_group_topological_closure [t2_space G] (s : subgroup G)
(hs : ∀ (x y : s), x * y = y * x) : comm_group s.topological_closure :=
{ ..s.topological_closure.to_group,
..s.to_submonoid.comm_monoid_topological_closure hs }
@[to_additive exists_nhds_half_neg]
lemma exists_nhds_split_inv {s : set G} (hs : s ∈ 𝓝 (1 : G)) :
∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v / w ∈ s :=
have ((λp : G × G, p.1 * p.2⁻¹) ⁻¹' s) ∈ 𝓝 ((1, 1) : G × G),
from continuous_at_fst.mul continuous_at_snd.inv (by simpa),
by simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage]
using this
@[to_additive]
lemma nhds_translation_mul_inv (x : G) : comap (λ y : G, y * x⁻¹) (𝓝 1) = 𝓝 x :=
((homeomorph.mul_right x⁻¹).comap_nhds_eq 1).trans $ show 𝓝 (1 * x⁻¹⁻¹) = 𝓝 x, by simp
@[simp, to_additive] lemma map_mul_left_nhds (x y : G) : map ((*) x) (𝓝 y) = 𝓝 (x * y) :=
(homeomorph.mul_left x).map_nhds_eq y
@[to_additive] lemma map_mul_left_nhds_one (x : G) : map ((*) x) (𝓝 1) = 𝓝 x := by simp
/-- A monoid homomorphism (a bundled morphism of a type that implements `monoid_hom_class`) from a
topological group to a topological monoid is continuous provided that it is continuous at one. See
also `uniform_continuous_of_continuous_at_one`. -/
@[to_additive "An additive monoid homomorphism (a bundled morphism of a type that implements
`add_monoid_hom_class`) from an additive topological group to an additive topological monoid is
continuous provided that it is continuous at zero. See also
`uniform_continuous_of_continuous_at_zero`."]
lemma continuous_of_continuous_at_one {M hom : Type*} [mul_one_class M] [topological_space M]
[has_continuous_mul M] [monoid_hom_class hom G M] (f : hom) (hf : continuous_at f 1) :
continuous f :=
continuous_iff_continuous_at.2 $ λ x,
by simpa only [continuous_at, ← map_mul_left_nhds_one x, tendsto_map'_iff, (∘),
map_mul, map_one, mul_one] using hf.tendsto.const_mul (f x)
@[to_additive]
lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G}
(tg : @topological_group G t _) (tg' : @topological_group G t' _)
(h : @nhds G t 1 = @nhds G t' 1) : t = t' :=
eq_of_nhds_eq_nhds $ λ x, by
rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h]
@[to_additive]
lemma topological_group.of_nhds_aux {G : Type*} [group G] [topological_space G]
(hinv : tendsto (λ (x : G), x⁻¹) (𝓝 1) (𝓝 1))
(hleft : ∀ (x₀ : G), 𝓝 x₀ = map (λ (x : G), x₀ * x) (𝓝 1))
(hconj : ∀ (x₀ : G), map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) ≤ 𝓝 1) : continuous (λ x : G, x⁻¹) :=
begin
rw continuous_iff_continuous_at,
rintros x₀,
have key : (λ x, (x₀*x)⁻¹) = (λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹) ∘ (λ x, x⁻¹),
by {ext ; simp[mul_assoc] },
calc map (λ x, x⁻¹) (𝓝 x₀)
= map (λ x, x⁻¹) (map (λ x, x₀*x) $ 𝓝 1) : by rw hleft
... = map (λ x, (x₀*x)⁻¹) (𝓝 1) : by rw filter.map_map
... = map (((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) ∘ (λ x, x⁻¹)) (𝓝 1) : by rw key
... = map ((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) _ : by rw ← filter.map_map
... ≤ map ((λ x, x₀⁻¹ * x) ∘ λ x, x₀ * x * x₀⁻¹) (𝓝 1) : map_mono hinv
... = map (λ x, x₀⁻¹ * x) (map (λ x, x₀ * x * x₀⁻¹) (𝓝 1)) : filter.map_map
... ≤ map (λ x, x₀⁻¹ * x) (𝓝 1) : map_mono (hconj x₀)
... = 𝓝 x₀⁻¹ : (hleft _).symm
end
@[to_additive]
lemma topological_group.of_nhds_one' {G : Type u} [group G] [topological_space G]
(hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1))
(hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1))
(hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1))
(hright : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : topological_group G :=
begin
refine { continuous_mul := (has_continuous_mul.of_nhds_one hmul hleft hright).continuous_mul,
continuous_inv := topological_group.of_nhds_aux hinv hleft _ },
intros x₀,
suffices : map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) = 𝓝 1, by simp [this, le_refl],
rw [show (λ x, x₀ * x * x₀⁻¹) = (λ x, x₀ * x) ∘ λ x, x*x₀⁻¹, by {ext, simp [mul_assoc] },
← filter.map_map, ← hright, hleft x₀⁻¹, filter.map_map],
convert map_id,
ext,
simp
end
@[to_additive]
lemma topological_group.of_nhds_one {G : Type u} [group G] [topological_space G]
(hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1))
(hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1))
(hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1))
(hconj : ∀ x₀ : G, tendsto (λ x, x₀*x*x₀⁻¹) (𝓝 1) (𝓝 1)) : topological_group G :=
{ continuous_mul := begin
rw continuous_iff_continuous_at,
rintros ⟨x₀, y₀⟩,
have key : (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) =
((λ x, x₀*y₀*x) ∘ (uncurry (*)) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id)),
by { ext, simp [uncurry, prod.map, mul_assoc] },
specialize hconj y₀⁻¹, rw inv_inv at hconj,
calc map (λ (p : G × G), p.1 * p.2) (𝓝 (x₀, y₀))
= map (λ (p : G × G), p.1 * p.2) ((𝓝 x₀) ×ᶠ 𝓝 y₀)
: by rw nhds_prod_eq
... = map (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) ((𝓝 1) ×ᶠ (𝓝 1))
: by rw [hleft x₀, hleft y₀, prod_map_map_eq, filter.map_map]
... = map (((λ x, x₀*y₀*x) ∘ (uncurry (*))) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id))((𝓝 1) ×ᶠ (𝓝 1))
: by rw key
... = map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((map (λ x, y₀⁻¹*x*y₀) $ 𝓝 1) ×ᶠ (𝓝 1))
: by rw [← filter.map_map, ← prod_map_map_eq', map_id]
... ≤ map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((𝓝 1) ×ᶠ (𝓝 1))
: map_mono (filter.prod_mono hconj $ le_rfl)
... = map (λ x, x₀*y₀*x) (map (uncurry (*)) ((𝓝 1) ×ᶠ (𝓝 1))) : by rw filter.map_map
... ≤ map (λ x, x₀*y₀*x) (𝓝 1) : map_mono hmul
... = 𝓝 (x₀*y₀) : (hleft _).symm
end,
continuous_inv := topological_group.of_nhds_aux hinv hleft hconj}
@[to_additive]
lemma topological_group.of_comm_of_nhds_one {G : Type u} [comm_group G] [topological_space G]
(hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1))
(hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1))
(hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : topological_group G :=
topological_group.of_nhds_one hmul hinv hleft (by simpa using tendsto_id)
end topological_group
section quotient_topological_group
variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal)
@[to_additive]
instance quotient_group.quotient.topological_space {G : Type*} [group G] [topological_space G]
(N : subgroup G) : topological_space (G ⧸ N) :=
quotient.topological_space
open quotient_group
@[to_additive]
lemma quotient_group.is_open_map_coe : is_open_map (coe : G → G ⧸ N) :=
begin
intros s s_op,
change is_open ((coe : G → G ⧸ N) ⁻¹' (coe '' s)),
rw quotient_group.preimage_image_coe N s,
exact is_open_Union (λ n, (continuous_mul_right _).is_open_preimage s s_op)
end
@[to_additive]
instance topological_group_quotient [N.normal] : topological_group (G ⧸ N) :=
{ continuous_mul := begin
have cont : continuous ((coe : G → G ⧸ N) ∘ (λ (p : G × G), p.fst * p.snd)) :=
continuous_quot_mk.comp continuous_mul,
have quot : quotient_map (λ p : G × G, ((p.1 : G ⧸ N), (p.2 : G ⧸ N))),
{ apply is_open_map.to_quotient_map,
{ exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) },
{ exact continuous_quot_mk.prod_map continuous_quot_mk },
{ exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } },
exact (quotient_map.continuous_iff quot).2 cont,
end,
continuous_inv := begin
have : continuous ((coe : G → G ⧸ N) ∘ (λ (a : G), a⁻¹)) :=
continuous_quot_mk.comp continuous_inv,
convert continuous_quotient_lift _ this,
end }
end quotient_topological_group
/-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property
automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/
class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop :=
(continuous_sub : continuous (λ p : G × G, p.1 - p.2))
/-- A typeclass saying that `λ p : G × G, p.1 / p.2` is a continuous function. This property
automatically holds for topological groups. Lemmas using this class have primes.
The unprimed version is for `group_with_zero`. -/
@[to_additive]
class has_continuous_div (G : Type*) [topological_space G] [has_div G] : Prop :=
(continuous_div' : continuous (λ p : G × G, p.1 / p.2))
@[priority 100, to_additive] -- see Note [lower instance priority]
instance topological_group.to_has_continuous_div [topological_space G] [group G]
[topological_group G] : has_continuous_div G :=
⟨by { simp only [div_eq_mul_inv], exact continuous_fst.mul continuous_snd.inv }⟩
export has_continuous_sub (continuous_sub)
export has_continuous_div (continuous_div')
section has_continuous_div
variables [topological_space G] [has_div G] [has_continuous_div G]
@[to_additive sub]
lemma filter.tendsto.div' {f g : α → G} {l : filter α} {a b : G} (hf : tendsto f l (𝓝 a))
(hg : tendsto g l (𝓝 b)) : tendsto (λ x, f x / g x) l (𝓝 (a / b)) :=
(continuous_div'.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
@[to_additive const_sub]
lemma filter.tendsto.const_div' (b : G) {c : G} {f : α → G} {l : filter α}
(h : tendsto f l (𝓝 c)) : tendsto (λ k : α, b / f k) l (𝓝 (b / c)) :=
tendsto_const_nhds.div' h
@[to_additive sub_const]
lemma filter.tendsto.div_const' (b : G) {c : G} {f : α → G} {l : filter α}
(h : tendsto f l (𝓝 c)) : tendsto (λ k : α, f k / b) l (𝓝 (c / b)) :=
h.div' tendsto_const_nhds
variables [topological_space α] {f g : α → G} {s : set α} {x : α}
@[continuity, to_additive sub] lemma continuous.div' (hf : continuous f) (hg : continuous g) :
continuous (λ x, f x / g x) :=
continuous_div'.comp (hf.prod_mk hg : _)
@[to_additive continuous_sub_left]
lemma continuous_div_left' (a : G) : continuous (λ b : G, a / b) :=
continuous_const.div' continuous_id
@[to_additive continuous_sub_right]
lemma continuous_div_right' (a : G) : continuous (λ b : G, b / a) :=
continuous_id.div' continuous_const
@[to_additive sub]
lemma continuous_at.div' {f g : α → G} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) :
continuous_at (λx, f x / g x) x :=
hf.div' hg
@[to_additive sub]
lemma continuous_within_at.div' (hf : continuous_within_at f s x)
(hg : continuous_within_at g s x) :
continuous_within_at (λ x, f x / g x) s x :=
hf.div' hg
@[to_additive sub]
lemma continuous_on.div' (hf : continuous_on f s) (hg : continuous_on g s) :
continuous_on (λx, f x / g x) s :=
λ x hx, (hf x hx).div' (hg x hx)
end has_continuous_div
section div_in_topological_group
variables [group G] [topological_space G] [topological_group G]
/-- A version of `homeomorph.mul_left a b⁻¹` that is defeq to `a / b`. -/
@[to_additive /-" A version of `homeomorph.add_left a (-b)` that is defeq to `a - b`. "-/,
simps {simp_rhs := tt}]
def homeomorph.div_left (x : G) : G ≃ₜ G :=
{ continuous_to_fun := continuous_const.div' continuous_id,
continuous_inv_fun := continuous_inv.mul continuous_const,
.. equiv.div_left x }
@[to_additive] lemma is_open_map_div_left (a : G) : is_open_map ((/) a) :=
(homeomorph.div_left _).is_open_map
@[to_additive] lemma is_closed_map_div_left (a : G) : is_closed_map ((/) a) :=
(homeomorph.div_left _).is_closed_map
/-- A version of `homeomorph.mul_right a⁻¹ b` that is defeq to `b / a`. -/
@[to_additive /-" A version of `homeomorph.add_right (-a) b` that is defeq to `b - a`. "-/,
simps {simp_rhs := tt}]
def homeomorph.div_right (x : G) : G ≃ₜ G :=
{ continuous_to_fun := continuous_id.div' continuous_const,
continuous_inv_fun := continuous_id.mul continuous_const,
.. equiv.div_right x }
@[to_additive]
lemma is_open_map_div_right (a : G) : is_open_map (λ x, x / a) :=
(homeomorph.div_right a).is_open_map
@[to_additive]
lemma is_closed_map_div_right (a : G) : is_closed_map (λ x, x / a) :=
(homeomorph.div_right a).is_closed_map
@[to_additive]
lemma tendsto_div_nhds_one_iff
{α : Type*} {l : filter α} {x : G} {u : α → G} :
tendsto (λ n, u n / x) l (𝓝 1) ↔ tendsto u l (𝓝 x) :=
begin
have A : tendsto (λ (n : α), x) l (𝓝 x) := tendsto_const_nhds,
exact ⟨λ h, by simpa using h.mul A, λ h, by simpa using h.div' A⟩
end
@[to_additive] lemma nhds_translation_div (x : G) : comap (/ x) (𝓝 1) = 𝓝 x :=
by simpa only [div_eq_mul_inv] using nhds_translation_mul_inv x
end div_in_topological_group
/-!
### Topological operations on pointwise sums and products
A few results about interior and closure of the pointwise addition/multiplication of sets in groups
with continuous addition/multiplication. See also `submonoid.top_closure_mul_self_eq` in
`topology.algebra.monoid`.
-/
section has_continuous_mul
variables [topological_space α] [group α] [has_continuous_mul α] {s t : set α}
@[to_additive] lemma is_open.mul_left (ht : is_open t) : is_open (s * t) :=
by { rw ←Union_mul_left_image, exact is_open_bUnion (λ a ha, is_open_map_mul_left a t ht) }
@[to_additive] lemma is_open.mul_right (hs : is_open s) : is_open (s * t) :=
by { rw ←Union_mul_right_image, exact is_open_bUnion (λ a ha, is_open_map_mul_right a s hs) }
@[to_additive] lemma subset_interior_mul_left : interior s * t ⊆ interior (s * t) :=
interior_maximal (set.mul_subset_mul_right interior_subset) is_open_interior.mul_right
@[to_additive] lemma subset_interior_mul_right : s * interior t ⊆ interior (s * t) :=
interior_maximal (set.mul_subset_mul_left interior_subset) is_open_interior.mul_left
@[to_additive] lemma subset_interior_mul : interior s * interior t ⊆ interior (s * t) :=
(set.mul_subset_mul_left interior_subset).trans subset_interior_mul_left
end has_continuous_mul
section topological_group
variables [topological_space α] [group α] [topological_group α] {s t : set α}
@[to_additive] lemma is_open.div_left (ht : is_open t) : is_open (s / t) :=
by { rw ←Union_div_left_image, exact is_open_bUnion (λ a ha, is_open_map_div_left a t ht) }
@[to_additive] lemma is_open.div_right (hs : is_open s) : is_open (s / t) :=
by { rw ←Union_div_right_image, exact is_open_bUnion (λ a ha, is_open_map_div_right a s hs) }
@[to_additive] lemma subset_interior_div_left : interior s / t ⊆ interior (s / t) :=
interior_maximal (div_subset_div_right interior_subset) is_open_interior.div_right
@[to_additive] lemma subset_interior_div_right : s / interior t ⊆ interior (s / t) :=
interior_maximal (div_subset_div_left interior_subset) is_open_interior.div_left
@[to_additive] lemma subset_interior_div : interior s / interior t ⊆ interior (s / t) :=
(div_subset_div_left interior_subset).trans subset_interior_div_left
@[to_additive] lemma is_open.mul_closure (hs : is_open s) (t : set α) : s * closure t = s * t :=
begin
refine (mul_subset_iff.2 $ λ a ha b hb, _).antisymm (mul_subset_mul_left subset_closure),
rw mem_closure_iff at hb,
have hbU : b ∈ s⁻¹ * {a * b} := ⟨a⁻¹, a * b, set.inv_mem_inv.2 ha, rfl, inv_mul_cancel_left _ _⟩,
obtain ⟨_, ⟨c, d, hc, (rfl : d = _), rfl⟩, hcs⟩ := hb _ hs.inv.mul_right hbU,
exact ⟨c⁻¹, _, hc, hcs, inv_mul_cancel_left _ _⟩,
end
@[to_additive] lemma is_open.closure_mul (ht : is_open t) (s : set α) : closure s * t = s * t :=
by rw [←inv_inv (closure s * t), mul_inv_rev, inv_closure, ht.inv.mul_closure, mul_inv_rev, inv_inv,
inv_inv]
@[to_additive] lemma is_open.div_closure (hs : is_open s) (t : set α) : s / closure t = s / t :=
by simp_rw [div_eq_mul_inv, inv_closure, hs.mul_closure]
@[to_additive] lemma is_open.closure_div (ht : is_open t) (s : set α) : closure s / t = s / t :=
by simp_rw [div_eq_mul_inv, ht.inv.closure_mul]
end topological_group
/-- additive group with a neighbourhood around 0.
Only used to construct a topology and uniform space.
This is currently only available for commutative groups, but it can be extended to
non-commutative groups too.
-/
class add_group_with_zero_nhd (G : Type u) extends add_comm_group G :=
(Z [] : filter G)
(zero_Z : pure 0 ≤ Z)
(sub_Z : tendsto (λp:G×G, p.1 - p.2) (Z ×ᶠ Z) Z)
section filter_mul
section
variables (G) [topological_space G] [group G] [topological_group G]
@[to_additive]
lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G :=
⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩
@[to_additive]
lemma topological_group.regular_space [t1_space G] : regular_space G :=
⟨assume s a hs ha,
let f := λ p : G × G, p.1 * (p.2)⁻¹ in
have hf : continuous f := continuous_fst.mul continuous_snd.inv,
-- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s);
-- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s)
let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ :=
is_open_prod_iff.1 ((is_open_compl_iff.2 hs).preimage hf) a (1:G) (by simpa [f]) in
begin
use [s * t₂, ht₂.mul_left, λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩],
rw [nhds_within, inf_principal_eq_bot, mem_nhds_iff],
refine ⟨t₁, _, ht₁, a_mem_t₁⟩,
rintros x hx ⟨y, z, hy, hz, yz⟩,
have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz,
have : x * z⁻¹ ∈ s, rw ← yz, simpa,
contradiction
end⟩
@[to_additive]
lemma topological_group.t2_space [t1_space G] : t2_space G :=
@regular_space.t2_space G _ (topological_group.regular_space G)
variables {G} (S : subgroup G) [subgroup.normal S] [is_closed (S : set G)]
@[to_additive]
instance subgroup.regular_quotient_of_is_closed
(S : subgroup G) [subgroup.normal S] [is_closed (S : set G)] : regular_space (G ⧸ S) :=
begin
suffices : t1_space (G ⧸ S), { exact @topological_group.regular_space _ _ _ _ this, },
have hS : is_closed (S : set G) := infer_instance,
rw ← quotient_group.ker_mk S at hS,
exact topological_group.t1_space (G ⧸ S) ((quotient_map_quotient_mk.is_closed_preimage).mp hS),
end
end
section
/-! Some results about an open set containing the product of two sets in a topological group. -/
variables [topological_space G] [group G] [topological_group G]
/-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1`
such that `K * V ⊆ U`. -/
@[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of
`0` such that `K + V ⊆ U`."]
lemma compact_open_separated_mul_right {K U : set G} (hK : is_compact K) (hU : is_open U)
(hKU : K ⊆ U) : ∃ V ∈ 𝓝 (1 : G), K * V ⊆ U :=
begin
apply hK.induction_on,
{ exact ⟨univ, by simp⟩ },
{ rintros s t hst ⟨V, hV, hV'⟩,
exact ⟨V, hV, (mul_subset_mul_right hst).trans hV'⟩ },
{ rintros s t ⟨V, V_in, hV'⟩ ⟨W, W_in, hW'⟩,
use [V ∩ W, inter_mem V_in W_in],
rw union_mul,
exact union_subset ((mul_subset_mul_left (V.inter_subset_left W)).trans hV')
((mul_subset_mul_left (V.inter_subset_right W)).trans hW') },
{ intros x hx,
have := tendsto_mul (show U ∈ 𝓝 (x * 1), by simpa using hU.mem_nhds (hKU hx)),
rw [nhds_prod_eq, mem_map, mem_prod_iff] at this,
rcases this with ⟨t, ht, s, hs, h⟩,
rw [← image_subset_iff, image_mul_prod] at h,
exact ⟨t, mem_nhds_within_of_mem_nhds ht, s, hs, h⟩ }
end
open mul_opposite
/-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1`
such that `V * K ⊆ U`. -/
@[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of
`0` such that `V + K ⊆ U`."]
lemma compact_open_separated_mul_left {K U : set G} (hK : is_compact K) (hU : is_open U)
(hKU : K ⊆ U) : ∃ V ∈ 𝓝 (1 : G), V * K ⊆ U :=
begin
rcases compact_open_separated_mul_right (hK.image continuous_op) (op_homeomorph.is_open_map U hU)
(image_subset op hKU) with ⟨V, (hV : V ∈ 𝓝 (op (1 : G))), hV' : op '' K * V ⊆ op '' U⟩,
refine ⟨op ⁻¹' V, continuous_op.continuous_at hV, _⟩,
rwa [← image_preimage_eq V op_surjective, ← image_op_mul, image_subset_iff,
preimage_image_eq _ op_injective] at hV'
end
/-- A compact set is covered by finitely many left multiplicative translates of a set
with non-empty interior. -/
@[to_additive "A compact set is covered by finitely many left additive translates of a set
with non-empty interior."]
lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K)
(hV : (interior V).nonempty) : ∃ t : finset G, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V :=
begin
obtain ⟨t, ht⟩ : ∃ t : finset G, K ⊆ ⋃ x ∈ t, interior (((*) x) ⁻¹' V),
{ refine hK.elim_finite_subcover (λ x, interior $ ((*) x) ⁻¹' V) (λ x, is_open_interior) _,
cases hV with g₀ hg₀,
refine λ g hg, mem_Union.2 ⟨g₀ * g⁻¹, _⟩,
refine preimage_interior_subset_interior_preimage (continuous_const.mul continuous_id) _,
rwa [mem_preimage, inv_mul_cancel_right] },
exact ⟨t, subset.trans ht $ Union₂_mono $ λ g hg, interior_subset⟩
end
/-- Every locally compact separable topological group is σ-compact.
Note: this is not true if we drop the topological group hypothesis. -/
@[priority 100, to_additive separable_locally_compact_add_group.sigma_compact_space]
instance separable_locally_compact_group.sigma_compact_space
[separable_space G] [locally_compact_space G] : sigma_compact_space G :=
begin
obtain ⟨L, hLc, hL1⟩ := exists_compact_mem_nhds (1 : G),
refine ⟨⟨λ n, (λ x, x * dense_seq G n) ⁻¹' L, _, _⟩⟩,
{ intro n, exact (homeomorph.mul_right _).compact_preimage.mpr hLc },
{ refine Union_eq_univ_iff.2 (λ x, _),
obtain ⟨_, ⟨n, rfl⟩, hn⟩ : (range (dense_seq G) ∩ (λ y, x * y) ⁻¹' L).nonempty,
{ rw [← (homeomorph.mul_left x).apply_symm_apply 1] at hL1,
exact (dense_range_dense_seq G).inter_nhds_nonempty
((homeomorph.mul_left x).continuous.continuous_at $ hL1) },
exact ⟨n, hn⟩ }
end
/-- Every separated topological group in which there exists a compact set with nonempty interior
is locally compact. -/
@[to_additive] lemma topological_space.positive_compacts.locally_compact_space_of_group
[t2_space G] (K : positive_compacts G) :
locally_compact_space G :=
begin
refine locally_compact_of_compact_nhds (λ x, _),
obtain ⟨y, hy⟩ := K.interior_nonempty,
let F := homeomorph.mul_left (x * y⁻¹),
refine ⟨F '' K, _, K.compact.image F.continuous⟩,
suffices : F.symm ⁻¹' K ∈ 𝓝 x, by { convert this, apply equiv.image_eq_preimage },
apply continuous_at.preimage_mem_nhds F.symm.continuous.continuous_at,
have : F.symm x = y, by simp [F, homeomorph.mul_left_symm],
rw this,
exact mem_interior_iff_mem_nhds.1 hy
end
end
section
variables [topological_space G] [comm_group G] [topological_group G]
@[to_additive]
lemma nhds_mul (x y : G) : 𝓝 (x * y) = 𝓝 x * 𝓝 y :=
filter_eq $ set.ext $ assume s,
begin
rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)],
split,
{ rintros ⟨t, ht, ts⟩,
rcases exists_nhds_one_split ht with ⟨V, V1, h⟩,
refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V,
⟨V, V1, subset.refl _⟩, ⟨V, V1, subset.refl _⟩, _⟩,
rintros a ⟨v, w, v_mem, w_mem, rfl⟩,
apply ts,
simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) v_mem (w * y⁻¹) w_mem },
{ rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩,
refine ⟨b ∩ d, inter_mem hb hd, assume v, _⟩,
simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *,
rintros ⟨vb, vd⟩,
refine ac ⟨v * y⁻¹, y, _, _, _⟩,
{ rw ← mul_assoc _ _ _ at vb, exact ba _ vb },
{ apply dc y, rw mul_right_inv, exact mem_of_mem_nhds hd },
{ simp only [inv_mul_cancel_right] } }
end
/-- On a topological group, `𝓝 : G → filter G` can be promoted to a `mul_hom`. -/
@[to_additive "On an additive topological group, `𝓝 : G → filter G` can be promoted to an
`add_hom`.", simps]
def nhds_mul_hom : G →ₙ* (filter G) :=
{ to_fun := 𝓝,
map_mul' := λ_ _, nhds_mul _ _ }
end
end filter_mul
instance additive.topological_add_group {G} [h : topological_space G]
[group G] [topological_group G] : @topological_add_group (additive G) h _ :=
{ continuous_neg := @continuous_inv G _ _ _ }
instance multiplicative.topological_group {G} [h : topological_space G]
[add_group G] [topological_add_group G] : @topological_group (multiplicative G) h _ :=
{ continuous_inv := @continuous_neg G _ _ _ }
section quotient
variables [group G] [topological_space G] [topological_group G] {Γ : subgroup G}
@[to_additive]
instance quotient_group.has_continuous_const_smul : has_continuous_const_smul G (G ⧸ Γ) :=
{ continuous_const_smul := λ g₀, begin
apply continuous_coinduced_dom,
change continuous (λ g : G, quotient_group.mk (g₀ * g)),
exact continuous_coinduced_rng.comp (continuous_mul_left g₀),
end }
@[to_additive]
lemma quotient_group.continuous_smul₁ (x : G ⧸ Γ) : continuous (λ g : G, g • x) :=
begin
obtain ⟨g₀, rfl⟩ : ∃ g₀, quotient_group.mk g₀ = x,
{ exact @quotient.exists_rep _ (quotient_group.left_rel Γ) x },
change continuous (λ g, quotient_group.mk (g * g₀)),
exact continuous_coinduced_rng.comp (continuous_mul_right g₀)
end
@[to_additive]
instance quotient_group.has_continuous_smul [locally_compact_space G] :
has_continuous_smul G (G ⧸ Γ) :=
{ continuous_smul := begin
let F : G × G ⧸ Γ → G ⧸ Γ := λ p, p.1 • p.2,
change continuous F,
have H : continuous (F ∘ (λ p : G × G, (p.1, quotient_group.mk p.2))),
{ change continuous (λ p : G × G, quotient_group.mk (p.1 * p.2)),
refine continuous_coinduced_rng.comp continuous_mul },
exact quotient_map.continuous_lift_prod_right quotient_map_quotient_mk H,
end }
end quotient
namespace units
open mul_opposite (continuous_op continuous_unop)
variables [monoid α] [topological_space α] [has_continuous_mul α] [monoid β] [topological_space β]
[has_continuous_mul β]
@[to_additive] instance : topological_group αˣ :=
{ continuous_inv := continuous_induced_rng ((continuous_unop.comp
(@continuous_embed_product α _ _).snd).prod_mk (continuous_op.comp continuous_coe)) }
/-- The topological group isomorphism between the units of a product of two monoids, and the product
of the units of each monoid. -/
def homeomorph.prod_units : homeomorph (α × β)ˣ (αˣ × βˣ) :=
{ continuous_to_fun :=
begin
show continuous (λ i : (α × β)ˣ, (map (monoid_hom.fst α β) i, map (monoid_hom.snd α β) i)),
refine continuous.prod_mk _ _,
{ refine continuous_induced_rng ((continuous_fst.comp units.continuous_coe).prod_mk _),
refine mul_opposite.continuous_op.comp (continuous_fst.comp _),
simp_rw units.inv_eq_coe_inv,
exact units.continuous_coe.comp continuous_inv, },
{ refine continuous_induced_rng ((continuous_snd.comp units.continuous_coe).prod_mk _),
simp_rw units.coe_map_inv,
exact continuous_op.comp (continuous_snd.comp (units.continuous_coe.comp continuous_inv)), }
end,
continuous_inv_fun :=
begin
refine continuous_induced_rng (continuous.prod_mk _ _),
{ exact (units.continuous_coe.comp continuous_fst).prod_mk
(units.continuous_coe.comp continuous_snd), },
{ refine continuous_op.comp
(units.continuous_coe.comp $ continuous_induced_rng $ continuous.prod_mk _ _),
{ exact (units.continuous_coe.comp (continuous_inv.comp continuous_fst)).prod_mk
(units.continuous_coe.comp (continuous_inv.comp continuous_snd)) },
{ exact continuous_op.comp ((units.continuous_coe.comp continuous_fst).prod_mk
(units.continuous_coe.comp continuous_snd)) }}
end,
..mul_equiv.prod_units }
end units
section lattice_ops
variables {ι : Sort*} [group G] [group H] {ts : set (topological_space G)}
(h : ∀ t ∈ ts, @topological_group G t _) {ts' : ι → topological_space G}
(h' : ∀ i, @topological_group G (ts' i) _) {t₁ t₂ : topological_space G}
(h₁ : @topological_group G t₁ _) (h₂ : @topological_group G t₂ _)
{t : topological_space H} [topological_group H] {F : Type*}
[monoid_hom_class F G H] (f : F)
@[to_additive] lemma topological_group_Inf :
@topological_group G (Inf ts) _ :=
{ continuous_inv := @has_continuous_inv.continuous_inv G (Inf ts) _
(@has_continuous_inv_Inf _ _ _
(λ t ht, @topological_group.to_has_continuous_inv G t _ (h t ht))),
continuous_mul := @has_continuous_mul.continuous_mul G (Inf ts) _
(@has_continuous_mul_Inf _ _ _
(λ t ht, @topological_group.to_has_continuous_mul G t _ (h t ht))) }
include h'
@[to_additive] lemma topological_group_infi :
@topological_group G (⨅ i, ts' i) _ :=
by {rw ← Inf_range, exact topological_group_Inf (set.forall_range_iff.mpr h')}
omit h'
include h₁ h₂
@[to_additive] lemma topological_group_inf :
@topological_group G (t₁ ⊓ t₂) _ :=
by {rw inf_eq_infi, refine topological_group_infi (λ b, _), cases b; assumption}
omit h₁ h₂
@[to_additive] lemma topological_group_induced :
@topological_group G (t.induced f) _ :=
{ continuous_inv :=
begin
letI : topological_space G := t.induced f,
refine continuous_induced_rng _,
simp_rw [function.comp, map_inv],
exact continuous_inv.comp (continuous_induced_dom : continuous f)
end,
continuous_mul := @has_continuous_mul.continuous_mul G (t.induced f) _
(@has_continuous_mul_induced G H _ _ t _ _ _ f) }
end lattice_ops
/-!
### Lattice of group topologies
We define a type class `group_topology α` which endows a group `α` with a topology such that all
group operations are continuous.
Group topologies on a fixed group `α` are ordered, by reverse inclusion. They form a complete
lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology.
Any function `f : α → β` induces `coinduced f : topological_space α → group_topology β`.
The additive version `add_group_topology α` and corresponding results are provided as well.
-/
/-- A group topology on a group `α` is a topology for which multiplication and inversion
are continuous. -/
structure group_topology (α : Type u) [group α]
extends topological_space α, topological_group α : Type u
/-- An additive group topology on an additive group `α` is a topology for which addition and
negation are continuous. -/
structure add_group_topology (α : Type u) [add_group α]
extends topological_space α, topological_add_group α : Type u
attribute [to_additive] group_topology
namespace group_topology
variables [group α]
/-- A version of the global `continuous_mul` suitable for dot notation. -/
@[to_additive]
lemma continuous_mul' (g : group_topology α) :
by haveI := g.to_topological_space; exact continuous (λ p : α × α, p.1 * p.2) :=
begin
letI := g.to_topological_space,
haveI := g.to_topological_group,
exact continuous_mul,
end
/-- A version of the global `continuous_inv` suitable for dot notation. -/
@[to_additive]
lemma continuous_inv' (g : group_topology α) :
by haveI := g.to_topological_space; exact continuous (has_inv.inv : α → α) :=
begin
letI := g.to_topological_space,
haveI := g.to_topological_group,
exact continuous_inv,
end
@[to_additive]
lemma to_topological_space_injective :
function.injective (to_topological_space : group_topology α → topological_space α):=
λ f g h, by { cases f, cases g, congr' }
@[ext, to_additive]
lemma ext' {f g : group_topology α} (h : f.is_open = g.is_open) : f = g :=
to_topological_space_injective $ topological_space_eq h
/-- The ordering on group topologies on the group `γ`.
`t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/
@[to_additive]
instance : partial_order (group_topology α) :=
partial_order.lift to_topological_space to_topological_space_injective
@[simp, to_additive] lemma to_topological_space_le {x y : group_topology α} :
x.to_topological_space ≤ y.to_topological_space ↔ x ≤ y := iff.rfl
@[to_additive]
instance : has_top (group_topology α) :=
⟨{to_topological_space := ⊤,
continuous_mul := continuous_top,
continuous_inv := continuous_top}⟩
@[simp, to_additive] lemma to_topological_space_top :
(⊤ : group_topology α).to_topological_space = ⊤ := rfl
@[to_additive]
instance : has_bot (group_topology α) :=
⟨{to_topological_space := ⊥,
continuous_mul := by continuity,
continuous_inv := continuous_bot}⟩
@[simp, to_additive] lemma to_topological_space_bot :
(⊥ : group_topology α).to_topological_space = ⊥ := rfl
@[to_additive]
instance : bounded_order (group_topology α) :=
{ top := ⊤,
le_top := λ x, show x.to_topological_space ≤ ⊤, from le_top,
bot := ⊥,
bot_le := λ x, show ⊥ ≤ x.to_topological_space, from bot_le }
@[to_additive]
instance : has_inf (group_topology α) :=
{ inf := λ x y,
{ to_topological_space := x.to_topological_space ⊓ y.to_topological_space,
continuous_mul := continuous_inf_rng
(continuous_inf_dom_left₂ x.continuous_mul') (continuous_inf_dom_right₂ y.continuous_mul'),
continuous_inv := continuous_inf_rng
(continuous_inf_dom_left x.continuous_inv') (continuous_inf_dom_right y.continuous_inv') } }
@[simp, to_additive]
lemma to_topological_space_inf (x y : group_topology α) :
(x ⊓ y).to_topological_space = x.to_topological_space ⊓ y.to_topological_space := rfl
@[to_additive]
instance : semilattice_inf (group_topology α) :=
to_topological_space_injective.semilattice_inf _ to_topological_space_inf
@[to_additive]
instance : inhabited (group_topology α) := ⟨⊤⟩
local notation `cont` := @continuous _ _
@[to_additive "Infimum of a collection of additive group topologies"]
instance : has_Inf (group_topology α) :=
{ Inf := λ S,
{ to_topological_space := Inf (to_topological_space '' S),
continuous_mul := continuous_Inf_rng begin
rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI,
exact continuous_Inf_dom₂
(set.mem_image_of_mem to_topological_space haS)
(set.mem_image_of_mem to_topological_space haS) continuous_mul,
end,
continuous_inv := continuous_Inf_rng begin
rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI,
exact continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_inv,
end, } }
@[simp, to_additive]
lemma to_topological_space_Inf (s : set (group_topology α)) :
(Inf s).to_topological_space = Inf (to_topological_space '' s) := rfl
@[simp, to_additive]
lemma to_topological_space_infi {ι} (s : ι → group_topology α) :
(⨅ i, s i).to_topological_space = ⨅ i, (s i).to_topological_space :=
congr_arg Inf (range_comp _ _).symm
/-- Group topologies on `γ` form a complete lattice, with `⊥` the discrete topology and `⊤` the
indiscrete topology.
The infimum of a collection of group topologies is the topology generated by all their open sets
(which is a group topology).
The supremum of two group topologies `s` and `t` is the infimum of the family of all group
topologies contained in the intersection of `s` and `t`. -/
@[to_additive]
instance : complete_semilattice_Inf (group_topology α) :=
{ Inf_le := λ S a haS, to_topological_space_le.1 $ Inf_le ⟨a, haS, rfl⟩,
le_Inf :=
begin
intros S a hab,
apply topological_space.complete_lattice.le_Inf,
rintros _ ⟨b, hbS, rfl⟩,
exact hab b hbS,
end,
..group_topology.has_Inf,
..group_topology.partial_order }
@[to_additive]
instance : complete_lattice (group_topology α) :=
{ inf := (⊓),
top := ⊤,
bot := ⊥,
..group_topology.bounded_order,
..group_topology.semilattice_inf,
..complete_lattice_of_complete_semilattice_Inf _ }
/-- Given `f : α → β` and a topology on `α`, the coinduced group topology on `β` is the finest
topology such that `f` is continuous and `β` is a topological group. -/
@[to_additive "Given `f : α → β` and a topology on `α`, the coinduced additive group topology on `β`
is the finest topology such that `f` is continuous and `β` is a topological additive group."]
def coinduced {α β : Type*} [t : topological_space α] [group β] (f : α → β) :
group_topology β :=
Inf {b : group_topology β | (topological_space.coinduced f t) ≤ b.to_topological_space}
@[to_additive]
lemma coinduced_continuous {α β : Type*} [t : topological_space α] [group β]
(f : α → β) : cont t (coinduced f).to_topological_space f :=
begin
rw continuous_iff_coinduced_le,
refine le_Inf _,
rintros _ ⟨t', ht', rfl⟩,
exact ht',
end
end group_topology
|
[STATEMENT]
lemma sets_vimage_algebra_cong: "sets M = sets N \<Longrightarrow> sets (vimage_algebra X f M) = sets (vimage_algebra X f N)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sets M = sets N \<Longrightarrow> sets (vimage_algebra X f M) = sets (vimage_algebra X f N)
[PROOF STEP]
by (simp add: sets_vimage_algebra) |
lemma convex_epigraphI: "convex_on S f \<Longrightarrow> convex S \<Longrightarrow> convex (epigraph S f)" |
Formal statement is: lemma continuous_inj_imp_mono: fixes f :: "'a::linear_continuum_topology \<Rightarrow> 'b::linorder_topology" assumes x: "a < x" "x < b" and cont: "continuous_on {a..b} f" and inj: "inj_on f {a..b}" shows "(f a < f x \<and> f x < f b) \<or> (f b < f x \<and> f x < f a)" Informal statement is: If $f$ is a continuous injective function on an interval $[a,b]$, then $f(a) < f(x) < f(b)$ or $f(b) < f(x) < f(a)$. |
Formal statement is: lemma residue_simple': assumes s: "open s" "z \<in> s" and holo: "f holomorphic_on (s - {z})" and lim: "((\<lambda>w. f w * (w - z)) \<longlongrightarrow> c) (at z)" shows "residue f z = c" Informal statement is: If $f$ is holomorphic on $s - \{z\}$ and $\lim_{w \to z} f(w) (w - z) = c$, then the residue of $f$ at $z$ is $c$. |
/-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Chris Hughes, Mario Carneiro, Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.group.prod
import Mathlib.algebra.ring.basic
import Mathlib.data.equiv.ring
import Mathlib.PostPort
universes u_1 u_3 u_5 u_2 u_4
namespace Mathlib
/-!
# Semiring, ring etc structures on `R × S`
In this file we define two-binop (`semiring`, `ring` etc) structures on `R × S`. We also prove
trivial `simp` lemmas, and define the following operations on `ring_hom`s:
* `fst R S : R × S →+* R`, `snd R S : R × S →+* R`: projections `prod.fst` and `prod.snd`
as `ring_hom`s;
* `f.prod g : `R →+* S × T`: sends `x` to `(f x, g x)`;
* `f.prod_map g : `R × S → R' × S'`: `prod.map f g` as a `ring_hom`,
sends `(x, y)` to `(f x, g y)`.
-/
namespace prod
/-- Product of two semirings is a semiring. -/
protected instance semiring {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] :
semiring (R × S) :=
semiring.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry sorry monoid.mul sorry
monoid.one sorry sorry sorry sorry sorry sorry
/-- Product of two commutative semirings is a commutative semiring. -/
protected instance comm_semiring {R : Type u_1} {S : Type u_3} [comm_semiring R] [comm_semiring S] :
comm_semiring (R × S) :=
comm_semiring.mk semiring.add sorry semiring.zero sorry sorry sorry semiring.mul sorry
semiring.one sorry sorry sorry sorry sorry sorry sorry
/-- Product of two rings is a ring. -/
protected instance ring {R : Type u_1} {S : Type u_3} [ring R] [ring S] : ring (R × S) :=
ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg
add_comm_group.sub sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry
/-- Product of two commutative rings is a commutative ring. -/
protected instance comm_ring {R : Type u_1} {S : Type u_3} [comm_ring R] [comm_ring S] :
comm_ring (R × S) :=
comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry
ring.one sorry sorry sorry sorry sorry
end prod
namespace ring_hom
/-- Given semirings `R`, `S`, the natural projection homomorphism from `R × S` to `R`.-/
def fst (R : Type u_1) (S : Type u_3) [semiring R] [semiring S] : R × S →+* R :=
mk prod.fst sorry sorry sorry sorry
/-- Given semirings `R`, `S`, the natural projection homomorphism from `R × S` to `S`.-/
def snd (R : Type u_1) (S : Type u_3) [semiring R] [semiring S] : R × S →+* S :=
mk prod.snd sorry sorry sorry sorry
@[simp] theorem coe_fst {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] :
⇑(fst R S) = prod.fst :=
rfl
@[simp] theorem coe_snd {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] :
⇑(snd R S) = prod.snd :=
rfl
/-- Combine two ring homomorphisms `f : R →+* S`, `g : R →+* T` into `f.prod g : R →+* S × T`
given by `(f.prod g) x = (f x, g x)` -/
protected def prod {R : Type u_1} {S : Type u_3} {T : Type u_5} [semiring R] [semiring S]
[semiring T] (f : R →+* S) (g : R →+* T) : R →+* S × T :=
mk (fun (x : R) => (coe_fn f x, coe_fn g x)) sorry sorry sorry sorry
@[simp] theorem prod_apply {R : Type u_1} {S : Type u_3} {T : Type u_5} [semiring R] [semiring S]
[semiring T] (f : R →+* S) (g : R →+* T) (x : R) :
coe_fn (ring_hom.prod f g) x = (coe_fn f x, coe_fn g x) :=
rfl
@[simp] theorem fst_comp_prod {R : Type u_1} {S : Type u_3} {T : Type u_5} [semiring R] [semiring S]
[semiring T] (f : R →+* S) (g : R →+* T) : comp (fst S T) (ring_hom.prod f g) = f :=
ext fun (x : R) => rfl
@[simp] theorem snd_comp_prod {R : Type u_1} {S : Type u_3} {T : Type u_5} [semiring R] [semiring S]
[semiring T] (f : R →+* S) (g : R →+* T) : comp (snd S T) (ring_hom.prod f g) = g :=
ext fun (x : R) => rfl
theorem prod_unique {R : Type u_1} {S : Type u_3} {T : Type u_5} [semiring R] [semiring S]
[semiring T] (f : R →+* S × T) : ring_hom.prod (comp (fst S T) f) (comp (snd S T) f) = f :=
sorry
/-- `prod.map` as a `ring_hom`. -/
def prod_map {R : Type u_1} {R' : Type u_2} {S : Type u_3} {S' : Type u_4} [semiring R] [semiring S]
[semiring R'] [semiring S'] (f : R →+* R') (g : S →+* S') : R × S →* R' × S' :=
↑(ring_hom.prod (comp f (fst R S)) (comp g (snd R S)))
theorem prod_map_def {R : Type u_1} {R' : Type u_2} {S : Type u_3} {S' : Type u_4} [semiring R]
[semiring S] [semiring R'] [semiring S'] (f : R →+* R') (g : S →+* S') :
prod_map f g = ↑(ring_hom.prod (comp f (fst R S)) (comp g (snd R S))) :=
rfl
@[simp] theorem coe_prod_map {R : Type u_1} {R' : Type u_2} {S : Type u_3} {S' : Type u_4}
[semiring R] [semiring S] [semiring R'] [semiring S'] (f : R →+* R') (g : S →+* S') :
⇑(prod_map f g) = prod.map ⇑f ⇑g :=
rfl
theorem prod_comp_prod_map {R : Type u_1} {R' : Type u_2} {S : Type u_3} {S' : Type u_4}
{T : Type u_5} [semiring R] [semiring S] [semiring R'] [semiring S'] [semiring T] (f : T →* R)
(g : T →* S) (f' : R →* R') (g' : S →* S') :
monoid_hom.comp (monoid_hom.prod_map f' g') (monoid_hom.prod f g) =
monoid_hom.prod (monoid_hom.comp f' f) (monoid_hom.comp g' g) :=
rfl
end ring_hom
namespace ring_equiv
/-- Swapping components as an equivalence of (semi)rings. -/
def prod_comm {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] : R × S ≃+* S × R :=
mk (add_equiv.to_fun add_equiv.prod_comm) (add_equiv.inv_fun add_equiv.prod_comm) sorry sorry
sorry sorry
@[simp] theorem coe_prod_comm {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] :
⇑prod_comm = prod.swap :=
rfl
@[simp] theorem coe_prod_comm_symm {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] :
⇑(ring_equiv.symm prod_comm) = prod.swap :=
rfl
@[simp] theorem fst_comp_coe_prod_comm {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] :
ring_hom.comp (ring_hom.fst S R) ↑prod_comm = ring_hom.snd R S :=
ring_hom.ext fun (_x : R × S) => rfl
@[simp] theorem snd_comp_coe_prod_comm {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] :
ring_hom.comp (ring_hom.snd S R) ↑prod_comm = ring_hom.fst R S :=
ring_hom.ext fun (_x : R × S) => rfl
end Mathlib |
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn
-/
import algebra.group data.set.basic
universes u v
variable {α : Type u}
section
variable [semiring α]
theorem mul_two (n : α) : n * 2 = n + n :=
(left_distrib n 1 1).trans (by simp)
theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n :=
(two_mul _).symm
variable (α)
lemma zero_ne_one_or_forall_eq_0 : (0 : α) ≠ 1 ∨ (∀a:α, a = 0) :=
by haveI := classical.dec;
refine not_or_of_imp (λ h a, _); simpa using congr_arg ((*) a) h.symm
variable {α}
end
namespace units
variables [ring α] {a b : α}
instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩
@[simp] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl
@[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl
@[simp] protected theorem neg_neg (u : units α) : - -u = u :=
units.ext $ neg_neg _
@[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) :=
units.ext $ neg_mul_eq_neg_mul_symm _ _
@[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) :=
units.ext $ (neg_mul_eq_mul_neg _ _).symm
@[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp
protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp
end units
instance [semiring α] : semiring (with_zero α) :=
{ left_distrib := λ a b c, begin
cases a with a, {refl},
cases b with b; cases c with c; try {refl},
exact congr_arg some (left_distrib _ _ _)
end,
right_distrib := λ a b c, begin
cases c with c,
{ change (a + b) * 0 = a * 0 + b * 0, simp },
cases a with a; cases b with b; try {refl},
exact congr_arg some (right_distrib _ _ _)
end,
..with_zero.add_comm_monoid,
..with_zero.mul_zero_class,
..with_zero.monoid }
attribute [refl] dvd_refl
attribute [trans] dvd.trans
class is_semiring_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) : Prop :=
(map_zero : f 0 = 0)
(map_one : f 1 = 1)
(map_add : ∀ {x y}, f (x + y) = f x + f y)
(map_mul : ∀ {x y}, f (x * y) = f x * f y)
namespace is_semiring_hom
variables {β : Type v} [semiring α] [semiring β]
variables (f : α → β) [is_semiring_hom f] {x y : α}
instance id : is_semiring_hom (@id α) := by refine {..}; intros; refl
instance comp {γ} [semiring γ] (g : β → γ) [is_semiring_hom g] :
is_semiring_hom (g ∘ f) :=
{ map_zero := by simp [map_zero f]; exact map_zero g,
map_one := by simp [map_one f]; exact map_one g,
map_add := λ x y, by simp [map_add f]; rw map_add g; refl,
map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl }
instance : is_add_monoid_hom f :=
{ ..‹is_semiring_hom f› }
instance : is_monoid_hom f :=
{ ..‹is_semiring_hom f› }
end is_semiring_hom
@[simp] lemma zero_dvd_iff_eq_zero [comm_semiring α] (a : α) : 0 ∣ a ↔ a = 0 :=
iff.intro
eq_zero_of_zero_dvd
(assume ha, ha ▸ dvd_refl a)
section
variables [ring α] (a b c d e : α)
lemma mul_neg_one (a : α) : a * -1 = -a := by simp
lemma neg_one_mul (a : α) : -1 * a = -a := by simp
theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d :=
calc
a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp
... ↔ a * e + c - b * e = d : iff.intro (λ h, begin simp [h] end) (λ h,
begin simp [h.symm] end)
... ↔ (a - b) * e + c = d : begin simp [@sub_eq_add_neg α, @right_distrib α] end
theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d :=
assume h,
calc
(a - b) * e + c = (a * e + c) - b * e : begin simp [@sub_eq_add_neg α, @right_distrib α] end
... = d : begin rw h, simp [@add_sub_cancel α] end
theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : α} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 :=
begin
split,
{ intro ha, apply h, simp [ha] },
{ intro hb, apply h, simp [hb] }
end
end
@[simp] lemma zero_dvd_iff [comm_semiring α] {a : α} : 0 ∣ a ↔ a = 0 :=
⟨eq_zero_of_zero_dvd, λ h, by rw h⟩
section comm_ring
variable [comm_ring α]
@[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) :=
⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩
@[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) :=
⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩
end comm_ring
class is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) : Prop :=
(map_one : f 1 = 1)
(map_mul : ∀ {x y}, f (x * y) = f x * f y)
(map_add : ∀ {x y}, f (x + y) = f x + f y)
namespace is_ring_hom
variables {β : Type v} [ring α] [ring β]
def of_semiring (f : α → β) [H : is_semiring_hom f] : is_ring_hom f := {..H}
variables (f : α → β) [is_ring_hom f] {x y : α}
lemma map_zero : f 0 = 0 :=
calc f 0 = f (0 + 0) - f 0 : by rw [map_add f]; simp
... = 0 : by simp
lemma map_neg : f (-x) = -f x :=
calc f (-x) = f (-x + x) - f x : by rw [map_add f]; simp
... = -f x : by simp [map_zero f]
lemma map_sub : f (x - y) = f x - f y :=
by simp [map_add f, map_neg f]
instance id : is_ring_hom (@id α) := by refine {..}; intros; refl
instance comp {γ} [ring γ] (g : β → γ) [is_ring_hom g] :
is_ring_hom (g ∘ f) :=
{ map_add := λ x y, by simp [map_add f]; rw map_add g; refl,
map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl,
map_one := by simp [map_one f]; exact map_one g }
instance : is_semiring_hom f :=
{ map_zero := map_zero f, ..‹is_ring_hom f› }
instance : is_add_group_hom f :=
⟨λ _ _, map_add f⟩
end is_ring_hom
set_option old_structure_cmd true
class nonzero_comm_ring (α : Type*) extends zero_ne_one_class α, comm_ring α
instance integral_domain.to_nonzero_comm_ring (α : Type*) [id : integral_domain α] :
nonzero_comm_ring α :=
{ ..id }
/-- A domain is a ring with no zero divisors, i.e. satisfying
the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain
is an integral domain without assuming commutativity of multiplication. -/
class domain (α : Type u) extends ring α, no_zero_divisors α, zero_ne_one_class α
section domain
variable [domain α]
@[simp] theorem mul_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 :=
⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo,
or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩
@[simp] theorem zero_eq_mul {a b : α} : 0 = a * b ↔ a = 0 ∨ b = 0 :=
by rw [eq_comm, mul_eq_zero]
theorem mul_ne_zero' {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 :=
λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) h₁ h₂
theorem domain.mul_right_inj {a b c : α} (ha : a ≠ 0) : b * a = c * a ↔ b = c :=
by rw [← sub_eq_zero, ← mul_sub_right_distrib, mul_eq_zero];
simp [ha]; exact sub_eq_zero
theorem domain.mul_left_inj {a b c : α} (ha : a ≠ 0) : a * b = a * c ↔ b = c :=
by rw [← sub_eq_zero, ← mul_sub_left_distrib, mul_eq_zero];
simp [ha]; exact sub_eq_zero
theorem eq_zero_of_mul_eq_self_right' {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 :=
by apply (mul_eq_zero.1 _).resolve_right (sub_ne_zero.2 h₁);
rw [mul_sub_left_distrib, mul_one, sub_eq_zero, h₂]
theorem eq_zero_of_mul_eq_self_left' {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 :=
by apply (mul_eq_zero.1 _).resolve_left (sub_ne_zero.2 h₁);
rw [mul_sub_right_distrib, one_mul, sub_eq_zero, h₂]
theorem mul_ne_zero_comm' {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 :=
mul_ne_zero' (ne_zero_of_mul_ne_zero_left h) (ne_zero_of_mul_ne_zero_right h)
end domain
/- integral domains -/
section
variables [s : integral_domain α] (a b c d e : α)
include s
instance integral_domain.to_domain : domain α := {..s}
theorem eq_of_mul_eq_mul_right_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c :=
have b * a - c * a = 0, by simp [h],
have (b - c) * a = 0, by rw [mul_sub_right_distrib, this],
have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha,
eq_of_sub_eq_zero this
theorem eq_of_mul_eq_mul_left_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c :=
have a * b - a * c = 0, by simp [h],
have a * (b - c) = 0, by rw [mul_sub_left_distrib, this],
have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha,
eq_of_sub_eq_zero this
theorem mul_dvd_mul_iff_left {a b c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c :=
exists_congr $ λ d, by rw [mul_assoc, domain.mul_left_inj ha]
theorem mul_dvd_mul_iff_right {a b c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b :=
exists_congr $ λ d, by rw [mul_right_comm, domain.mul_right_inj hc]
end
/- units in various rings -/
namespace units
section comm_semiring
variables [comm_semiring α] (a b : α) (u : units α)
@[simp] lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩
@[simp] lemma dvd_coe_mul : a ∣ b * u ↔ a ∣ b :=
iff.intro
(assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩)
(assume ⟨c, eq⟩, eq.symm ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)
@[simp] lemma dvd_coe : a ∣ ↑u ↔ a ∣ 1 :=
suffices a ∣ 1 * ↑u ↔ a ∣ 1, by simpa,
dvd_coe_mul _ _ _
@[simp] lemma coe_mul_dvd : a * u ∣ b ↔ a ∣ b :=
iff.intro
(assume ⟨c, eq⟩, ⟨c * ↑u, eq.symm ▸ by ac_refl⟩)
(assume h, suffices a * ↑u ∣ b * 1, by simpa, mul_dvd_mul h (coe_dvd _ _))
end comm_semiring
section domain
variables [domain α]
@[simp] theorem ne_zero : ∀(u : units α), (↑u : α) ≠ 0
| ⟨u, v, (huv : 0 * v = 1), hvu⟩ rfl := by simpa using huv
end domain
end units
|
If $h$ is eventually nonzero, then $f/h$ is in $L^1$ if and only if $f$ is in $L^1$. |
Do You Need Residential Roofing Contractor in Hearne Texas?
Having a high-quality roof indicates that only a experienced contractor should be retained to do any repairing or even replacements. The only way to separate amateur roofing companies from the professional bunch is examining our jobs. As a roofing company in Hearne Texas, we help make our customers satisfied by giving them extremely reliable Residential Roofing Contractor.
The expert services our company offers are very reasonable, and this suggests that our customers could have their roofing problem remedied and not having to dig further in their bank account. Our friendly support desk is all set to assist our clients. Call Roofing Bryan to setup an appointment!
Prior to doing the actual roof repair, we hold appointments with the clients. This technique makes sure that our specialists are better set at choosing the correct methods to any sort of roofing problem at hand. The result is something that the clients as well as our firm are forever happy with.
Do You Want Residential Roofing Contractor in Hearne Texas? |
{-# OPTIONS --without-K --safe #-}
module Algebra.Linear.Structures.Bundles where
open import Algebra
open import Level using (Level; suc; _⊔_)
open import Relation.Binary using (Rel; IsEquivalence)
open import Algebra.FunctionProperties
open import Algebra.Structures.Field
open import Algebra.Structures.Bundles.Field
open import Algebra.Linear.Structures.VectorSpace
record RawVectorSpace {k ℓᵏ} (K : Field k ℓᵏ) (c ℓ : Level) : Set (suc (c ⊔ k ⊔ ℓ)) where
infix 20 _≈_
infixl 25 _+_
infixr 30 _∙_
field
Carrier : Set c
_≈_ : Rel Carrier ℓ
_+_ : Carrier -> Carrier -> Carrier
_∙_ : Field.Carrier K -> Carrier -> Carrier
-_ : Carrier -> Carrier
0# : Carrier
rawGroup : RawGroup c ℓ
rawGroup = record { _≈_ = _≈_; _∙_ = _+_; ε = 0#; _⁻¹ = -_ }
open RawGroup rawGroup public
using (rawMagma; rawMonoid)
record VectorSpace {k ℓᵏ} (K : Field k ℓᵏ) (c ℓ : Level) : Set (suc (c ⊔ k ⊔ ℓ ⊔ ℓᵏ)) where
infix 20 _≈_
infixl 25 _+_
infixr 30 _∙_
field
Carrier : Set c
_≈_ : Rel Carrier ℓ
_+_ : Carrier -> Carrier -> Carrier
_∙_ : Field.Carrier K -> Carrier -> Carrier
-_ : Carrier -> Carrier
0# : Carrier
isVectorSpace : IsVectorSpace K _≈_ _+_ _∙_ -_ 0#
open IsVectorSpace isVectorSpace public
rawVectorSpace : RawVectorSpace K c ℓ
rawVectorSpace = record
{ _≈_ = _≈_; _+_ = _+_; _∙_ = _∙_; -_ = -_; 0# = 0# }
abelianGroup : AbelianGroup c ℓ
abelianGroup = record { isAbelianGroup = isAbelianGroup }
open AbelianGroup abelianGroup public
using (rawMagma; magma; rawMonoid; monoid; rawGroup; group)
|
module Data.Union.Relation.Binary.Subtype where
open import Data.List using (List)
open import Data.List.Relation.Unary.Any using (here; there)
open import Data.List.Relation.Binary.Subset.Propositional using (_⊆_)
open import Data.Union using (Union; here; there; inj)
open import Function using (_∘_; id)
open import Relation.Binary.PropositionalEquality using () renaming (refl to refl≡)
open import Level using (Level; _⊔_)
-- ----------------------------------------------------------------------
-- Subtyping
private
variable
a b c d f : Level
A : Set a
B : Set b
C : Set c
D : Set d
F : A → Set f
ts ts′ : List A
infix 4 _≼_ _,_⊢_≼_
_≼_ : Set a → Set b → Set (a ⊔ b)
A ≼ B = A → B
_,_⊢_≼_ : (A : Set a) → (F : A → Set b) → List A → List A → Set (a ⊔ b)
A , F ⊢ ts ≼ ts′ = Union A F ts ≼ Union A F ts′
refl : A ≼ A
refl = id
trans : A ≼ B → B ≼ C → A ≼ C
trans A≼B B≼C = B≼C ∘ A≼B
generalize : ts ⊆ ts′ → A , F ⊢ ts ≼ ts′
generalize ts⊆ts′ (here x) = inj (ts⊆ts′ (here refl≡)) x
generalize ts⊆ts′ (there x) = generalize (ts⊆ts′ ∘ there) x
function : C ≼ A → B ≼ D → (A → B) ≼ (C → D)
function C≼A B≼D f = B≼D ∘ f ∘ C≼A
coerce : A ≼ B → A → B
coerce = id |
module NanoParsec.Parser
import NanoParsec.MonadPlus
%access export
record Parser a where
constructor MkParser
parse : String -> List (a, String)
runParser : Parser a -> String -> Maybe a
runParser p st =
case parse p st of
[(res, "")] => Just res
[(_, remSt)] => Nothing
_ => Nothing
item : Parser Char
item = MkParser $ \st =>
case st of
"" => []
_ => [(strHead st, strTail st)]
implementation Functor Parser where
map f (MkParser cs) = MkParser (\st => [(f a, b) | (a, b) <- cs st])
implementation Applicative Parser where
pure a = MkParser (\st => [(a, st)])
(MkParser cs1) <*> (MkParser cs2) =
MkParser (\st => [(f a, st2) | (f, st1) <- cs1 st, (a, st2) <- cs2 st1])
implementation Monad Parser where
p >>= f = MkParser $ \st => concatMap (\(a, st') => parse (f a) st') $ parse p st
combine : Parser a -> Parser a -> Parser a
combine p1 p2 = MkParser (\st => parse p1 st ++ parse p2 st)
failure : Parser a
failure = MkParser (\cs => [])
option : Parser a -> Parser a -> Parser a
option p1 p2 = MkParser $ \st =>
case parse p1 st of
[] => parse p2 st
res => res
satisfy : (Char -> Bool) -> Parser Char
satisfy pred = item >>= \ch => if (pred ch) then (return ch) else failure
implementation MonadPlus Parser where
mzero = failure
mplus = option
implementation Alternative Parser where
empty = failure
(<|>) = option
||| Extract at least one success.
some : (Alternative f, Applicative f) => f a -> f (List a)
some v = some_v
where
mutual
some_v : f (List a)
some_v = (map (::) v) <*> many_v
many_v : f (List a)
many_v = some_v <|> pure []
||| Extracts 0 or more successes.
many : (Alternative f, Applicative f) => f a -> f (List a)
many v = many_v
where
mutual
many_v : f (List a)
many_v = some_v <|> pure []
some_v : f (List a)
some_v = (map (::) v) <*> many_v
sepBy1 : Parser a -> Parser sep -> Parser (List a)
sepBy1 p sep = do
first <- p
remainder <- many (sep >>= \_ => p)
return (first :: remainder)
sepBy : Parser a -> Parser sep -> Parser (list a)
sepBy p sep = (p `sepBy1` sep) <|> pure List.Nil
|
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.Relation.Nullary.Base where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Function
open import Cubical.Functions.Fixpoint
open import Cubical.Data.Empty as ⊥
open import Cubical.HITs.PropositionalTruncation.Base
private
variable
ℓ : Level
A : Type ℓ
-- Negation
infix 3 ¬_
¬_ : Type ℓ → Type ℓ
¬ A = A → ⊥
-- Decidable types (inspired by standard library)
data Dec (P : Type ℓ) : Type ℓ where
yes : ( p : P) → Dec P
no : (¬p : ¬ P) → Dec P
NonEmpty : Type ℓ → Type ℓ
NonEmpty A = ¬ ¬ A
Stable : Type ℓ → Type ℓ
Stable A = NonEmpty A → A
-- reexport propositional truncation for uniformity
open Cubical.HITs.PropositionalTruncation.Base
using (∥_∥) public
SplitSupport : Type ℓ → Type ℓ
SplitSupport A = ∥ A ∥ → A
Collapsible : Type ℓ → Type ℓ
Collapsible A = Σ[ f ∈ (A → A) ] 2-Constant f
Populated ⟪_⟫ : Type ℓ → Type ℓ
Populated A = (f : Collapsible A) → Fixpoint (f .fst)
⟪_⟫ = Populated
PStable : Type ℓ → Type ℓ
PStable A = ⟪ A ⟫ → A
onAllPaths : (Type ℓ → Type ℓ) → Type ℓ → Type ℓ
onAllPaths S A = (x y : A) → S (x ≡ y)
Separated : Type ℓ → Type ℓ
Separated = onAllPaths Stable
HSeparated : Type ℓ → Type ℓ
HSeparated = onAllPaths SplitSupport
Collapsible≡ : Type ℓ → Type ℓ
Collapsible≡ = onAllPaths Collapsible
PStable≡ : Type ℓ → Type ℓ
PStable≡ = onAllPaths PStable
Discrete : Type ℓ → Type ℓ
Discrete = onAllPaths Dec
|
import tactic
import tactic.induction
namespace pred_logic
universe u
structure language (α β : Type u) :=
(hαβ : α ≠ β)
(rel_symbols : set α)
(func_symbols : set β)
(rel_arity : α → ℕ)
(func_arity : β → ℕ)
inductive term {α β : Type u} (𝓛 : language α β)
| var : ℕ → term
| func {f : β} (f ∈ 𝓛.func_symbols) : (fin (𝓛.func_arity f) → term) → term
inductive formula {α β : Type u} (𝓛 : language α β)
| bot : formula
| relation {R : α} (R ∈ 𝓛.rel_symbols) : (fin (𝓛.rel_arity R) → term 𝓛) → formula
| Exists : ℕ → formula → formula
| imp : formula → formula → formula
variables {α β : Type u} {𝓛 : language α β}
def term_vars : term 𝓛 → ℕ → Prop
| (term.var m) n := m = n
| (term.func f hf terms) n := ∃m : (fin (𝓛.func_arity f)), term_vars (terms m) n
def free_vars : formula 𝓛 → ℕ → Prop
| formula.bot m := false
| (formula.Exists n φ) m := m ≠ n ∧ free_vars φ m
| (formula.imp φ ψ) m := free_vars φ m ∨ free_vars ψ m
| (formula.relation R hR terms) m := ∃n : (fin (𝓛.rel_arity R)), term_vars (terms n) m
structure interpretation (𝓛 : language α β) :=
(domain : Type)
(to_func : ∀{f}, f ∈ 𝓛.func_symbols → (fin (𝓛.func_arity f) → domain) → domain)
(to_rel : ∀{R}, R ∈ 𝓛.rel_symbols → (fin (𝓛.rel_arity R) → domain) → Prop)
variable {M : interpretation 𝓛}
def assignment (M : interpretation 𝓛) := ℕ → M.domain
def replace (s : assignment M) (n : ℕ) (m : M.domain) : assignment M :=
λk, if k = n then m else s k
lemma replace_pos {s : assignment M} {n : ℕ} {m : M.domain}
: replace s n m n = m := if_pos rfl
lemma replace_neg {s : assignment M} {n : ℕ} {m : M.domain} {k : ℕ}
: k ≠ n → replace s n m k = s k := λhk, if_neg hk
def value (s : assignment M) : term 𝓛 → M.domain
| (term.var n) := s n
| (term.func f hf terms) := let v := λk, value (terms k) in M.to_func hf v
def satisfies : assignment M → formula 𝓛 → Prop
| s (formula.bot) := false
| s (formula.relation R hR terms) := M.to_rel hR (value s ∘ terms)
| s (formula.imp φ ψ) := satisfies s φ → satisfies s ψ
| s (formula.Exists n φ) := ∃(m : M.domain), satisfies (replace s n m) φ
example {s s' : assignment M} {u : term 𝓛} :
(∀n, term_vars u n → s n = s' n) → value s u = value s' u :=
begin
intro h,
induction' u with u f g g_func g_args ih,
{exact h u rfl},
{
unfold value,
simp,
apply congr_arg,
sorry,
},
end
lemma satisfies_of_agree_free {s s' : assignment M} (φ : formula 𝓛) :
(∀{n}, free_vars φ n → s n = s' n) → satisfies s φ → satisfies s' φ :=
begin
intros agree_free hsφ,
induction' φ,
{exfalso,exact hsφ},
{
unfold satisfies at *,
sorry,
}, repeat {sorry},
end
end pred_logic |
The coefficient of $x^k$ in the product of a monomial $cx^n$ and a polynomial $p$ is $0$ if $k < n$, and $c$ times the coefficient of $x^{k-n}$ in $p$ otherwise. |
{-# OPTIONS --without-K --rewriting --allow-unsolved-metas #-}
open import HoTT renaming (pt to pt⊙)
open import homotopy.DisjointlyPointedSet
open import lib.types.Nat
open import lib.types.Vec
module simplicial.Base where
-- HELPERS
combinations : ℕ → List ℕ -> List (List ℕ)
combinations 0 _ = nil :: nil
combinations _ nil = nil
combinations (S n) (x :: xs) = (map (λ ys → x :: ys) (combinations (n) xs)) ++ (combinations (S n) xs)
standardSimplex : ℕ → List ℕ
standardSimplex O = nil
standardSimplex (S x) = (S x) :: (standardSimplex x)
-- UGLY HELPER FUNCTIONS -- TO BE REPLACED WITH STANDARD FUNCTIONS LATER ON
bfilter : {A : Type₀} → ((a : A) → Bool) → List A → List A
bfilter f nil = nil
bfilter f (a :: l) with f a
... | inl _ = a :: (bfilter f l)
... | inr _ = bfilter f l
ℕin : ℕ → List ℕ → Bool
ℕin x nil = inr unit
ℕin x (y :: ys) with ℕ-has-dec-eq x y
... | inl x₁ = inl unit
... | inr x₁ = inr unit
_lsubset_ : List ℕ → List ℕ → Bool
nil lsubset ys = inl unit
(x :: xs) lsubset ys with ℕin x ys
... | inl _ = xs lsubset ys
... | inr _ = inr unit
-- TYPES FOR SIMPLICES
-- 'Simplices' saves a collection of simplices, grouped by their dimension.
-- Note that we do not specify the dimensions of individual simplices, since
-- otherwise we could not simply save all simplices in a single vector
Simplex = List ℕ
Simplices : ℕ → Type₀
Simplices dim = (Vec (List Simplex) dim)
is-closed : {dim : ℕ} → (Simplices dim) → Type₀
record SC (dim : ℕ) : Type₀ where
constructor complex
field
simplices : Simplices dim
closed : is-closed simplices
simplices : {dim : ℕ} → SC dim → Simplices dim
simplices (complex simplices _) = simplices
faces : Simplex → List Simplex
faces s = concat (map (λ l → combinations l s) (standardSimplex (ℕ-pred (length s))))
-- removes grouping of simplices by dimension and puts all simplices in single list
compress : {dim : ℕ} → Simplices dim → List Simplex
compress {dim} [] = nil
compress {dim} (xs ∷ xss) = xs ++ compress xss
bodies : {dim : ℕ} → (SC dim) → Simplex → List Simplex
bodies (complex ss _) s = bfilter (λ o → (s lsubset o)) (compress ss)
-- inverse of compress function
unfold : {dim : ℕ} → List Simplex → Simplices dim
unfold {dim} ss = unfold' {dim} ss (emptyss dim)
where
emptyss : (dim : ℕ) → Simplices dim
emptyss 0 = []
emptyss (S n) = nil ∷ (emptyss n)
unfold' : {dim : ℕ} → List Simplex → Simplices dim → Simplices dim
unfold' {dim} nil sc = sc
unfold' {dim} (x :: ss) sc = insert (faces x) sc
where
insert : {dim : ℕ} → List Simplex → Simplices dim → Simplices dim
insert nil sc = sc
insert (s :: ss) sc = insertS s sc
where
insertS : {dim : ℕ} → Simplex → Simplices dim → Simplices dim
insertS s sc = updateAt ((length s) , {!!}) (λ l → s :: l) sc
is-closed {dim} ss = All (λ s → All (λ f → f ∈ ssc) (faces s)) ssc
where ssc = compress ss
-- takes facet description of SC and generates their face closure
SCgenerator : (dim : ℕ) → List Simplex → SC dim
SC.simplices (SCgenerator dim ss) = unfold $ concat(concat (map(λ simplex → map (λ l → combinations l simplex) (standardSimplex (length simplex))) ss))
SC.closed (SCgenerator dim ss) = {!!}
-- EXAMPLES
sc-unit : SC 2
SC.simplices sc-unit = ((1 :: nil) :: (2 :: nil) :: nil) ∷ ((1 :: 2 :: nil) :: nil) ∷ []
SC.closed sc-unit = nil :: (nil :: (((here idp) :: ((there (here idp)) :: nil)) :: nil))
sc-circle : SC 2
SC.simplices sc-circle =
((1 :: nil) :: (2 :: nil) :: (3 :: nil) :: nil) ∷
((1 :: 2 :: nil) :: (1 :: 3 :: nil) :: (2 :: 3 :: nil) :: nil) ∷ []
SC.closed sc-circle = nil :: (nil :: (nil :: (((here idp) :: ((there (here idp)) :: nil)) :: (((here idp) :: ((there (there (here idp))) :: nil)) :: ((there (here idp) :: (there (there (here idp)) :: nil)) :: nil)))))
-- sc-circle-equiv-cw-circle : CWSphere 1 ≃ CWSphere 1
-- sc-circle-equiv-cw-circle = {!!}
sc-sphere : SC 3
sc-sphere = SCgenerator 3 ((1 :: 2 :: 3 :: nil) :: (1 :: 3 :: 4 :: nil) :: (2 :: 3 :: 4 :: nil) :: (1 :: 3 :: 4 :: nil) :: nil)
sc-unit-gen : SC 2
sc-unit-gen = SCgenerator 2 ((1 :: 2 :: nil) :: nil)
-- sc-unit≃sc-unit-gen : sc-unit ≃ sc-unit-gen
-- sc-unit≃sc-unit-gen = ?
|
{-# OPTIONS --without-K #-}
module Common.Unit where
open import Agda.Builtin.Unit public renaming (⊤ to Unit; tt to unit)
|
Base.:+(x::ExactReal, y::ExactReal) = ExactReal(n -> (x(n+2) + y(n+2) + 2) >> 2)
Base.:-(x::ExactReal) = ExactReal(n->-x(n))
Base.:-(x::ExactReal, y::ExactReal) = x + (-y)
Base.:-(x::Union{Rational, Integer}, y::ExactReal) = ExactReal(x) - y
"Most significant digit"
function msd(x::ExactReal)
x.msd > -1 && return x.msd
n = 0
while x(n) == 0
n += 1
end
x.msd = n
return n
end
function Base.:*(x::ExactReal, y::ExactReal)
return ExactReal(n -> begin
p = max(n - msd(y) + 4, n + 3 >> 1)
q = max(n - msd(x) + 4, n + 3 >> 1)
(1 + x(p) * y(q)) >> (p + q - n)
end
)
end
Base.:*(x::Rational, y::ExactReal) = ExactReal(x) * y
Base.sqrt(x::ExactReal) = ExactReal(n -> isqrt(x(2n)))
"Returns -1 if x < y and +1 if x > y"
function compare(x::ExactReal, y::ExactReal)
n = 0
while true
xn, yn = x(n), y(n)
xn < yn - 1 && return -1 # x < y
xn > yn + 1 && return 1 # x > y
n += 1
end
end
Base.:<(x::ExactReal, y::ExactReal) = compare(x, y) == -1
|
module Automata.Composition.Union (Σ : Set) where
-- Standard libraries imports ----------------------------------------
open import Data.Empty using (⊥ ; ⊥-elim)
open import Data.Nat using (ℕ)
open import Data.Sum using (_⊎_ ; inj₁ ; inj₂)
open import Data.Product using (_,_)
open import Data.Vec using (Vec ; [] ; _∷_)
open import Relation.Nullary using (¬_)
open import Relation.Binary.PropositionalEquality
using (_≡_ ; refl)
----------------------------------------------------------------------
-- Thesis imports ----------------------------------------------------
open import Automata.Nondeterministic
----------------------------------------------------------------------
_∪_ : (M : NDA Σ) → (N : NDA Σ) → NDA Σ
⟨ Q₁ , S₁ , F₁ , Δ₁ ⟩ ∪ ⟨ Q₂ , S₂ , F₂ , Δ₂ ⟩ = ⟨ Q , S , F , Δ ⟩
where
Q : Set _
Q = Q₁ ⊎ Q₂
S : Q → Set _
S (inj₁ q) = S₁ q
S (inj₂ q) = S₂ q
F : Q → Set
F (inj₁ q) = F₁ q
F (inj₂ q) = F₂ q
Δ : Q → Σ → Q → Set
Δ (inj₁ q) c (inj₁ q′) = Δ₁ q c q′
Δ (inj₂ q) c (inj₂ q′) = Δ₂ q c q′
{-# CATCHALL #-}
Δ _ _ _ = ⊥ -- No connections between the machines
M-Δ*⇒M∪N-Δ* : {M N : NDA Σ}
→ let Q₁ = NDA.Q M
Δ₁* = NDA.Δ* M
Δ* = NDA.Δ* (M ∪ N) in
(q : Q₁) → {n : ℕ} → (xs : Vec Σ n) → (q′ : Q₁)
→ Δ₁* q xs q′
→ Δ* (inj₁ q) xs (inj₁ q′)
M-Δ*⇒M∪N-Δ* q [] .q refl = refl
M-Δ*⇒M∪N-Δ* q (x ∷ xs) q′ (q₀ , Δ₁-q-x-q₀ , Δ₁*-q₀-xs-q′) =
inj₁ q₀ , Δ₁-q-x-q₀ , M-Δ*⇒M∪N-Δ* q₀ xs q′ Δ₁*-q₀-xs-q′
N-Δ*⇒M∪N-Δ* : {M N : NDA Σ}
→ let Q₂ = NDA.Q N
Δ₂* = NDA.Δ* N
Δ* = NDA.Δ* (M ∪ N) in
(q : Q₂) → {n : ℕ} → (xs : Vec Σ n) → (q′ : Q₂)
→ Δ₂* q xs q′
→ Δ* (inj₂ q) xs (inj₂ q′)
N-Δ*⇒M∪N-Δ* q [] .q refl = refl
N-Δ*⇒M∪N-Δ* q (x ∷ xs) q′ (q₀ , Δ₂-q-x-q₀ , Δ₂*-q₀-xs-q′) =
inj₂ q₀ , Δ₂-q-x-q₀ , N-Δ*⇒M∪N-Δ* q₀ xs q′ Δ₂*-q₀-xs-q′
M∪N-Δ*⇒M-Δ* : {M N : NDA Σ}
→ let Q₁ = NDA.Q M
Δ₁* = NDA.Δ* M
Δ* = NDA.Δ* (M ∪ N) in
(q : Q₁) → {n : ℕ} → (xs : Vec Σ n) → (q′ : Q₁)
→ Δ* (inj₁ q) xs (inj₁ q′)
→ Δ₁* q xs q′
M∪N-Δ*⇒M-Δ* q [] .q refl = refl
M∪N-Δ*⇒M-Δ* q (x ∷ xs) q′ (inj₁ q₀ , Δ-q-x-q₀ , Δ*-q₀-xs-q′) =
q₀ , Δ-q-x-q₀ , M∪N-Δ*⇒M-Δ* q₀ xs q′ Δ*-q₀-xs-q′
M∪N-Δ*⇒N-Δ* : {M N : NDA Σ}
→ let Q₂ = NDA.Q N
Δ₂* = NDA.Δ* N
Δ* = NDA.Δ* (M ∪ N) in
(q : Q₂) → {n : ℕ} → (xs : Vec Σ n) → (q′ : Q₂)
→ Δ* (inj₂ q) xs (inj₂ q′)
→ Δ₂* q xs q′
M∪N-Δ*⇒N-Δ* q [] .q refl = refl
M∪N-Δ*⇒N-Δ* q (x ∷ xs) q′ (inj₂ q₀ , Δ-q-x-q₀ , Δ*-q₀-xs-q′) =
q₀ , Δ-q-x-q₀ , M∪N-Δ*⇒N-Δ* q₀ xs q′ Δ*-q₀-xs-q′
M∪N-Δ*-disconnectedˡ : {M N : NDA Σ}
→ let Q₁ = NDA.Q M
Q₂ = NDA.Q N
Δ* = NDA.Δ* (M ∪ N) in
(q : Q₁) → {n : ℕ} → (xs : Vec Σ n) → (q′ : Q₂)
→ ¬ (Δ* (inj₁ q) xs (inj₂ q′))
M∪N-Δ*-disconnectedˡ q (x ∷ xs) q′ (inj₁ q₀ , _ , Δ*-q₀-xs-q′) =
M∪N-Δ*-disconnectedˡ q₀ xs q′ Δ*-q₀-xs-q′
M∪N-Δ*-disconnectedʳ : {M N : NDA Σ}
→ let Q₁ = NDA.Q M
Q₂ = NDA.Q N
Δ* = NDA.Δ* (M ∪ N) in
(q : Q₂) → {n : ℕ} → (xs : Vec Σ n) → (q′ : Q₁)
→ ¬ (Δ* (inj₂ q) xs (inj₁ q′))
M∪N-Δ*-disconnectedʳ q (x ∷ xs) q′ (inj₂ q₀ , _ , Δ*-q₀-xs-q′) =
M∪N-Δ*-disconnectedʳ q₀ xs q′ Δ*-q₀-xs-q′
M-Accepts⇒M∪N-Accepts : {M N : NDA Σ}
→ {n : ℕ} → (xs : Vec Σ n)
→ NDA.Accepts M xs
→ NDA.Accepts (M ∪ N) xs
M-Accepts⇒M∪N-Accepts [] (q , S-q , .q , F-q , refl) =
inj₁ q , S-q , inj₁ q , F-q , refl
M-Accepts⇒M∪N-Accepts (x ∷ xs)
( q , S-q -- The beginning state
, q′ , F-q′ -- The ending state
, q₀ , Δ₁-q-x-q₀ -- The first step
, Δ₁*-q₀-xs-q′) = -- The remaining steps
-- Translate to the union:
(inj₁ q , S-q -- The beginning state
, inj₁ q′ , F-q′ -- The ending state
, inj₁ q₀ , Δ₁-q-x-q₀ -- The first step
, M-Δ*⇒M∪N-Δ* q₀ xs q′ Δ₁*-q₀-xs-q′) -- The remaining steps (applying I.H.)
N-Accepts⇒M∪N-Accepts : {M N : NDA Σ}
→ {n : ℕ} → (xs : Vec Σ n)
→ NDA.Accepts N xs
→ NDA.Accepts (M ∪ N) xs
N-Accepts⇒M∪N-Accepts [] (q , S-q , .q , F-q , refl) =
inj₂ q , S-q , inj₂ q , F-q , refl
N-Accepts⇒M∪N-Accepts (x ∷ xs)
( q , S-q
, q′ , F-q′
, q₀ , Δ-q-x-q₀
, Δ*-q₀-xs-q′) =
( inj₂ q , S-q
, inj₂ q′ , F-q′
, inj₂ q₀ , Δ-q-x-q₀
, N-Δ*⇒M∪N-Δ* q₀ xs q′ Δ*-q₀-xs-q′ )
----------------------------------------------------------------------
M∪N-Accepts⇒M-Accepts∨N-Accepts : {M N : NDA Σ}
→ {n : ℕ} → (xs : Vec Σ n)
→ NDA.Accepts (M ∪ N) xs
→ NDA.Accepts M xs ⊎ NDA.Accepts N xs
-- Base cases.
M∪N-Accepts⇒M-Accepts∨N-Accepts []
(inj₁ q , S-q , .(inj₁ q) , F-q , refl) =
inj₁ (q , S-q , q , F-q , refl)
M∪N-Accepts⇒M-Accepts∨N-Accepts []
(inj₂ q , S-q , .(inj₂ q) , F-q , refl) =
inj₂ (q , S-q , q , F-q , refl)
-- Induction step 1: both the start and final state are in M.
M∪N-Accepts⇒M-Accepts∨N-Accepts (x ∷ xs)
( inj₁ q , S-q
, inj₁ q′ , F-q′
, inj₁ q₀ , Δ-q-x-q₀
, Δ*-q₀-xs-q′) =
inj₁ ( q , S-q
, q′ , F-q′
, q₀ , Δ-q-x-q₀
, M∪N-Δ*⇒M-Δ* q₀ xs q′ Δ*-q₀-xs-q′)
-- Induction step 2: both the start and final state are in N.
M∪N-Accepts⇒M-Accepts∨N-Accepts (x ∷ xs)
( inj₂ q , S-q
, inj₂ q′ , F-q′
, inj₂ q₀ , Δ-q-x-q₀
, Δ*-q₀-xs-q′) =
inj₂ ( q , S-q
, q′ , F-q′
, q₀ , Δ-q-x-q₀
, M∪N-Δ*⇒N-Δ* q₀ xs q′ Δ*-q₀-xs-q′)
-- Unreachable cases: the proof of “Accepts (M ∪ N) xs”
-- asserts M and N are connected.
M∪N-Accepts⇒M-Accepts∨N-Accepts (x ∷ xs)
(inj₁ q , _ , inj₂ q′ , _ , inj₁ q₀ , _ , Δ*-q₀-xs-q′) =
⊥-elim (M∪N-Δ*-disconnectedˡ q₀ xs q′ Δ*-q₀-xs-q′)
M∪N-Accepts⇒M-Accepts∨N-Accepts (x ∷ xs)
(inj₂ q , _ , inj₁ q′ , _ , inj₂ q₀ , _ , Δ*-q₀-xs-q′) =
⊥-elim (M∪N-Δ*-disconnectedʳ q₀ xs q′ Δ*-q₀-xs-q′)
----------------------------------------------------------------------
|
[STATEMENT]
lemma map_add_subsumed1: "f \<subseteq>\<^sub>m g \<Longrightarrow> f++g = g"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. f \<subseteq>\<^sub>m g \<Longrightarrow> f ++ g = g
[PROOF STEP]
by (simp add: map_add_le_mapI map_le_antisym) |
Formal statement is: lemma setdist_le_dist: "\<lbrakk>x \<in> s; y \<in> t\<rbrakk> \<Longrightarrow> setdist s t \<le> dist x y" Informal statement is: If $x$ is in $s$ and $y$ is in $t$, then the distance between $s$ and $t$ is less than or equal to the distance between $x$ and $y$. |
-- {-# OPTIONS -v tc.meta.assign:50 #-}
module Issue483c where
import Common.Level
data _≡_ {A : Set}(a : A) : A → Set where
refl : a ≡ a
data ⊥ : Set where
record ⊤ : Set where
refute : .⊥ → ⊥
refute ()
mk⊤ : ⊥ → ⊤
mk⊤ ()
X : .⊤ → ⊥
bad : .(x : ⊥) → X (mk⊤ x) ≡ refute x
X = _
bad x = refl
false : ⊥
false = X _
|
2007-2009, Vocational Qualification Tailoring, Title: Women’s Dressmaker.
2000-2003 Gothenburg Sweden, Upper Secondary School, Technical program with a focus on industrial design. Art, Design, Construction and CAD.
2007 to current, Bridal, larp, costumes, bellydance costumes, corsetry, production samples and more.
2012 London, 2 weeks work placement in the textile conservation department. Mounting and packing parts of the ‘Hollywood Costume’ exhibition.
2006-2008 Gothenburg Sweden, shop manager for a corset boutique, display, alterations, buying and more.
References and further details given on request. |
//////////////////////////////////////////////////////////////////////////////////////////////
/// \file DcsLossFunc.hpp
///
/// \author Sean Anderson, ASRL
//////////////////////////////////////////////////////////////////////////////////////////////
#ifndef STEAM_DCS_LOSS_FUNCTION_HPP
#define STEAM_DCS_LOSS_FUNCTION_HPP
#include <Eigen/Core>
#include <steam/problem/lossfunc/LossFunctionBase.hpp>
namespace steam {
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Huber loss function class
//////////////////////////////////////////////////////////////////////////////////////////////
class DcsLossFunc : public LossFunctionBase
{
public:
/// Convenience typedefs
typedef std::shared_ptr<DcsLossFunc> Ptr;
typedef std::shared_ptr<const DcsLossFunc> ConstPtr;
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Constructor -- k is the `threshold' based on number of std devs (1-3 is typical)
//////////////////////////////////////////////////////////////////////////////////////////////
DcsLossFunc(double k) : k2_(k*k) {}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Cost function (basic evaluation of the loss function)
//////////////////////////////////////////////////////////////////////////////////////////////
virtual double cost(double whitened_error_norm) const;
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Weight for iteratively reweighted least-squares (influence function div. by error)
//////////////////////////////////////////////////////////////////////////////////////////////
virtual double weight(double whitened_error_norm) const;
private:
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Huber constant
//////////////////////////////////////////////////////////////////////////////////////////////
double k2_;
};
} // steam
#endif // STEAM_DCS_LOSS_FUNCTION_HPP
|
------------------------------------------------------------------------
-- The Agda standard library
--
-- Rational numbers in non-reduced form.
------------------------------------------------------------------------
{-# OPTIONS --without-K --safe #-}
module Data.Rational.Unnormalised where
open import Data.Integer.Base as ℤ using (ℤ; ∣_∣; +_; +0; +[1+_]; -[1+_])
open import Data.Nat as ℕ using (ℕ; zero; suc)
open import Level using (0ℓ)
open import Relation.Nullary using (¬_)
open import Relation.Nullary.Decidable using (False)
open import Relation.Binary using (Rel)
open import Relation.Binary.PropositionalEquality using (_≡_)
------------------------------------------------------------------------
-- Definition
-- Here we define rationals that are not necessarily in reduced form.
-- Consequently there are multiple ways of representing a given rational
-- number, and the performance of the arithmetic operations may suffer
-- due to blowup of the numerator and denominator.
-- Nonetheless they are much easier to reason about. In general proofs
-- are first proved for these unnormalised rationals and then translated
-- into the normalised rationals.
record ℚᵘ : Set where
constructor mkℚᵘ
field
numerator : ℤ
denominator-1 : ℕ
denominatorℕ : ℕ
denominatorℕ = suc denominator-1
denominator : ℤ
denominator = + denominatorℕ
open ℚᵘ public using ()
renaming
( numerator to ↥_
; denominator to ↧_
; denominatorℕ to ↧ₙ_
)
------------------------------------------------------------------------
-- Equality of rational numbers (does not coincide with _≡_)
infix 4 _≃_
data _≃_ : Rel ℚᵘ 0ℓ where
*≡* : ∀ {p q} → (↥ p ℤ.* ↧ q) ≡ (↥ q ℤ.* ↧ p) → p ≃ q
------------------------------------------------------------------------
-- Ordering of rationals
infix 4 _≤_ _<_ _≥_ _>_ _≰_ _≱_ _≮_ _≯_
data _≤_ : Rel ℚᵘ 0ℓ where
*≤* : ∀ {p q} → (↥ p ℤ.* ↧ q) ℤ.≤ (↥ q ℤ.* ↧ p) → p ≤ q
data _<_ : Rel ℚᵘ 0ℓ where
*<* : ∀ {p q} → (↥ p ℤ.* ↧ q) ℤ.< (↥ q ℤ.* ↧ p) → p < q
_≥_ : Rel ℚᵘ 0ℓ
x ≥ y = y ≤ x
_>_ : Rel ℚᵘ 0ℓ
x > y = y < x
_≰_ : Rel ℚᵘ 0ℓ
x ≰ y = ¬ (x ≤ y)
_≱_ : Rel ℚᵘ 0ℓ
x ≱ y = ¬ (x ≥ y)
_≮_ : Rel ℚᵘ 0ℓ
x ≮ y = ¬ (x < y)
_≯_ : Rel ℚᵘ 0ℓ
x ≯ y = ¬ (x > y)
------------------------------------------------------------------------
-- Constructing rationals
infix 4 _≢0
_≢0 : ℕ → Set
n ≢0 = False (n ℕ.≟ 0)
-- An alternative constructor for ℚᵘ. See the constants section below
-- for examples of how to use this operator.
infixl 7 _/_
_/_ : (n : ℤ) (d : ℕ) .{d≢0 : d ≢0} → ℚᵘ
n / suc d = mkℚᵘ n d
------------------------------------------------------------------------------
-- Operations on rationals
infix 8 -_ 1/_
infixl 7 _*_ _÷_
infixl 6 _-_ _+_
-- negation
-_ : ℚᵘ → ℚᵘ
- mkℚᵘ n d = mkℚᵘ (ℤ.- n) d
-- addition
_+_ : ℚᵘ → ℚᵘ → ℚᵘ
p + q = (↥ p ℤ.* ↧ q ℤ.+ ↥ q ℤ.* ↧ p) / (↧ₙ p ℕ.* ↧ₙ q)
-- multiplication
_*_ : ℚᵘ → ℚᵘ → ℚᵘ
p * q = (↥ p ℤ.* ↥ q) / (↧ₙ p ℕ.* ↧ₙ q)
-- subtraction
_-_ : ℚᵘ → ℚᵘ → ℚᵘ
p - q = p + (- q)
-- reciprocal: requires a proof that the numerator is not zero
1/_ : (p : ℚᵘ) → .{n≢0 : ∣ ↥ p ∣ ≢0} → ℚᵘ
1/ mkℚᵘ +[1+ n ] d = mkℚᵘ +[1+ d ] n
1/ mkℚᵘ -[1+ n ] d = mkℚᵘ -[1+ d ] n
-- division: requires a proof that the denominator is not zero
_÷_ : (p q : ℚᵘ) → .{n≢0 : ∣ ↥ q ∣ ≢0} → ℚᵘ
(p ÷ q) {n≢0} = p * (1/_ q {n≢0})
------------------------------------------------------------------------------
-- Some constants
0ℚᵘ : ℚᵘ
0ℚᵘ = + 0 / 1
1ℚᵘ : ℚᵘ
1ℚᵘ = + 1 / 1
½ : ℚᵘ
½ = + 1 / 2
-½ : ℚᵘ
-½ = - ½
|
%% LyX 1.6.5 created this file. For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage[a4paper]{geometry}
\geometry{verbose,tmargin=3cm,bmargin=3cm,lmargin=2cm,rmargin=2cm}
\setlength{\parskip}{\medskipamount}
\setlength{\parindent}{0pt}
\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
\usepackage{fancyhdr}
\pagestyle{fancy}
\rhead{Notes\ on\ pricing\ of\ crop\ monitoring\ data,\ \today}
\makeatother
\usepackage{babel}
\begin{document}
\section*{The problem}
We want to monitor the spread of viral disease among staple crops.
Interested in two things: incidence and severity.
Survey workers can provide geotagged images of crops, in return for
micropayments of airtime or mobile money.
Use changing prices (as a function of location) to create the right
bias for data collection.
Assume computer vision software on the survey device can reject images
which have low information (not of a leaf/out of focus).
\section*{The model}
Start with a Gaussian process with squared exponential covariance
(lat,lon,time).
Advantages: posterior is centred around the data points. Disadvantages:
could become computationally expensive with large numbers of datapoints.
Two coupled models: severity and incidence. (Are these two things
related? Or conditionally independent given the observations?)
Nature of observations: tropical agriculture standards for levels
of disease severity, CMD symptoms are quantified from 0 (no damage)
to 5 (very damaged). Seems easiest to use these; a lot of thought
has gone into this quantification. Alternatives: degree of belief
that plant is infected, problematic because this tops out.
Underlying severity: use the data space directly (range 0-5), or use
range $+\infty$ to$-\infty$ and squash through a logistic sigmoid?
Incidence is more complicated: this is a partially observed point
process. The underlying state could either be something like a Poisson
rate (probability per unit area that there is an infected plant),
or a probability that a given plant is infected.
We get a posterior $\mu,S|x_{*},x,y$ . The covariance $S$ is used
in the pricing.
When using a temporal model, to make this stable we need to work out
which points past in time to {}``forget''.
\section*{Pricing data collection}
We want images from the places where our uncertainty is highest (about
either severity or incidence). Therefore we price according to uncertainty.
Active learning.
We are more interested in cases of disease than non-disease (how can
this be quantified?).
We are more interested in areas where there is high cassava cultivation.
If GP mean is zero, then non-zero observations will have high surprise.
Price is therefore at the minimum a function of two covariances (incidence/severity),
cassava cultivation density.
\section*{Practical issues}
How often should the pricing be updated? If someone takes a picture
of a plant, we don't want too many more pictures of that plant. We
want that person to move away. Ideally we would recalculate the pricing
there and then. But person may not have network to communicate there
and then. Would also have to communicate the updated map to everyone
using the sytem. Possibly download some global pricing map each day,
then local computations adjust the price. This doesn't stop several
people photographing the same plant though and expecting the same
price.
Creating a market might mean the survey becomes autonomous; people
buy location aware survey phones with microcredit, then make earnings
to pay off the loans.
\end{document}
|
Formal statement is: lemma binary_in_sigma_sets: "binary a b i \<in> sigma_sets sp A" if "a \<in> sigma_sets sp A" and "b \<in> sigma_sets sp A" Informal statement is: If $a$ and $b$ are in $\sigma$-algebras $A$ and $B$, then the binary operation $a \cup b$ is in the $\sigma$-algebra generated by $A$ and $B$. |
module ReverseVec
import Data.Vect
myReverse : Vect n elem -> Vect n elem
myReverse [] = []
myReverse (x :: xs) = reverseProof (myReverse xs ++ [x])
where
reverseProof : Vect (k + 1) elem -> Vect (S k) elem
reverseProof {k} res = rewrite sym (plusCommutative k 1) in res
-- Used sym for fun to get the hang of reversing direction of rewrites
|
(* Title: HOL/Auth/n_german_lemma_inv__29_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_german Protocol Case Study*}
theory n_german_lemma_inv__29_on_rules imports n_german_lemma_on_inv__29
begin
section{*All lemmas on causal relation between inv__29*}
lemma lemma_inv__29_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__29 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> j. j\<le>N\<and>r=n_SendReqS j)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqEI i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqES i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReq N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvE i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)\<or>
(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> j. j\<le>N\<and>r=n_SendReqS j)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqSVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqEI i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqEIVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqES i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqESVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReq N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvEVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvSVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__29) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__29) done
}
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__29) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
corollary interior_bijective_linear_image: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes "linear f" "bij f" shows "interior (f ` S) = f ` interior S" (is "?lhs = ?rhs") |
/-
Copyright (c) 2020 Fox Thomson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Fox Thomson
-/
import tactic.rcases
import computability.language
/-!
# Regular Expressions
This file contains the formal definition for regular expressions and basic lemmas. Note these are
regular expressions in terms of formal language theory. Note this is different to regex's used in
computer science such as the POSIX standard.
## TODO
* Show that this regular expressions and DFA/NFA's are equivalent.
* `attribute [pattern] has_mul.mul` has been added into this file, it could be moved.
-/
open list set
open_locale computability
universe u
variables {α β γ : Type*} [dec : decidable_eq α]
/--
This is the definition of regular expressions. The names used here is to mirror the definition
of a Kleene algebra (https://en.wikipedia.org/wiki/Kleene_algebra).
* `0` (`zero`) matches nothing
* `1` (`epsilon`) matches only the empty string
* `char a` matches only the string 'a'
* `star P` matches any finite concatenation of strings which match `P`
* `P + Q` (`plus P Q`) matches anything which match `P` or `Q`
* `P * Q` (`comp P Q`) matches `x ++ y` if `x` matches `P` and `y` matches `Q`
-/
inductive regular_expression (α : Type u) : Type u
| zero : regular_expression
| epsilon : regular_expression
| char : α → regular_expression
| plus : regular_expression → regular_expression → regular_expression
| comp : regular_expression → regular_expression → regular_expression
| star : regular_expression → regular_expression
namespace regular_expression
variables {a b : α}
instance : inhabited (regular_expression α) := ⟨zero⟩
instance : has_add (regular_expression α) := ⟨plus⟩
instance : has_mul (regular_expression α) := ⟨comp⟩
instance : has_one (regular_expression α) := ⟨epsilon⟩
instance : has_zero (regular_expression α) := ⟨zero⟩
instance : has_pow (regular_expression α) ℕ := ⟨λ n r, npow_rec r n⟩
attribute [pattern] has_mul.mul
@[simp] lemma zero_def : (zero : regular_expression α) = 0 := rfl
@[simp] lemma one_def : (epsilon : regular_expression α) = 1 := rfl
@[simp] lemma plus_def (P Q : regular_expression α) : plus P Q = P + Q := rfl
@[simp] lemma comp_def (P Q : regular_expression α) : comp P Q = P * Q := rfl
/-- `matches P` provides a language which contains all strings that `P` matches -/
@[simp] def matches : regular_expression α → language α
| 0 := 0
| 1 := 1
| (char a) := {[a]}
| (P + Q) := P.matches + Q.matches
| (P * Q) := P.matches * Q.matches
| (star P) := P.matches∗
@[simp] lemma matches_zero : (0 : regular_expression α).matches = 0 := rfl
@[simp] lemma matches_epsilon : (1 : regular_expression α).matches = 1 := rfl
@[simp] lemma matches_char (a : α) : (char a).matches = {[a]} := rfl
@[simp] lemma matches_add (P Q : regular_expression α) :
(P + Q).matches = P.matches + Q.matches := rfl
@[simp] lemma matches_mul (P Q : regular_expression α) :
(P * Q).matches = P.matches * Q.matches := rfl
@[simp] lemma matches_pow (P : regular_expression α) :
∀ n : ℕ, (P ^ n).matches = P.matches ^ n
| 0 := matches_epsilon
| (n + 1) := (matches_mul _ _).trans $ eq.trans (congr_arg _ (matches_pow n)) (pow_succ _ _).symm
@[simp] lemma matches_star (P : regular_expression α) : P.star.matches = P.matches∗ := rfl
/-- `match_epsilon P` is true if and only if `P` matches the empty string -/
def match_epsilon : regular_expression α → bool
| 0 := ff
| 1 := tt
| (char _) := ff
| (P + Q) := P.match_epsilon || Q.match_epsilon
| (P * Q) := P.match_epsilon && Q.match_epsilon
| (star P) := tt
include dec
/-- `P.deriv a` matches `x` if `P` matches `a :: x`, the Brzozowski derivative of `P` with respect
to `a` -/
def deriv : regular_expression α → α → regular_expression α
| 0 _ := 0
| 1 _ := 0
| (char a₁) a₂ := if a₁ = a₂ then 1 else 0
| (P + Q) a := deriv P a + deriv Q a
| (P * Q) a :=
if P.match_epsilon then
deriv P a * Q + deriv Q a
else
deriv P a * Q
| (star P) a := deriv P a * star P
@[simp] lemma deriv_zero (a : α) : deriv 0 a = 0 := rfl
@[simp] lemma deriv_one (a : α) : deriv 1 a = 0 := rfl
@[simp] lemma deriv_char_self (a : α) : deriv (char a) a = 1 := if_pos rfl
@[simp] lemma deriv_char_of_ne (h : a ≠ b) : deriv (char a) b = 0 := if_neg h
@[simp] lemma deriv_add (P Q : regular_expression α) (a : α) :
deriv (P + Q) a = deriv P a + deriv Q a := rfl
@[simp] lemma deriv_star (P : regular_expression α) (a : α) :
deriv (P.star) a = deriv P a * star P := rfl
/-- `P.rmatch x` is true if and only if `P` matches `x`. This is a computable definition equivalent
to `matches`. -/
def rmatch : regular_expression α → list α → bool
| P [] := match_epsilon P
| P (a::as) := rmatch (P.deriv a) as
@[simp] lemma zero_rmatch (x : list α) : rmatch 0 x = ff :=
by induction x; simp [rmatch, match_epsilon, *]
lemma char_rmatch_iff (a : α) (x : list α) : rmatch (char a) x ↔ x = [a] :=
begin
cases x with _ x,
dec_trivial,
cases x,
rw [rmatch, deriv],
split_ifs;
tauto,
rw [rmatch, deriv],
split_ifs,
rw one_rmatch_iff,
tauto,
rw zero_rmatch,
tauto
end
lemma add_rmatch_iff (P Q : regular_expression α) (x : list α) :
(P + Q).rmatch x ↔ P.rmatch x ∨ Q.rmatch x :=
begin
induction x with _ _ ih generalizing P Q,
{ simp only [rmatch, match_epsilon, bor_coe_iff] },
{ repeat {rw rmatch},
rw deriv,
exact ih _ _ }
end
lemma mul_rmatch_iff (P Q : regular_expression α) (x : list α) :
(P * Q).rmatch x ↔ ∃ t u : list α, x = t ++ u ∧ P.rmatch t ∧ Q.rmatch u :=
begin
induction x with a x ih generalizing P Q,
{ rw [rmatch, match_epsilon],
split,
{ intro h,
refine ⟨ [], [], rfl, _ ⟩,
rw [rmatch, rmatch],
rwa band_coe_iff at h },
{ rintro ⟨ t, u, h₁, h₂ ⟩,
cases list.append_eq_nil.1 h₁.symm with ht hu,
subst ht,
subst hu,
repeat {rw rmatch at h₂},
simp [h₂] } },
{ rw [rmatch, deriv],
split_ifs with hepsilon,
{ rw [add_rmatch_iff, ih],
split,
{ rintro (⟨ t, u, _ ⟩ | h),
{ exact ⟨ a :: t, u, by tauto ⟩ },
{ exact ⟨ [], a :: x, rfl, hepsilon, h ⟩ } },
{ rintro ⟨ t, u, h, hP, hQ ⟩,
cases t with b t,
{ right,
rw list.nil_append at h,
rw ←h at hQ,
exact hQ },
{ left,
simp only [list.cons_append] at h,
refine ⟨ t, u, h.2, _, hQ ⟩,
rw rmatch at hP,
convert hP,
exact h.1 } } },
{ rw ih,
split;
rintro ⟨ t, u, h, hP, hQ ⟩,
{ exact ⟨ a :: t, u, by tauto ⟩ },
{ cases t with b t,
{ contradiction },
{ simp only [list.cons_append] at h,
refine ⟨ t, u, h.2, _, hQ ⟩,
rw rmatch at hP,
convert hP,
exact h.1 } } } }
end
lemma star_rmatch_iff (P : regular_expression α) : ∀ (x : list α),
(star P).rmatch x ↔ ∃ S : list (list α), x = S.join ∧ ∀ t ∈ S, t ≠ [] ∧ P.rmatch t
| x :=
begin
have A : ∀ (m n : ℕ), n < m + n + 1,
{ assume m n,
convert add_lt_add_of_le_of_lt (add_le_add (zero_le m) (le_refl n)) zero_lt_one,
simp },
have IH := λ t (h : list.length t < list.length x), star_rmatch_iff t,
clear star_rmatch_iff,
split,
{ cases x with a x,
{ intro,
fconstructor,
exact [],
tauto },
{ rw [rmatch, deriv, mul_rmatch_iff],
rintro ⟨ t, u, hs, ht, hu ⟩,
have hwf : u.length < (list.cons a x).length,
{ rw [hs, list.length_cons, list.length_append],
apply A },
rw IH _ hwf at hu,
rcases hu with ⟨ S', hsum, helem ⟩,
use (a :: t) :: S',
split,
{ simp [hs, hsum] },
{ intros t' ht',
cases ht' with ht' ht',
{ rw ht',
exact ⟨ dec_trivial, ht ⟩ },
{ exact helem _ ht' } } } },
{ rintro ⟨ S, hsum, helem ⟩,
cases x with a x,
{ dec_trivial },
{ rw [rmatch, deriv, mul_rmatch_iff],
cases S with t' U,
{ exact ⟨ [], [], by tauto ⟩ },
{ cases t' with b t,
{ simp only [forall_eq_or_imp, list.mem_cons_iff] at helem,
simp only [eq_self_iff_true, not_true, ne.def, false_and] at helem,
cases helem },
simp only [list.join, list.cons_append] at hsum,
refine ⟨ t, U.join, hsum.2, _, _ ⟩,
{ specialize helem (b :: t) (by simp),
rw rmatch at helem,
convert helem.2,
exact hsum.1 },
{ have hwf : U.join.length < (list.cons a x).length,
{ rw [hsum.1, hsum.2],
simp only [list.length_append, list.length_join, list.length],
apply A },
rw IH _ hwf,
refine ⟨ U, rfl, λ t h, helem t _ ⟩,
right,
assumption } } } }
end
using_well_founded
{ rel_tac := λ _ _, `[exact ⟨(λ L₁ L₂ : list _, L₁.length < L₂.length), inv_image.wf _ nat.lt_wf⟩] }
@[simp] lemma rmatch_iff_matches (P : regular_expression α) :
∀ x : list α, P.rmatch x ↔ x ∈ P.matches :=
begin
intro x,
induction P generalizing x,
all_goals
{ try {rw zero_def},
try {rw one_def},
try {rw plus_def},
try {rw comp_def},
rw matches },
case zero :
{ rw zero_rmatch,
tauto },
case epsilon :
{ rw one_rmatch_iff,
refl },
case char :
{ rw char_rmatch_iff,
refl },
case plus : _ _ ih₁ ih₂
{ rw [add_rmatch_iff, ih₁, ih₂],
refl },
case comp : P Q ih₁ ih₂
{ simp only [mul_rmatch_iff, comp_def, language.mul_def, exists_and_distrib_left, set.mem_image2,
set.image_prod],
split,
{ rintro ⟨ x, y, hsum, hmatch₁, hmatch₂ ⟩,
rw ih₁ at hmatch₁,
rw ih₂ at hmatch₂,
exact ⟨ x, hmatch₁, y, hmatch₂, hsum.symm ⟩ },
{ rintro ⟨ x, hmatch₁, y, hmatch₂, hsum ⟩,
rw ←ih₁ at hmatch₁,
rw ←ih₂ at hmatch₂,
exact ⟨ x, y, hsum.symm, hmatch₁, hmatch₂ ⟩ } },
case star : _ ih
{ rw [star_rmatch_iff, language.kstar_def_nonempty],
split,
all_goals
{ rintro ⟨ S, hx, hS ⟩,
refine ⟨ S, hx, _ ⟩,
intro y,
specialize hS y },
{ rw ←ih y,
tauto },
{ rw ih y,
tauto } }
end
instance (P : regular_expression α) : decidable_pred P.matches :=
begin
intro x,
change decidable (x ∈ P.matches),
rw ←rmatch_iff_matches,
exact eq.decidable _ _
end
omit dec
/-- Map the alphabet of a regular expression. -/
@[simp] def map (f : α → β) : regular_expression α → regular_expression β
| 0 := 0
| 1 := 1
| (char a) := char (f a)
| (R + S) := map R + map S
| (R * S) := map R * map S
| (star R) := star (map R)
@[simp] protected lemma map_pow (f : α → β) (P : regular_expression α) :
∀ n : ℕ, map f (P ^ n) = map f P ^ n
| 0 := rfl
| (n + 1) := (congr_arg ((*) (map f P)) (map_pow n) : _)
@[simp] lemma map_id : ∀ (P : regular_expression α), P.map id = P
| 0 := rfl
| 1 := rfl
| (char a) := rfl
| (R + S) := by simp_rw [map, map_id]
| (R * S) := by simp_rw [map, map_id]
| (star R) := by simp_rw [map, map_id]
@[simp] lemma map_map (g : β → γ) (f : α → β) :
∀ (P : regular_expression α), (P.map f).map g = P.map (g ∘ f)
| 0 := rfl
| 1 := rfl
| (char a) := rfl
| (R + S) := by simp_rw [map, map_map]
| (R * S) := by simp_rw [map, map_map]
| (star R) := by simp_rw [map, map_map]
/-- The language of the map is the map of the language. -/
@[simp] lemma matches_map (f : α → β) :
∀ P : regular_expression α, (P.map f).matches = language.map f P.matches
| 0 := (map_zero _).symm
| 1 := (map_one _).symm
| (char a) := by { rw eq_comm, exact image_singleton }
| (R + S) := by simp only [matches_map, map, matches_add, map_add]
| (R * S) := by simp only [matches_map, map, matches_mul, map_mul]
| (star R) := begin
simp_rw [map, matches, matches_map],
rw [language.kstar_eq_supr_pow, language.kstar_eq_supr_pow],
simp_rw ←map_pow,
exact image_Union.symm,
end
end regular_expression
|
[STATEMENT]
lemma less_multiset_less_multiset\<^sub>H\<^sub>O: "M < N \<longleftrightarrow> less_multiset\<^sub>H\<^sub>O M N"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (M < N) = less_multiset\<^sub>H\<^sub>O M N
[PROOF STEP]
unfolding less_multiset_def multp_def mult\<^sub>H\<^sub>O less_multiset\<^sub>H\<^sub>O_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (M \<noteq> N \<and> (\<forall>y. count N y < count M y \<longrightarrow> (\<exists>x>y. count M x < count N x))) = (M \<noteq> N \<and> (\<forall>y. count N y < count M y \<longrightarrow> (\<exists>x>y. count M x < count N x)))
[PROOF STEP]
.. |
Formal statement is: lemma complete_isometric_image: assumes "0 < e" and s: "subspace s" and f: "bounded_linear f" and normf: "\<forall>x\<in>s. norm(f x) \<ge> e * norm(x)" and cs: "complete s" shows "complete (f ` s)" Informal statement is: If $f$ is a bounded linear map from a complete normed vector space $s$ to a normed vector space $t$ such that $\|f(x)\| \geq e \|x\|$ for all $x \in s$, then $f(s)$ is complete. |
-- Strict A is a datatype isomorphic to A, with constructor ! : A → Strict A
-- Semantically it has no impact, but its constructor is strict, so it can be
-- used to force evaluation of a term to whnf by pattern-matching.
open import Data.Strict.Primitive using ()
module Data.Strict where
open Data.Strict.Primitive public using ( Strict ; ! )
|
[STATEMENT]
lemma qps_qp: "Q \<in> qps G \<Longrightarrow> qp Q"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Q \<in> qps G \<Longrightarrow> qp Q
[PROOF STEP]
by (auto simp: qps_def) |
[STATEMENT]
lemma dterm_pure[simp]: "pure t \<Longrightarrow> dterm t = t"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. pure t \<Longrightarrow> dterm t = t
[PROOF STEP]
by (induct pred:pure) auto |
State Before: l : Type ?u.20354
m : Type u_1
n : Type u_3
o : Type ?u.20363
l' : Type ?u.20366
m' : Type u_2
n' : Type u_4
o' : Type ?u.20375
m'' : Type u_5
n'' : Type u_6
R : Type u_8
A : Type u_7
inst✝² : Semiring R
inst✝¹ : AddCommMonoid A
inst✝ : Module R A
e₁ : m ≃ m'
e₂ : n ≃ n'
e₁' : m' ≃ m''
e₂' : n' ≃ n''
⊢ LinearEquiv.trans (reindexLinearEquiv R A e₁ e₂) (reindexLinearEquiv R A e₁' e₂') =
reindexLinearEquiv R A (e₁.trans e₁') (e₂.trans e₂') State After: case h.a.h
l : Type ?u.20354
m : Type u_1
n : Type u_3
o : Type ?u.20363
l' : Type ?u.20366
m' : Type u_2
n' : Type u_4
o' : Type ?u.20375
m'' : Type u_5
n'' : Type u_6
R : Type u_8
A : Type u_7
inst✝² : Semiring R
inst✝¹ : AddCommMonoid A
inst✝ : Module R A
e₁ : m ≃ m'
e₂ : n ≃ n'
e₁' : m' ≃ m''
e₂' : n' ≃ n''
x✝¹ : Matrix m n A
i✝ : m''
x✝ : n''
⊢ ↑(LinearEquiv.trans (reindexLinearEquiv R A e₁ e₂) (reindexLinearEquiv R A e₁' e₂')) x✝¹ i✝ x✝ =
↑(reindexLinearEquiv R A (e₁.trans e₁') (e₂.trans e₂')) x✝¹ i✝ x✝ Tactic: ext State Before: case h.a.h
l : Type ?u.20354
m : Type u_1
n : Type u_3
o : Type ?u.20363
l' : Type ?u.20366
m' : Type u_2
n' : Type u_4
o' : Type ?u.20375
m'' : Type u_5
n'' : Type u_6
R : Type u_8
A : Type u_7
inst✝² : Semiring R
inst✝¹ : AddCommMonoid A
inst✝ : Module R A
e₁ : m ≃ m'
e₂ : n ≃ n'
e₁' : m' ≃ m''
e₂' : n' ≃ n''
x✝¹ : Matrix m n A
i✝ : m''
x✝ : n''
⊢ ↑(LinearEquiv.trans (reindexLinearEquiv R A e₁ e₂) (reindexLinearEquiv R A e₁' e₂')) x✝¹ i✝ x✝ =
↑(reindexLinearEquiv R A (e₁.trans e₁') (e₂.trans e₂')) x✝¹ i✝ x✝ State After: no goals Tactic: rfl |
(* Title: ZF/Induct/Comb.thy
Author: Lawrence C Paulson
Copyright 1994 University of Cambridge
*)
section \<open>Combinatory Logic example: the Church-Rosser Theorem\<close>
theory Comb
imports ZF
begin
text \<open>
Curiously, combinators do not include free variables.
Example taken from @{cite camilleri92}.
\<close>
subsection \<open>Definitions\<close>
text \<open>Datatype definition of combinators \<open>S\<close> and \<open>K\<close>.\<close>
consts comb :: i
datatype comb =
K
| S
| app ("p \<in> comb", "q \<in> comb") (infixl \<open>\<bullet>\<close> 90)
text \<open>
Inductive definition of contractions, \<open>\<rightarrow>\<^sup>1\<close> and
(multi-step) reductions, \<open>\<rightarrow>\<close>.
\<close>
consts contract :: i
abbreviation contract_syntax :: "[i,i] \<Rightarrow> o" (infixl \<open>\<rightarrow>\<^sup>1\<close> 50)
where "p \<rightarrow>\<^sup>1 q \<equiv> \<langle>p,q\<rangle> \<in> contract"
abbreviation contract_multi :: "[i,i] \<Rightarrow> o" (infixl \<open>\<rightarrow>\<close> 50)
where "p \<rightarrow> q \<equiv> \<langle>p,q\<rangle> \<in> contract^*"
inductive
domains "contract" \<subseteq> "comb \<times> comb"
intros
K: "\<lbrakk>p \<in> comb; q \<in> comb\<rbrakk> \<Longrightarrow> K\<bullet>p\<bullet>q \<rightarrow>\<^sup>1 p"
S: "\<lbrakk>p \<in> comb; q \<in> comb; r \<in> comb\<rbrakk> \<Longrightarrow> S\<bullet>p\<bullet>q\<bullet>r \<rightarrow>\<^sup>1 (p\<bullet>r)\<bullet>(q\<bullet>r)"
Ap1: "\<lbrakk>p\<rightarrow>\<^sup>1q; r \<in> comb\<rbrakk> \<Longrightarrow> p\<bullet>r \<rightarrow>\<^sup>1 q\<bullet>r"
Ap2: "\<lbrakk>p\<rightarrow>\<^sup>1q; r \<in> comb\<rbrakk> \<Longrightarrow> r\<bullet>p \<rightarrow>\<^sup>1 r\<bullet>q"
type_intros comb.intros
text \<open>
Inductive definition of parallel contractions, \<open>\<Rrightarrow>\<^sup>1\<close> and
(multi-step) parallel reductions, \<open>\<Rrightarrow>\<close>.
\<close>
consts parcontract :: i
abbreviation parcontract_syntax :: "[i,i] \<Rightarrow> o" (infixl \<open>\<Rrightarrow>\<^sup>1\<close> 50)
where "p \<Rrightarrow>\<^sup>1 q \<equiv> \<langle>p,q\<rangle> \<in> parcontract"
abbreviation parcontract_multi :: "[i,i] \<Rightarrow> o" (infixl \<open>\<Rrightarrow>\<close> 50)
where "p \<Rrightarrow> q \<equiv> \<langle>p,q\<rangle> \<in> parcontract^+"
inductive
domains "parcontract" \<subseteq> "comb \<times> comb"
intros
refl: "\<lbrakk>p \<in> comb\<rbrakk> \<Longrightarrow> p \<Rrightarrow>\<^sup>1 p"
K: "\<lbrakk>p \<in> comb; q \<in> comb\<rbrakk> \<Longrightarrow> K\<bullet>p\<bullet>q \<Rrightarrow>\<^sup>1 p"
S: "\<lbrakk>p \<in> comb; q \<in> comb; r \<in> comb\<rbrakk> \<Longrightarrow> S\<bullet>p\<bullet>q\<bullet>r \<Rrightarrow>\<^sup>1 (p\<bullet>r)\<bullet>(q\<bullet>r)"
Ap: "\<lbrakk>p\<Rrightarrow>\<^sup>1q; r\<Rrightarrow>\<^sup>1s\<rbrakk> \<Longrightarrow> p\<bullet>r \<Rrightarrow>\<^sup>1 q\<bullet>s"
type_intros comb.intros
text \<open>
Misc definitions.
\<close>
definition I :: i
where "I \<equiv> S\<bullet>K\<bullet>K"
definition diamond :: "i \<Rightarrow> o"
where "diamond(r) \<equiv>
\<forall>x y. \<langle>x,y\<rangle>\<in>r \<longrightarrow> (\<forall>y'. <x,y'>\<in>r \<longrightarrow> (\<exists>z. \<langle>y,z\<rangle>\<in>r \<and> <y',z> \<in> r))"
subsection \<open>Transitive closure preserves the Church-Rosser property\<close>
lemma diamond_strip_lemmaD [rule_format]:
"\<lbrakk>diamond(r); \<langle>x,y\<rangle>:r^+\<rbrakk> \<Longrightarrow>
\<forall>y'. <x,y'>:r \<longrightarrow> (\<exists>z. <y',z>: r^+ \<and> \<langle>y,z\<rangle>: r)"
unfolding diamond_def
apply (erule trancl_induct)
apply (blast intro: r_into_trancl)
apply clarify
apply (drule spec [THEN mp], assumption)
apply (blast intro: r_into_trancl trans_trancl [THEN transD])
done
lemma diamond_trancl: "diamond(r) \<Longrightarrow> diamond(r^+)"
apply (simp (no_asm_simp) add: diamond_def)
apply (rule impI [THEN allI, THEN allI])
apply (erule trancl_induct)
apply auto
apply (best intro: r_into_trancl trans_trancl [THEN transD]
dest: diamond_strip_lemmaD)+
done
inductive_cases Ap_E [elim!]: "p\<bullet>q \<in> comb"
subsection \<open>Results about Contraction\<close>
text \<open>
For type checking: replaces \<^term>\<open>a \<rightarrow>\<^sup>1 b\<close> by \<open>a, b \<in>
comb\<close>.
\<close>
lemmas contract_combE2 = contract.dom_subset [THEN subsetD, THEN SigmaE2]
and contract_combD1 = contract.dom_subset [THEN subsetD, THEN SigmaD1]
and contract_combD2 = contract.dom_subset [THEN subsetD, THEN SigmaD2]
lemma field_contract_eq: "field(contract) = comb"
by (blast intro: contract.K elim!: contract_combE2)
lemmas reduction_refl =
field_contract_eq [THEN equalityD2, THEN subsetD, THEN rtrancl_refl]
lemmas rtrancl_into_rtrancl2 =
r_into_rtrancl [THEN trans_rtrancl [THEN transD]]
declare reduction_refl [intro!] contract.K [intro!] contract.S [intro!]
lemmas reduction_rls =
contract.K [THEN rtrancl_into_rtrancl2]
contract.S [THEN rtrancl_into_rtrancl2]
contract.Ap1 [THEN rtrancl_into_rtrancl2]
contract.Ap2 [THEN rtrancl_into_rtrancl2]
lemma "p \<in> comb \<Longrightarrow> I\<bullet>p \<rightarrow> p"
\<comment> \<open>Example only: not used\<close>
unfolding I_def by (blast intro: reduction_rls)
lemma comb_I: "I \<in> comb"
unfolding I_def by blast
subsection \<open>Non-contraction results\<close>
text \<open>Derive a case for each combinator constructor.\<close>
inductive_cases K_contractE [elim!]: "K \<rightarrow>\<^sup>1 r"
and S_contractE [elim!]: "S \<rightarrow>\<^sup>1 r"
and Ap_contractE [elim!]: "p\<bullet>q \<rightarrow>\<^sup>1 r"
lemma I_contract_E: "I \<rightarrow>\<^sup>1 r \<Longrightarrow> P"
by (auto simp add: I_def)
lemma K1_contractD: "K\<bullet>p \<rightarrow>\<^sup>1 r \<Longrightarrow> (\<exists>q. r = K\<bullet>q \<and> p \<rightarrow>\<^sup>1 q)"
by auto
lemma Ap_reduce1: "\<lbrakk>p \<rightarrow> q; r \<in> comb\<rbrakk> \<Longrightarrow> p\<bullet>r \<rightarrow> q\<bullet>r"
apply (frule rtrancl_type [THEN subsetD, THEN SigmaD1])
apply (drule field_contract_eq [THEN equalityD1, THEN subsetD])
apply (erule rtrancl_induct)
apply (blast intro: reduction_rls)
apply (erule trans_rtrancl [THEN transD])
apply (blast intro: contract_combD2 reduction_rls)
done
lemma Ap_reduce2: "\<lbrakk>p \<rightarrow> q; r \<in> comb\<rbrakk> \<Longrightarrow> r\<bullet>p \<rightarrow> r\<bullet>q"
apply (frule rtrancl_type [THEN subsetD, THEN SigmaD1])
apply (drule field_contract_eq [THEN equalityD1, THEN subsetD])
apply (erule rtrancl_induct)
apply (blast intro: reduction_rls)
apply (blast intro: trans_rtrancl [THEN transD]
contract_combD2 reduction_rls)
done
text \<open>Counterexample to the diamond property for \<open>\<rightarrow>\<^sup>1\<close>.\<close>
lemma KIII_contract1: "K\<bullet>I\<bullet>(I\<bullet>I) \<rightarrow>\<^sup>1 I"
by (blast intro: comb_I)
lemma KIII_contract2: "K\<bullet>I\<bullet>(I\<bullet>I) \<rightarrow>\<^sup>1 K\<bullet>I\<bullet>((K\<bullet>I)\<bullet>(K\<bullet>I))"
by (unfold I_def) (blast intro: contract.intros)
lemma KIII_contract3: "K\<bullet>I\<bullet>((K\<bullet>I)\<bullet>(K\<bullet>I)) \<rightarrow>\<^sup>1 I"
by (blast intro: comb_I)
lemma not_diamond_contract: "\<not> diamond(contract)"
unfolding diamond_def
apply (blast intro: KIII_contract1 KIII_contract2 KIII_contract3
elim!: I_contract_E)
done
subsection \<open>Results about Parallel Contraction\<close>
text \<open>For type checking: replaces \<open>a \<Rrightarrow>\<^sup>1 b\<close> by \<open>a, b
\<in> comb\<close>\<close>
lemmas parcontract_combE2 = parcontract.dom_subset [THEN subsetD, THEN SigmaE2]
and parcontract_combD1 = parcontract.dom_subset [THEN subsetD, THEN SigmaD1]
and parcontract_combD2 = parcontract.dom_subset [THEN subsetD, THEN SigmaD2]
lemma field_parcontract_eq: "field(parcontract) = comb"
by (blast intro: parcontract.K elim!: parcontract_combE2)
text \<open>Derive a case for each combinator constructor.\<close>
inductive_cases
K_parcontractE [elim!]: "K \<Rrightarrow>\<^sup>1 r"
and S_parcontractE [elim!]: "S \<Rrightarrow>\<^sup>1 r"
and Ap_parcontractE [elim!]: "p\<bullet>q \<Rrightarrow>\<^sup>1 r"
declare parcontract.intros [intro]
subsection \<open>Basic properties of parallel contraction\<close>
lemma K1_parcontractD [dest!]:
"K\<bullet>p \<Rrightarrow>\<^sup>1 r \<Longrightarrow> (\<exists>p'. r = K\<bullet>p' \<and> p \<Rrightarrow>\<^sup>1 p')"
by auto
lemma S1_parcontractD [dest!]:
"S\<bullet>p \<Rrightarrow>\<^sup>1 r \<Longrightarrow> (\<exists>p'. r = S\<bullet>p' \<and> p \<Rrightarrow>\<^sup>1 p')"
by auto
lemma S2_parcontractD [dest!]:
"S\<bullet>p\<bullet>q \<Rrightarrow>\<^sup>1 r \<Longrightarrow> (\<exists>p' q'. r = S\<bullet>p'\<bullet>q' \<and> p \<Rrightarrow>\<^sup>1 p' \<and> q \<Rrightarrow>\<^sup>1 q')"
by auto
lemma diamond_parcontract: "diamond(parcontract)"
\<comment> \<open>Church-Rosser property for parallel contraction\<close>
unfolding diamond_def
apply (rule impI [THEN allI, THEN allI])
apply (erule parcontract.induct)
apply (blast elim!: comb.free_elims intro: parcontract_combD2)+
done
text \<open>
\medskip Equivalence of \<^prop>\<open>p \<rightarrow> q\<close> and \<^prop>\<open>p \<Rrightarrow> q\<close>.
\<close>
lemma contract_imp_parcontract: "p\<rightarrow>\<^sup>1q \<Longrightarrow> p\<Rrightarrow>\<^sup>1q"
by (induct set: contract) auto
lemma reduce_imp_parreduce: "p\<rightarrow>q \<Longrightarrow> p\<Rrightarrow>q"
apply (frule rtrancl_type [THEN subsetD, THEN SigmaD1])
apply (drule field_contract_eq [THEN equalityD1, THEN subsetD])
apply (erule rtrancl_induct)
apply (blast intro: r_into_trancl)
apply (blast intro: contract_imp_parcontract r_into_trancl
trans_trancl [THEN transD])
done
lemma parcontract_imp_reduce: "p\<Rrightarrow>\<^sup>1q \<Longrightarrow> p\<rightarrow>q"
apply (induct set: parcontract)
apply (blast intro: reduction_rls)
apply (blast intro: reduction_rls)
apply (blast intro: reduction_rls)
apply (blast intro: trans_rtrancl [THEN transD]
Ap_reduce1 Ap_reduce2 parcontract_combD1 parcontract_combD2)
done
lemma parreduce_imp_reduce: "p\<Rrightarrow>q \<Longrightarrow> p\<rightarrow>q"
apply (frule trancl_type [THEN subsetD, THEN SigmaD1])
apply (drule field_parcontract_eq [THEN equalityD1, THEN subsetD])
apply (erule trancl_induct, erule parcontract_imp_reduce)
apply (erule trans_rtrancl [THEN transD])
apply (erule parcontract_imp_reduce)
done
lemma parreduce_iff_reduce: "p\<Rrightarrow>q \<longleftrightarrow> p\<rightarrow>q"
by (blast intro: parreduce_imp_reduce reduce_imp_parreduce)
end
|
/-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
Notation for operators defined at Prelude.lean
-/
prelude
import Fixtures.Termination.Init.Prelude
import Fixtures.Termination.Init.Coe
set_option linter.all false -- prevent error messages from runFrontend
namespace Lean
/--
Auxiliary type used to represent syntax categories. We mainly use auxiliary
definitions with this type to attach doc strings to syntax categories.
-/
structure Parser.Category
namespace Parser.Category
/-- `command` is the syntax category for things that appear at the top level
of a lean file. For example, `def foo := 1` is a `command`, as is
`namespace Foo` and `end Foo`. Commands generally have an effect on the state of
adding something to the environment (like a new definition), as well as
commands like `variable` which modify future commands within a scope. -/
def command : Category := {}
/-- `term` is the builtin syntax category for terms. A term denotes an expression
in lean's type theory, for example `2 + 2` is a term. The difference between
`Term` and `Expr` is that the former is a kind of syntax, while the latter is
the result of elaboration. For example `by simp` is also a `Term`, but it elaborates
to different `Expr`s depending on the context. -/
def term : Category := {}
/-- `tactic` is the builtin syntax category for tactics. These appear after
`by` in proofs, and they are programs that take in the proof context
(the hypotheses in scope plus the type of the term to synthesize) and construct
a term of the expected type. For example, `simp` is a tactic, used in:
```
example : 2 + 2 = 4 := by simp
```
-/
def tactic : Category := {}
/-- `doElem` is a builtin syntax category for elements that can appear in the `do` notation.
For example, `let x ← e` is a `doElem`, and a `do` block consists of a list of `doElem`s. -/
def doElem : Category := {}
/-- `level` is a builtin syntax category for universe levels.
This is the `u` in `Sort u`: it can contain `max` and `imax`, addition with
constants, and variables. -/
def level : Category := {}
/-- `attr` is a builtin syntax category for attributes.
Declarations can be annotated with attributes using the `@[...]` notation. -/
def attr : Category := {}
/-- `stx` is a builtin syntax category for syntax. This is the abbreviated
parser notation used inside `syntax` and `macro` declarations. -/
def stx : Category := {}
/-- `prio` is a builtin syntax category for priorities.
Priorities are used in many different attributes.
Higher numbers denote higher priority, and for example typeclass search will
try high priority instances before low priority.
In addition to literals like `37`, you can also use `low`, `mid`, `high`, as well as
add and subtract priorities. -/
def prio : Category := {}
/-- `prec` is a builtin syntax category for precedences. A precedence is a value
that expresses how tightly a piece of syntax binds: for example `1 + 2 * 3` is
parsed as `1 + (2 * 3)` because `*` has a higher pr0ecedence than `+`.
Higher numbers denote higher precedence.
In addition to literals like `37`, there are some special named priorities:
* `arg` for the precedence of function arguments
* `max` for the highest precedence used in term parsers (not actually the maximum possible value)
* `lead` for the precedence of terms not supposed to be used as arguments
and you can also add and subtract precedences. -/
def prec : Category := {}
end Parser.Category
namespace Parser.Syntax
/-! DSL for specifying parser precedences and priorities -/
/-- Addition of precedences. This is normally used only for offseting, e.g. `max + 1`. -/
syntax:65 (name := addPrec) prec " + " prec:66 : prec
/-- Subtraction of precedences. This is normally used only for offseting, e.g. `max - 1`. -/
syntax:65 (name := subPrec) prec " - " prec:66 : prec
/-- Addition of priorities. This is normally used only for offseting, e.g. `default + 1`. -/
syntax:65 (name := addPrio) prio " + " prio:66 : prio
/-- Subtraction of priorities. This is normally used only for offseting, e.g. `default - 1`. -/
syntax:65 (name := subPrio) prio " - " prio:66 : prio
end Parser.Syntax
instance : CoeOut (TSyntax ks) Syntax where
coe stx := stx.raw
instance : Coe SyntaxNodeKind SyntaxNodeKinds where
coe k := List.cons k List.nil
end Lean
/--
Maximum precedence used in term parsers, in particular for terms in
function position (`ident`, `paren`, ...)
-/
macro "max" : prec => `(prec| 1024)
/-- Precedence used for application arguments (`do`, `by`, ...). -/
macro "arg" : prec => `(prec| 1023)
/-- Precedence used for terms not supposed to be used as arguments (`let`, `have`, ...). -/
macro "lead" : prec => `(prec| 1022)
/-- Parentheses are used for grouping precedence expressions. -/
macro "(" p:prec ")" : prec => return p
/-- Minimum precedence used in term parsers. -/
macro "min" : prec => `(prec| 10)
/-- `(min+1)` (we can only write `min+1` after `Meta.lean`) -/
macro "min1" : prec => `(prec| 11)
/--
`max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`.
We use `max_prec` to workaround bootstrapping issues.
-/
macro "max_prec" : term => `(1024)
/-- The default priority `default = 1000`, which is used when no priority is set. -/
macro "default" : prio => `(prio| 1000)
/-- The standardized "low" priority `low = 100`, for things that should be lower than default priority. -/
macro "low" : prio => `(prio| 100)
/--
The standardized "medium" priority `med = 1000`. This is lower than `default`, and higher than `low`.
-/
macro "mid" : prio => `(prio| 500)
/-- The standardized "high" priority `high = 10000`, for things that should be higher than default priority. -/
macro "high" : prio => `(prio| 10000)
/-- Parentheses are used for grouping priority expressions. -/
macro "(" p:prio ")" : prio => return p
/-
Note regarding priorities. We want `low < mid < default` because we have the following default instances:
```
@[default_instance low] instance (n : Nat) : OfNat Nat n where ...
@[default_instance mid] instance : Neg Int where ...
@[default_instance default] instance [Add α] : HAdd α α α where ...
@[default_instance default] instance [Sub α] : HSub α α α where ...
...
```
Monomorphic default instances must always "win" to preserve the Lean 3 monomorphic "look&feel".
The `Neg Int` instance must have precedence over the `OfNat Nat n` one, otherwise we fail to elaborate `#check -42`
See issue #1813 for an example that failed when `mid = default`.
-/
-- Basic notation for defining parsers
-- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses
/--
`p+` is shorthand for `many1(p)`. It uses parser `p` 1 or more times, and produces a
`nullNode` containing the array of parsed results. This parser has arity 1.
If `p` has arity more than 1, it is auto-grouped in the items generated by the parser.
-/
syntax:arg stx:max "+" : stx
/--
`p*` is shorthand for `many(p)`. It uses parser `p` 0 or more times, and produces a
`nullNode` containing the array of parsed results. This parser has arity 1.
If `p` has arity more than 1, it is auto-grouped in the items generated by the parser.
-/
syntax:arg stx:max "*" : stx
/--
`(p)?` is shorthand for `optional(p)`. It uses parser `p` 0 or 1 times, and produces a
`nullNode` containing the array of parsed results. This parser has arity 1.
`p` is allowed to have arity n > 1 (in which case the node will have either 0 or n children),
but if it has arity 0 then the result will be ambiguous.
Because `?` is an identifier character, `ident?` will not work as intended.
You have to write either `ident ?` or `(ident)?` for it to parse as the `?` combinator
applied to the `ident` parser.
-/
syntax:arg stx:max "?" : stx
/--
`p1 <|> p2` is shorthand for `orelse(p1, p2)`, and parses either `p1` or `p2`.
It does not backtrack, meaning that if `p1` consumes at least one token then
`p2` will not be tried. Therefore, the parsers should all differ in their first
token. The `atomic(p)` parser combinator can be used to locally backtrack a parser.
(For full backtracking, consider using extensible syntax classes instead.)
On success, if the inner parser does not generate exactly one node, it will be
automatically wrapped in a `group` node, so the result will always be arity 1.
The `<|>` combinator does not generate a node of its own, and in particular
does not tag the inner parsers to distinguish them, which can present a problem
when reconstructing the parse. A well formed `<|>` parser should use disjoint
node kinds for `p1` and `p2`.
-/
syntax:2 stx:2 " <|> " stx:1 : stx
macro_rules
| `(stx| $p +) => `(stx| many1($p))
| `(stx| $p *) => `(stx| many($p))
| `(stx| $p ?) => `(stx| optional($p))
| `(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂))
/--
`p,*` is shorthand for `sepBy(p, ",")`. It parses 0 or more occurrences of
`p` separated by `,`, that is: `empty | p | p,p | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",*" : stx => `(stx| sepBy($x, ",", ", "))
/--
`p,+` is shorthand for `sepBy(p, ",")`. It parses 1 or more occurrences of
`p` separated by `,`, that is: `p | p,p | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",+" : stx => `(stx| sepBy1($x, ",", ", "))
/--
`p,*,?` is shorthand for `sepBy(p, ",", allowTrailingSep)`.
It parses 0 or more occurrences of `p` separated by `,`, possibly including
a trailing `,`, that is: `empty | p | p, | p,p | p,p, | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep))
/--
`p,+,?` is shorthand for `sepBy1(p, ",", allowTrailingSep)`.
It parses 1 or more occurrences of `p` separated by `,`, possibly including
a trailing `,`, that is: `p | p, | p,p | p,p, | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep))
/--
`!p` parses the negation of `p`. That is, it fails if `p` succeeds, and
otherwise parses nothing. It has arity 0.
-/
macro:arg "!" x:stx:max : stx => `(stx| notFollowedBy($x))
/--
The `nat_lit n` macro constructs "raw numeric literals". This corresponds to the
`Expr.lit (.natVal n)` constructor in the `Expr` data type.
Normally, when you write a numeral like `#check 37`, the parser turns this into
an application of `OfNat.ofNat` to the raw literal `37` to cast it into the
target type, even if this type is `Nat` (so the cast is the identity function).
But sometimes it is necessary to talk about the raw numeral directly,
especially when proving properties about the `ofNat` function itself.
-/
syntax (name := rawNatLit) "nat_lit " num : term
@[inherit_doc] infixr:90 " ∘ " => Function.comp
@[inherit_doc] infixr:35 " × " => Prod
@[inherit_doc] infixl:55 " ||| " => HOr.hOr
@[inherit_doc] infixl:58 " ^^^ " => HXor.hXor
@[inherit_doc] infixl:60 " &&& " => HAnd.hAnd
@[inherit_doc] infixl:65 " + " => HAdd.hAdd
@[inherit_doc] infixl:65 " - " => HSub.hSub
@[inherit_doc] infixl:70 " * " => HMul.hMul
@[inherit_doc] infixl:70 " / " => HDiv.hDiv
@[inherit_doc] infixl:70 " % " => HMod.hMod
@[inherit_doc] infixl:75 " <<< " => HShiftLeft.hShiftLeft
@[inherit_doc] infixl:75 " >>> " => HShiftRight.hShiftRight
@[inherit_doc] infixr:80 " ^ " => HPow.hPow
@[inherit_doc] infixl:65 " ++ " => HAppend.hAppend
@[inherit_doc] prefix:75 "-" => Neg.neg
@[inherit_doc] prefix:100 "~~~" => Complement.complement
/-!
Remark: the infix commands above ensure a delaborator is generated for each relations.
We redefine the macros below to be able to use the auxiliary `binop%` elaboration helper for binary operators.
It addresses issue #382. -/
macro_rules | `($x ||| $y) => `(binop% HOr.hOr $x $y)
macro_rules | `($x ^^^ $y) => `(binop% HXor.hXor $x $y)
macro_rules | `($x &&& $y) => `(binop% HAnd.hAnd $x $y)
macro_rules | `($x + $y) => `(binop% HAdd.hAdd $x $y)
macro_rules | `($x - $y) => `(binop% HSub.hSub $x $y)
macro_rules | `($x * $y) => `(binop% HMul.hMul $x $y)
macro_rules | `($x / $y) => `(binop% HDiv.hDiv $x $y)
macro_rules | `($x % $y) => `(binop% HMod.hMod $x $y)
macro_rules | `($x ^ $y) => `(binop% HPow.hPow $x $y)
macro_rules | `($x ++ $y) => `(binop% HAppend.hAppend $x $y)
macro_rules | `(- $x) => `(unop% Neg.neg $x)
-- declare ASCII alternatives first so that the latter Unicode unexpander wins
@[inherit_doc] infix:50 " <= " => LE.le
@[inherit_doc] infix:50 " ≤ " => LE.le
@[inherit_doc] infix:50 " < " => LT.lt
@[inherit_doc] infix:50 " >= " => GE.ge
@[inherit_doc] infix:50 " ≥ " => GE.ge
@[inherit_doc] infix:50 " > " => GT.gt
@[inherit_doc] infix:50 " = " => Eq
@[inherit_doc] infix:50 " == " => BEq.beq
/-!
Remark: the infix commands above ensure a delaborator is generated for each relations.
We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations.
It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and
`i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but
`binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/
macro_rules | `($x <= $y) => `(binrel% LE.le $x $y)
macro_rules | `($x ≤ $y) => `(binrel% LE.le $x $y)
macro_rules | `($x < $y) => `(binrel% LT.lt $x $y)
macro_rules | `($x > $y) => `(binrel% GT.gt $x $y)
macro_rules | `($x >= $y) => `(binrel% GE.ge $x $y)
macro_rules | `($x ≥ $y) => `(binrel% GE.ge $x $y)
macro_rules | `($x = $y) => `(binrel% Eq $x $y)
macro_rules | `($x == $y) => `(binrel_no_prop% BEq.beq $x $y)
@[inherit_doc] infixr:35 " /\\ " => And
@[inherit_doc] infixr:35 " ∧ " => And
@[inherit_doc] infixr:30 " \\/ " => Or
@[inherit_doc] infixr:30 " ∨ " => Or
@[inherit_doc] notation:max "¬" p:40 => Not p
@[inherit_doc] infixl:35 " && " => and
@[inherit_doc] infixl:30 " || " => or
@[inherit_doc] notation:max "!" b:40 => not b
@[inherit_doc] infix:50 " ∈ " => Membership.mem
/-- `a ∉ b` is negated elementhood. It is notation for `¬ (a ∈ b)`. -/
notation:50 a:50 " ∉ " b:50 => ¬ (a ∈ b)
@[inherit_doc] infixr:67 " :: " => List.cons
@[inherit_doc HOrElse.hOrElse] syntax:20 term:21 " <|> " term:20 : term
@[inherit_doc HAndThen.hAndThen] syntax:60 term:61 " >> " term:60 : term
@[inherit_doc] infixl:55 " >>= " => Bind.bind
@[inherit_doc] notation:60 a:60 " <*> " b:61 => Seq.seq a fun _ : Unit => b
@[inherit_doc] notation:60 a:60 " <* " b:61 => SeqLeft.seqLeft a fun _ : Unit => b
@[inherit_doc] notation:60 a:60 " *> " b:61 => SeqRight.seqRight a fun _ : Unit => b
@[inherit_doc] infixr:100 " <$> " => Functor.map
macro_rules | `($x <|> $y) => `(binop_lazy% HOrElse.hOrElse $x $y)
macro_rules | `($x >> $y) => `(binop_lazy% HAndThen.hAndThen $x $y)
namespace Lean
/--
`binderIdent` matches an `ident` or a `_`. It is used for identifiers in binding
position, where `_` means that the value should be left unnamed and inaccessible.
-/
syntax binderIdent := ident <|> hole
namespace Parser.Tactic
/--
A case tag argument has the form `tag x₁ ... xₙ`; it refers to tag `tag` and renames
the last `n` hypotheses to `x₁ ... xₙ`.
-/
syntax caseArg := binderIdent binderIdent*
end Parser.Tactic
end Lean
@[inherit_doc dite] syntax (name := termDepIfThenElse)
ppRealGroup(ppRealFill(ppIndent("if " Lean.binderIdent " : " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(if $h:ident : $c then $t else $e) => do
let mvar ← Lean.withRef c `(?m)
`(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun $h:ident => $t) (fun $h:ident => $e))
| `(if _%$h : $c then $t else $e) => do
let mvar ← Lean.withRef c `(?m)
`(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun _%$h => $t) (fun _%$h => $e))
@[inherit_doc ite] syntax (name := termIfThenElse)
ppRealGroup(ppRealFill(ppIndent("if " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(if $c then $t else $e) => do
let mvar ← Lean.withRef c `(?m)
`(let_mvar% ?m := $c; wait_if_type_mvar% ?m; ite $mvar $t $e)
/--
`if let pat := d then t else e` is a shorthand syntax for:
```
match d with
| pat => t
| _ => e
```
It matches `d` against the pattern `pat` and the bindings are available in `t`.
If the pattern does not match, it returns `e` instead.
-/
syntax (name := termIfLet)
ppRealGroup(ppRealFill(ppIndent("if " "let " term " := " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(if let $pat := $d then $t else $e) =>
`(match $d:term with | $pat => $t | _ => $e)
@[inherit_doc cond] syntax (name := boolIfThenElse)
ppRealGroup(ppRealFill(ppIndent("bif " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(bif $c then $t else $e) => `(cond $c $t $e)
/--
Haskell-like pipe operator `<|`. `f <| x` means the same as the same as `f x`,
except that it parses `x` with lower precedence, which means that `f <| g <| x`
is interpreted as `f (g x)` rather than `(f g) x`.
-/
syntax:min term " <| " term:min : term
macro_rules
| `($f $args* <| $a) => `($f $args* $a)
| `($f <| $a) => `($f $a)
/--
Haskell-like pipe operator `|>`. `x |> f` means the same as the same as `f x`,
and it chains such that `x |> f |> g` is interpreted as `g (f x)`.
-/
syntax:min term " |> " term:min1 : term
macro_rules
| `($a |> $f $args*) => `($f $args* $a)
| `($a |> $f) => `($f $a)
/--
Alternative syntax for `<|`. `f $ x` means the same as the same as `f x`,
except that it parses `x` with lower precedence, which means that `f $ g $ x`
is interpreted as `f (g x)` rather than `(f g) x`.
-/
-- Note that we have a whitespace after `$` to avoid an ambiguity with antiquotations.
syntax:min term atomic(" $" ws) term:min : term
macro_rules
| `($f $args* $ $a) => `($f $args* $a)
| `($f $ $a) => `($f $a)
@[inherit_doc Subtype] syntax "{ " withoutPosition(ident (" : " term)? " // " term) " }" : term
macro_rules
| `({ $x : $type // $p }) => ``(Subtype (fun ($x:ident : $type) => $p))
| `({ $x // $p }) => ``(Subtype (fun ($x:ident : _) => $p))
/--
`without_expected_type t` instructs Lean to elaborate `t` without an expected type.
Recall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until
expected type is known. So, `without_expected_type` is not effective in this case.
-/
macro "without_expected_type " x:term : term => `(let aux := $x; aux)
/--
The syntax `[a, b, c]` is shorthand for `a :: b :: c :: []`, or
`List.cons a (List.cons b (List.cons c List.nil))`. It allows conveniently constructing
list literals.
For lists of length at least 64, an alternative desugaring strategy is used
which uses let bindings as intermediates as in
`let left := [d, e, f]; a :: b :: c :: left` to avoid creating very deep expressions.
Note that this changes the order of evaluation, although it should not be observable
unless you use side effecting operations like `dbg_trace`.
-/
syntax "[" withoutPosition(term,*) "]" : term
/--
Auxiliary syntax for implementing `[$elem,*]` list literal syntax.
The syntax `%[a,b,c|tail]` constructs a value equivalent to `a::b::c::tail`.
It uses binary partitioning to construct a tree of intermediate let bindings as in
`let left := [d, e, f]; a :: b :: c :: left` to avoid creating very deep expressions.
-/
syntax "%[" withoutPosition(term,* "|" term) "]" : term
namespace Lean
macro_rules
| `([ $elems,* ]) => do
-- NOTE: we do not have `TSepArray.getElems` yet at this point
let rec expandListLit (i : Nat) (skip : Bool) (result : TSyntax `term) : MacroM Syntax := do
match i, skip with
| 0, _ => pure result
| i+1, true => expandListLit i false result
| i+1, false => expandListLit i true (← ``(List.cons $(⟨elems.elemsAndSeps.get! i⟩) $result))
if elems.elemsAndSeps.size < 64 then
expandListLit elems.elemsAndSeps.size false (← ``(List.nil))
else
`(%[ $elems,* | List.nil ])
-- Declare `this` as a keyword that unhygienically binds to a scope-less `this` assumption (or other binding).
-- The keyword prevents declaring a `this` binding except through metaprogramming, as is done by `have`/`show`.
/-- Special identifier introduced by "anonymous" `have : ...`, `suffices p ...` etc. -/
macro tk:"this" : term =>
return (⟨(Syntax.ident tk.getHeadInfo "this".toSubstring `this [])⟩ : TSyntax `term)
/--
Category for carrying raw syntax trees between macros; any content is printed as is by the pretty printer.
The only accepted parser for this category is an antiquotation.
-/
declare_syntax_cat rawStx
instance : Coe Syntax (TSyntax `rawStx) where
coe stx := ⟨stx⟩
/-- `with_annotate_term stx e` annotates the lexical range of `stx : Syntax` with term info for `e`. -/
scoped syntax (name := withAnnotateTerm) "with_annotate_term " rawStx ppSpace term : term
/--
The attribute `@[deprecated]` on a declaration indicates that the declaration
is discouraged for use in new code, and/or should be migrated away from in
existing code. It may be removed in a future version of the library.
`@[deprecated myBetterDef]` means that `myBetterDef` is the suggested replacement.
-/
syntax (name := deprecated) "deprecated " (ident)? : attr
/--
When `parent_dir` contains the current Lean file, `include_str "path" / "to" / "file"` becomes
a string literal with the contents of the file at `"parent_dir" / "path" / "to" / "file"`. If this
file cannot be read, elaboration fails.
-/
syntax (name := includeStr) "include_str" term : term
|
-- @@stderr --
dtrace: failed to compile script test/unittest/translators/err.D_XLATE_SOU.BadTransDecl8.d: [D_XLATE_SOU] line 31: translator output type must be a struct or union
|
[STATEMENT]
lemma terminal_tllist_of_llist:
"terminal (tllist_of_llist y xs) = (if lfinite xs then y else undefined)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. terminal (tllist_of_llist y xs) = (if lfinite xs then y else undefined)
[PROOF STEP]
by(simp add: terminal_tinfinite) |
State Before: 𝕜 : Type u_3
E : Type u_1
F : Type u_2
G : Type ?u.1266934
inst✝⁶ : NontriviallyNormedField 𝕜
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace 𝕜 E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedAddCommGroup G
inst✝ : NormedSpace 𝕜 G
p : FormalMultilinearSeries 𝕜 E F
x✝ y : E
r R : ℝ≥0
k l : ℕ
x : E
⊢ ‖↑(changeOriginSeries p k l) fun x_1 => x‖₊ ≤ ∑' (x_1 : { s // Finset.card s = l }), ‖p (k + l)‖₊ * ‖x‖₊ ^ l State After: 𝕜 : Type u_3
E : Type u_1
F : Type u_2
G : Type ?u.1266934
inst✝⁶ : NontriviallyNormedField 𝕜
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace 𝕜 E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedAddCommGroup G
inst✝ : NormedSpace 𝕜 G
p : FormalMultilinearSeries 𝕜 E F
x✝ y : E
r R : ℝ≥0
k l : ℕ
x : E
⊢ ‖↑(changeOriginSeries p k l) fun x_1 => x‖₊ ≤ (∑' (x : { s // Finset.card s = l }), ‖p (k + l)‖₊) * ∏ _i : Fin l, ‖x‖₊ Tactic: rw [NNReal.tsum_mul_right, ← Fin.prod_const] State Before: 𝕜 : Type u_3
E : Type u_1
F : Type u_2
G : Type ?u.1266934
inst✝⁶ : NontriviallyNormedField 𝕜
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace 𝕜 E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedAddCommGroup G
inst✝ : NormedSpace 𝕜 G
p : FormalMultilinearSeries 𝕜 E F
x✝ y : E
r R : ℝ≥0
k l : ℕ
x : E
⊢ ‖↑(changeOriginSeries p k l) fun x_1 => x‖₊ ≤ (∑' (x : { s // Finset.card s = l }), ‖p (k + l)‖₊) * ∏ _i : Fin l, ‖x‖₊ State After: no goals Tactic: exact (p.changeOriginSeries k l).le_of_op_nnnorm_le _ (p.nnnorm_changeOriginSeries_le_tsum _ _) |
[STATEMENT]
lemma nyinitcls_gext: "snd s\<le>|snd s' \<Longrightarrow> nyinitcls G s' \<subseteq> nyinitcls G s"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. snd s\<le>|snd s' \<Longrightarrow> nyinitcls G s' \<subseteq> nyinitcls G s
[PROOF STEP]
unfolding nyinitcls_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. snd s\<le>|snd s' \<Longrightarrow> {C. is_class G C \<and> \<not> initd C s'} \<subseteq> {C. is_class G C \<and> \<not> initd C s}
[PROOF STEP]
by (force dest!: inited_gext') |
lemma contour_integral_circlepath_eq: assumes "open s" and f_holo:"f holomorphic_on (s-{z})" and "0<e1" "e1\<le>e2" and e2_cball:"cball z e2 \<subseteq> s" shows "f contour_integrable_on circlepath z e1" "f contour_integrable_on circlepath z e2" "contour_integral (circlepath z e2) f = contour_integral (circlepath z e1) f" |
proposition homotopic_paths_reparametrize: assumes "path p" and pips: "path_image p \<subseteq> s" and contf: "continuous_on {0..1} f" and f01:"f ` {0..1} \<subseteq> {0..1}" and [simp]: "f(0) = 0" "f(1) = 1" and q: "\<And>t. t \<in> {0..1} \<Longrightarrow> q(t) = p(f t)" shows "homotopic_paths s p q" |
/-
Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta, Maxwell Thum
-/
import combinatorial_surface.abstract_simplicial_complex.basic
/-!
# Finite abstract simplicial complexes
In this file, we define finite abstract simplicial complexes, which are ASCs with
finitely many faces, or, equivalently, finitely many vertices.
## Main declarations
* `finite_abstract_simplicial_complex E`: A finite abstract simplicial complex in the type `E`.
-/
open finset set
variables (E : Type*)
/-- A finite abstract simplicial complex has finitely many faces. -/
@[ext] structure finite_abstract_simplicial_complex extends abstract_simplicial_complex E :=
(is_finite : set.finite faces)
namespace finite_abstract_simplicial_complex
open abstract_simplicial_complex
variables {E} {K : finite_abstract_simplicial_complex E} {s t : finset E} {x : E}
/-- This probably isn't all that important -/
lemma finite_asc_vertices_finite : set.finite K.vertices := by
{ have faces_finite := K.is_finite,
rw vertices_eq,
sorry }
end finite_abstract_simplicial_complex |
theory Correctness
imports "CorrectnessStacked" "Launchbury-Unstack"
begin
text {*
As a corollary of the correctness of the stacked semantics and its equivalence to the original
semantics we obtaim Theorem 2 from \cite{launchbury}.
*}
theorem correctness:
assumes "\<Gamma> : e \<Down>\<^bsub>L\<^esub> \<Delta> : z"
and [simp]:"distinctVars \<Gamma>"
shows "\<lbrakk>e\<rbrakk>\<^bsub>\<lbrace>\<Gamma>\<rbrace>\<^esub> = \<lbrakk>z\<rbrakk>\<^bsub>\<lbrace>\<Delta>\<rbrace>\<^esub>" and "\<lbrace>\<Gamma>\<rbrace> \<le> \<lbrace>\<Delta>\<rbrace>"
proof-
obtain x :: var where fresh: "atom x \<sharp> (\<Gamma>,e,\<Delta>,z)"
by (rule obtain_fresh)
have "\<Gamma> : e \<Down>\<^bsub>x#L\<^esub> \<Delta> : z"
by (rule reds_add_var_L[OF assms(1) fresh], simp)
hence "\<Gamma> : [(x, e)] \<Down> \<Delta> : [(x, z)]"
by (rule add_stack, simp_all add: supp_Nil)
moreover
from fresh
have "x \<notin> heapVars \<Gamma>"
by (metis heapVars_not_fresh fresh_Pair)
hence "distinctVars ([(x, e)] @ \<Gamma>)"
by (simp add: distinctVars_append distinctVars_Cons)
ultimately
have le: "\<lbrace>[(x, e)] @ \<Gamma>\<rbrace> \<le> \<lbrace>[(x, z)] @ \<Delta>\<rbrace>"
by (rule CorrectnessStacked.correctness)
have "\<lbrace>\<Gamma>\<rbrace> = fmap_restr (heapVars \<Gamma>) (\<lbrace>(x, e) # \<Gamma>\<rbrace>)"
apply (rule HSem_add_fresh[OF fempty_is_HSem_cond fempty_is_HSem_cond, simplified (no_asm), symmetric])
using fresh apply (simp add: fresh_Pair)
done
also have "... \<le> fmap_restr (heapVars \<Delta>) (\<lbrace>(x, z) # \<Delta>\<rbrace>)"
by (rule fmap_restr_le[OF le Launchbury.reds_doesnt_forget[OF assms(1)], simplified])
also have "... = \<lbrace>\<Delta>\<rbrace>"
apply (rule HSem_add_fresh[OF fempty_is_HSem_cond fempty_is_HSem_cond, simplified (no_asm)])
using fresh apply (simp add: fresh_Pair)
done
finally show "\<lbrace>\<Gamma>\<rbrace> \<le> \<lbrace>\<Delta>\<rbrace>".
have "\<lbrakk>e\<rbrakk>\<^bsub>\<lbrace>\<Gamma>\<rbrace>\<^esub> = \<lbrakk>e\<rbrakk>\<^bsub>\<lbrace>(x, e) # \<Gamma>\<rbrace>\<^esub>"
apply (rule ESem_add_fresh[OF fempty_is_HSem_cond fempty_is_HSem_cond, symmetric])
using fresh by (simp add: fresh_Pair)
also have "... = \<lbrace>(x, e) # \<Gamma>\<rbrace> f! x"
apply (rule the_lookup_HSem_heap[of _ "(x, e) # \<Gamma>" x, simplified (no_asm), symmetric])
apply (rule fempty_is_HSem_cond)
apply simp_all
done
also have "... = \<lbrace>(x, z) # \<Delta>\<rbrace> f! x"
apply (rule arg_cong[OF fmap_less_eqD[OF le, simplified]])
apply simp
done
also have "... = \<lbrakk>z\<rbrakk>\<^bsub>\<lbrace>(x, z) # \<Delta>\<rbrace>\<^esub>"
apply (rule the_lookup_HSem_heap[of _ "(x, z) # \<Delta>" x, OF fempty_is_HSem_cond, simplified (no_asm)])
apply simp_all
done
also have "... = \<lbrakk>z\<rbrakk>\<^bsub>\<lbrace>\<Delta>\<rbrace>\<^esub>"
apply (rule ESem_add_fresh[OF fempty_is_HSem_cond fempty_is_HSem_cond])
using fresh by (simp add: fresh_Pair)
finally show "\<lbrakk> e \<rbrakk>\<^bsub>\<lbrace>\<Gamma>\<rbrace>\<^esub> = \<lbrakk> z \<rbrakk>\<^bsub>\<lbrace>\<Delta>\<rbrace>\<^esub>".
qed
end
|
Formal statement is: lemma open_path_connected_component_set: fixes S :: "'a :: real_normed_vector set" shows "open S \<Longrightarrow> path_component_set S x = connected_component_set S x" Informal statement is: If $S$ is an open set, then the path component of $x$ in $S$ is the same as the connected component of $x$ in $S$. |
[STATEMENT]
lemma diff_Real: "cauchy X \<Longrightarrow> cauchy Y \<Longrightarrow> Real X - Real Y = Real (\<lambda>n. X n - Y n)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>cauchy X; cauchy Y\<rbrakk> \<Longrightarrow> Real X - Real Y = Real (\<lambda>n. X n - Y n)
[PROOF STEP]
by (simp add: minus_Real add_Real minus_real_def) |
theory T38
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z)))
"
nitpick[card nat=4,timeout=86400]
oops
end |
function eventLog = ma_executeDVManeuver(maneuverEvent, initialState, eventNum, celBodyData)
%ma_executeDVManeuver Summary of this function goes here
% Detailed explanation goes here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Do the maneuver according to its sub-type
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
type = maneuverEvent.maneuverType;
value = maneuverEvent.maneuverValue;
thruster = maneuverEvent.thruster;
switch type
case 'dv_inertial'
eventLog = ma_executeDVManeuver_dv_inertial(value, thruster, initialState, eventNum);
case 'dv_orbit'
eventLog = ma_executeDVManeuver_dv_orbit(value, thruster, initialState, eventNum);
case 'finite_inertial'
eventLog = ma_executeDVManeuver_finite_inertial(value, thruster, initialState, eventNum, celBodyData);
case 'finite_steered'
eventLog = ma_executeDVManeuver_finite_steered(value, thruster, initialState, eventNum, celBodyData);
case 'dv_inertial_spherical'
eventLog = ma_executeDVManeuver_dv_inertial_spherical(value, thruster, initialState, eventNum);
case 'dv_orbit_spherical'
eventLog = ma_executeDVManeuver_dv_orbit_spherical(value, thruster, initialState, eventNum);
case 'finite_inertial_spherical'
eventLog = ma_executeDVManeuver_finite_inertial_spherical(value, thruster, initialState, eventNum, celBodyData);
case 'finite_steered_spherical'
eventLog = ma_executeDVManeuver_finite_steered_spherical(value, thruster, initialState, eventNum, celBodyData);
case 'circularize'
eventLog = ma_executeDVManeuver_circularize(thruster, initialState, eventNum, celBodyData);
otherwise
error(['Did not recongize maneuver of type ', type]);
end
end
|
-- Andreas, 2017-08-25, issue #1611.
-- Fixed by Jesper Cockx as #2621.
open import Common.Prelude
data D : Bool → Set where
dt : D true
df : D false
Works : ∀{b} → D b → Set
Works dt = Bool
Works df = Bool
Fails : ∀{b : Bool} → D _ → Set
Fails dt = Bool
Fails df = Bool
-- WAS:
-- false != true of type Bool
-- when checking that the pattern df has type D true
-- SHOULD BE:
-- Don't know whether to split on dt
-- NOW:
-- I'm not sure if there should be a case for the constructor dt,
-- because I get stuck when trying to solve the following unification
-- problems (inferred index ≟ expected index):
-- true ≟ _9
-- when checking that the pattern dt has type D _9
|
lemma diameter_cball [simp]: fixes a :: "'a::euclidean_space" shows "diameter(cball a r) = (if r < 0 then 0 else 2*r)" |
!! R426 derived-type-stmt
! is TYPE [ [ , type-attr-spec-list ] :: ] type-name [ ( type-param-name-list ) ]
module DTS
10 TYPE binky
end type
type, abstract, private :: boopy(l,m)
end type boopy
end module
|
theory Properties
imports Cheri_axioms_lemmas Sail.Sail2_state_lemmas
begin
locale CHERI_ISA = Capability_ISA CC ISA
for CC :: "'cap Capability_class" and ISA :: "('cap, 'regval, 'instr, 'e) isa" +
fixes fetch_assms :: "'regval trace \<Rightarrow> bool" and instr_assms :: "'regval trace \<Rightarrow> bool"
assumes instr_cheri_axioms: "\<And>t instr. hasTrace t \<lbrakk>instr\<rbrakk> \<Longrightarrow> instr_assms t \<Longrightarrow> cheri_axioms CC ISA False (instr_raises_ex ISA instr t) (invokes_caps ISA instr t) t"
and fetch_cheri_axioms: "\<And>t. hasTrace t (instr_fetch ISA) \<Longrightarrow> fetch_assms t \<Longrightarrow> cheri_axioms CC ISA True (fetch_raises_ex ISA t) False t"
and instr_assms_appendE: "\<And>t t' instr. instr_assms (t @ t') \<Longrightarrow> Run \<lbrakk>instr\<rbrakk> t () \<Longrightarrow> instr_assms t \<and> fetch_assms t'"
and fetch_assms_appendE: "\<And>t t' instr. fetch_assms (t @ t') \<Longrightarrow> Run (instr_fetch ISA) t instr \<Longrightarrow> fetch_assms t \<and> instr_assms t'"
locale Register_Accessors =
fixes read_regval :: "register_name \<Rightarrow> 'regs \<Rightarrow> 'regval option"
and write_regval :: "register_name \<Rightarrow> 'regval \<Rightarrow> 'regs \<Rightarrow> 'regs option"
begin
abbreviation "s_emit_event e s \<equiv> emitEventS (read_regval, write_regval) e s"
abbreviation "s_run_trace t s \<equiv> runTraceS (read_regval, write_regval) t s"
abbreviation "s_allows_trace t s \<equiv> \<exists>s'. s_run_trace t s = Some s'"
end
locale CHERI_ISA_State = CHERI_ISA CC ISA + Register_Accessors read_regval write_regval
for ISA :: "('cap, 'regval, 'instr, 'e) isa"
and CC :: "'cap Capability_class"
and read_regval :: "register_name \<Rightarrow> 'regs \<Rightarrow> 'regval option"
and write_regval :: "register_name \<Rightarrow> 'regval \<Rightarrow> 'regs \<Rightarrow> 'regs option" +
(* State versions of ISA model parameters *)
fixes s_translation_tables :: "'regs sequential_state \<Rightarrow> nat set"
and s_translate_address :: "nat \<Rightarrow> acctype \<Rightarrow> 'regs sequential_state \<Rightarrow> nat option"
assumes read_absorb_write: "\<And>r v s s'. write_regval r v s = Some s' \<Longrightarrow> read_regval r s' = Some v"
and read_ignore_write: "\<And>r r' v s s'. write_regval r v s = Some s' \<Longrightarrow> r' \<noteq> r \<Longrightarrow> read_regval r' s' = read_regval r' s"
and translation_tables_sound: "\<And>t s. s_allows_trace t s \<Longrightarrow> translation_tables ISA t \<subseteq> s_translation_tables s"
and translate_address_sound: "\<And>t s vaddr paddr load.
s_allows_trace t s \<Longrightarrow>
translate_address ISA vaddr load t = Some paddr \<Longrightarrow>
s_translate_address vaddr load s = Some paddr"
and translate_address_tag_aligned_iff: "\<And>s vaddr paddr load.
s_translate_address vaddr load s = Some paddr \<Longrightarrow>
address_tag_aligned ISA paddr \<longleftrightarrow> address_tag_aligned ISA vaddr"
begin
subsection \<open>Reachable capabilities\<close>
fun get_reg_val :: "register_name \<Rightarrow> 'regs sequential_state \<Rightarrow> 'regval option" where
"get_reg_val r s = read_regval r (regstate s)"
fun put_reg_val :: "register_name \<Rightarrow> 'regval \<Rightarrow> 'regs sequential_state \<Rightarrow> 'regs sequential_state option" where
"put_reg_val r v s = map_option (\<lambda>rs'. s\<lparr>regstate := rs'\<rparr>) (write_regval r v (regstate s))"
fun get_reg_caps :: "register_name \<Rightarrow> 'regs sequential_state \<Rightarrow> 'cap set" where
"get_reg_caps r s = (case read_regval r (regstate s) of Some v \<Rightarrow> {c \<in> caps_of_regval ISA v. is_tagged_method CC c} | None \<Rightarrow> {})"
fun get_mem_cap :: "nat \<Rightarrow> nat \<Rightarrow> 'regs sequential_state \<Rightarrow> 'cap option" where
"get_mem_cap addr sz s =
Option.bind (get_mem_bytes addr sz s) (\<lambda>(bytes, tag).
Option.bind (cap_of_mem_bytes_method CC bytes tag) (\<lambda>c.
if is_tagged_method CC c then Some c else None))"
fun get_aligned_mem_cap :: "nat \<Rightarrow> nat \<Rightarrow> 'regs sequential_state \<Rightarrow> 'cap option" where
"get_aligned_mem_cap vaddr sz s =
(if address_tag_aligned ISA vaddr \<and> sz = tag_granule ISA then get_mem_cap vaddr sz s else None)"
inductive_set reachable_caps :: "'regs sequential_state \<Rightarrow> 'cap set" for s :: "'regs sequential_state" where
Reg: "\<lbrakk>c \<in> get_reg_caps r s; r \<notin> privileged_regs ISA; is_tagged_method CC c\<rbrakk> \<Longrightarrow> c \<in> reachable_caps s"
| SysReg:
"\<lbrakk>c \<in> get_reg_caps r s; r \<in> privileged_regs ISA; c' \<in> reachable_caps s;
permit_system_access (get_perms_method CC c'); \<not>is_sealed_method CC c';
is_tagged_method CC c\<rbrakk>
\<Longrightarrow> c \<in> reachable_caps s"
| Mem:
"\<lbrakk>get_aligned_mem_cap addr (tag_granule ISA) s = Some c;
s_translate_address vaddr Load s = Some addr;
c' \<in> reachable_caps s; is_tagged_method CC c'; \<not>is_sealed_method CC c';
set (address_range vaddr (tag_granule ISA)) \<subseteq> get_mem_region_method CC c';
permit_load_capability (get_perms_method CC c');
is_tagged_method CC c\<rbrakk>
\<Longrightarrow> c \<in> reachable_caps s"
| Restrict: "\<lbrakk>c \<in> reachable_caps s; leq_cap CC c' c\<rbrakk> \<Longrightarrow> c' \<in> reachable_caps s"
| Seal:
"\<lbrakk>c' \<in> reachable_caps s; c'' \<in> reachable_caps s; is_tagged_method CC c'; is_tagged_method CC c'';
\<not>is_sealed_method CC c''; \<not>is_sealed_method CC c'; permit_seal (get_perms_method CC c'')\<rbrakk> \<Longrightarrow>
seal CC c' (get_cursor_method CC c'') \<in> reachable_caps s"
| Unseal:
"\<lbrakk>c' \<in> reachable_caps s; c'' \<in> reachable_caps s; is_tagged_method CC c'; is_tagged_method CC c'';
\<not>is_sealed_method CC c''; is_sealed_method CC c'; permit_unseal (get_perms_method CC c'');
get_obj_type_method CC c' = get_cursor_method CC c''\<rbrakk> \<Longrightarrow>
unseal CC c' (get_global CC c'') \<in> reachable_caps s"
lemma derivable_subseteq_reachableI:
assumes "C \<subseteq> reachable_caps s"
shows "derivable C \<subseteq> reachable_caps s"
proof
fix c
assume "c \<in> derivable C"
then show "c \<in> reachable_caps s" using assms
by induction (auto intro: reachable_caps.intros)
qed
lemma derivable_subseteq_reachableE:
assumes "derivable C \<subseteq> reachable_caps s"
shows "C \<subseteq> reachable_caps s"
using assms by (auto intro: derivable.intros)
lemma derivable_reachable_caps_idem[simp]: "derivable (reachable_caps s) = reachable_caps s"
using derivable_subseteq_reachableI[of "reachable_caps s" s] derivable_refl
by auto
lemma runTraceS_rev_induct[consumes 1, case_names Init Step]:
assumes "s_run_trace t s = Some s'"
and Init: "P [] s"
and Step: "\<And>t e s'' s'. s_run_trace t s = Some s'' \<Longrightarrow> s_emit_event e s'' = Some s' \<Longrightarrow> P t s'' \<Longrightarrow> P (t @ [e]) s'"
shows "P t s'"
using assms
by (induction t arbitrary: s' rule: rev_induct)
(auto elim: runTraceS_appendE runTraceS_ConsE simp: bind_eq_Some_conv)
lemma get_reg_val_s_run_trace_cases:
assumes v: "get_reg_val r s' = Some v" and c: "c \<in> caps_of_regval ISA v"
and s': "s_run_trace t s = Some s'"
obtains (Init) "get_reg_val r s = Some v"
| (Update) j v' where "t ! j = E_write_reg r v'" and "c \<in> caps_of_regval ISA v'" and "j < length t"
proof (use s' v c in \<open>induction rule: runTraceS_rev_induct\<close>)
case (Step t e s'' s')
note Init = Step(4)
note Update = Step(5)
note c = \<open>c \<in> caps_of_regval ISA v\<close>
show ?case
proof cases
assume v_s'': "get_reg_val r s'' = Some v"
show ?thesis
proof (rule Step.IH[OF _ _ v_s'' c])
assume "get_reg_val r s = Some v"
then show thesis by (intro Init)
next
fix j v'
assume "t ! j = E_write_reg r v'" and "c \<in> caps_of_regval ISA v'" and "j < length t"
then show thesis by (intro Update[of j v']) (auto simp: nth_append_left)
qed
next
assume v_s'': "get_reg_val r s'' \<noteq> Some v"
note e = \<open>s_emit_event e s'' = Some s'\<close>
note v_s' = \<open>get_reg_val r s' = Some v\<close>
from e v_s' v_s'' have "e = E_write_reg r v"
proof (cases rule: emitEventS_update_cases)
case (Write_reg r' v' rs')
then show ?thesis
using v_s' v_s''
by (cases "r' = r") (auto simp: read_ignore_write read_absorb_write)
qed (auto simp: put_mem_bytes_def Let_def)
then show thesis using c by (auto intro: Update[of "length t" v])
qed
qed auto
lemma reads_reg_cap_at_idx_provenance[consumes 5]:
assumes r: "t ! i = E_read_reg r v" and c: "c \<in> caps_of_regval ISA v" and tag: "is_tagged_method CC c"
and s': "s_run_trace t s = Some s'" and i: "i < length t"
obtains (Initial) "c \<in> get_reg_caps r s"
| (Update) j where "c \<in> writes_reg_caps CC (caps_of_regval ISA) (t ! j)"
and "writes_to_reg (t ! j) = Some r" and "j < i"
proof -
from s' i obtain s1 s2
where s1: "s_run_trace (take i t) s = Some s1"
and s2: "s_emit_event (t ! i) s1 = Some s2"
by (blast elim: runTraceS_nth_split)
from s2 c r tag have "c \<in> get_reg_caps r s1"
by (auto simp: bind_eq_Some_conv split: option.splits if_splits)
with s1 Update show thesis using i
proof (induction "take i t" s1 arbitrary: i t rule: runTraceS_rev_induct)
case Init
then show ?case by (intro Initial)
next
case (Step t' e s'' s' i t)
then obtain j where j: "i = Suc j" by (cases i) auto
then have t': "t' = take j t" and e: "e = t ! j"
using Step by (auto simp: take_hd_drop[symmetric] hd_drop_conv_nth)
note IH = Step(3)[of j t]
note Update = Step(5)
note i = \<open>i < length t\<close>
show ?case
proof (use \<open>s_emit_event e s'' = Some s'\<close> in \<open>cases rule: emitEventS_update_cases\<close>)
case (Write_mem wk addr sz v tag res)
then have c: "c \<in> get_reg_caps r s''"
using Step
by (auto simp: put_mem_bytes_def bind_eq_Some_conv Let_def)
show ?thesis
by (rule IH) (use c t' i j Update in \<open>auto\<close>)
next
case (Write_reg r' v rs')
show ?thesis
proof cases
assume "r' = r"
then show ?thesis
using Write_reg e j \<open>c \<in> get_reg_caps r s'\<close>
by (intro Update[of j]) (auto simp: read_absorb_write)
next
assume "r' \<noteq> r"
show ?thesis
by (rule IH)
(use \<open>r' \<noteq> r\<close> Write_reg e t' i j \<open>c \<in> get_reg_caps r s'\<close> Update in
\<open>auto simp: read_ignore_write\<close>)
qed
next
case Read
show ?thesis
by (rule IH) (use Read Step.prems t' i j Update in \<open>auto\<close>)
qed
qed
qed
lemma reads_reg_cap_at_idx_from_initial:
assumes r: "t ! i = E_read_reg r v" and c: "c \<in> caps_of_regval ISA v" and tag: "is_tagged_method CC c"
and s': "s_run_trace t s = Some s'" and i: "i < length t"
and "\<not> cap_reg_written_before_idx CC ISA i r t"
shows "c \<in> get_reg_caps r s"
using assms
by (elim reads_reg_cap_at_idx_provenance)
(auto simp: cap_reg_written_before_idx_def writes_reg_caps_at_idx_def)
subsection \<open>Capability monotonicity\<close>
lemma available_caps_mono:
assumes j: "j < i"
shows "available_caps CC ISA j t \<subseteq> available_caps CC ISA i t"
proof -
have "available_caps CC ISA j t \<subseteq> available_caps CC ISA (Suc (j + k)) t" for k
by (induction k) (auto simp: available_caps_Suc image_iff subset_iff)
then show ?thesis using assms less_iff_Suc_add[of j i] by blast
qed
lemma reads_reg_cap_non_privileged_accessible[intro]:
assumes "c \<in> caps_of_regval ISA v" and "t ! j = E_read_reg r v"
and "\<not>cap_reg_written_before_idx CC ISA j r t"
and "r \<notin> privileged_regs ISA"
and "is_tagged_method CC c"
and "j < i"
and "j < length t"
shows "c \<in> available_caps CC ISA i t"
proof -
from assms have c: "c \<in> available_caps CC ISA (Suc j) t"
by (auto simp: bind_eq_Some_conv image_iff available_caps.simps)
consider "i = Suc j" | "Suc j < i" using \<open>j < i\<close>
by (cases "i = Suc j") auto
then show "c \<in> available_caps CC ISA i t"
using c available_caps_mono[of "Suc j" i t]
by cases auto
qed
lemma system_access_permitted_at_idx_available_caps:
assumes "system_access_permitted_before_idx CC ISA i t"
obtains c where "c \<in> available_caps CC ISA i t" and "is_tagged_method CC c"
and "\<not>is_sealed_method CC c" and "permit_system_access (get_perms_method CC c)"
using assms
by (auto simp: system_access_permitted_before_idx_def; blast)
lemma writes_reg_cap_nth_provenance[consumes 4]:
assumes "t ! i = E_write_reg r v" and "c \<in> caps_of_regval ISA v"
and "cheri_axioms CC ISA is_fetch has_ex inv_caps t"
and "i < length t"
and tagged: "is_tagged_method CC c"
obtains (Accessible) "c \<in> derivable (available_caps CC ISA i t)"
| (Exception) v' r' j where "c \<in> exception_targets ISA {v. \<exists>r j. j < i \<and> j < length t \<and> t ! j = E_read_reg r v \<and> r \<in> KCC ISA}" (* "leq_cap CC c c'"*)
(*and "t ! j = E_read_reg r' v'" and "j < i"*) (*and "c' \<in> caps_of_regval ISA v'"*)
(*and "r' \<in> KCC ISA"*) and "r \<in> PCC ISA" and "has_ex"
| (CCall) cc cd c' where "inv_caps" (*"(cc, cd) \<in> inv_caps"*) and "invokable CC cc cd"
and "cc \<in> derivable (available_caps CC ISA i t)"
and "cd \<in> derivable (available_caps CC ISA i t)"
and "(r \<in> PCC ISA \<and> leq_cap CC c (unseal CC cc True)) \<or>
(r \<in> IDC ISA \<and> leq_cap CC c (unseal CC cd True))"
using assms
unfolding cheri_axioms_def store_cap_reg_axiom_def writes_reg_caps_at_idx_def cap_derivable_iff_derivable
by (elim impE conjE allE[where x = i] allE[where x = c])
(auto simp: eq_commute[where b = "t ! j" for t j])
lemma get_mem_cap_run_trace_cases:
assumes c: "get_mem_cap addr (tag_granule ISA) s' = Some c"
and s': "s_run_trace t s = Some s'"
and tagged: "is_tagged_method CC c"
and aligned: "address_tag_aligned ISA addr"
and axiom: "store_tag_axiom CC ISA t"
obtains (Initial) "get_mem_cap addr (tag_granule ISA) s = Some c"
| (Update) k wk bytes r where "k < length t"
and "t ! k = E_write_memt wk addr (tag_granule ISA) bytes B1 r"
and "cap_of_mem_bytes_method CC bytes B1 = Some c"
proof (use s' c axiom in \<open>induction rule: runTraceS_rev_induct\<close>)
case (Step t e s'' s')
note Update = Step.prems(2)
have axiom: "store_tag_axiom CC ISA t"
using \<open>store_tag_axiom CC ISA (t @ [e])\<close>
by (auto simp: store_tag_axiom_def writes_mem_val_at_idx_def nth_append bind_eq_Some_conv split: if_splits; metis less_SucI)
have IH: "thesis" if "get_mem_cap addr (tag_granule ISA) s'' = Some c"
proof (rule Step.IH[OF _ _ that axiom])
assume "get_mem_cap addr (tag_granule ISA) s = Some c"
then show thesis by (rule Initial)
next
fix k wk bytes r
assume "k < length t" and "t ! k = E_write_memt wk addr (tag_granule ISA) bytes B1 r"
and "cap_of_mem_bytes_method CC bytes B1 = Some c"
then show thesis
by (intro Update[of k wk bytes r]) (auto simp: nth_append)
qed
obtain v tag
where v: "get_mem_bytes addr (tag_granule ISA) s' = Some (v, tag)"
and cv: "cap_of_mem_bytes_method CC v tag = Some c"
using \<open>get_mem_cap addr (tag_granule ISA) s' = Some c\<close>
by (auto simp: bind_eq_Some_conv bool_of_bitU_def split: if_splits)
then have tag: "tag = B1" using tagged by auto
from \<open>s_emit_event e s'' = Some s'\<close> show thesis
proof (cases rule: emitEventS_update_cases)
case (Write_mem wk addr' sz' v' tag' r)
have sz': "tag' = B1 \<longrightarrow> (address_tag_aligned ISA addr' \<and> sz' = tag_granule ISA)"
and len_v': "length v' = sz'"
using \<open>store_tag_axiom CC ISA (t @ [e])\<close> Write_mem
by (auto simp: store_tag_axiom_def writes_mem_val_at_idx_def bind_eq_Some_conv nth_append split: if_splits)
show ?thesis
proof cases
assume addr_disj: "{addr..<tag_granule ISA + addr} \<inter> {addr'..<sz' + addr'} = {}"
then have "get_mem_bytes addr (tag_granule ISA) s'' = get_mem_bytes addr (tag_granule ISA) s'"
using Write_mem len_v'
by (intro get_mem_bytes_cong) (auto simp: memstate_put_mem_bytes tagstate_put_mem_bytes)
then show thesis
using v cv tag
by (intro IH) auto
next
assume addr_overlap: "{addr..<tag_granule ISA + addr} \<inter> {addr'..<sz' + addr'} \<noteq> {}"
then have tag': "tag' = B1"
proof -
obtain addr''
where addr_orig: "addr'' \<in> {addr..<tag_granule ISA + addr}"
and addr_prime: "addr'' \<in> {addr'..<sz' + addr'}"
using addr_overlap
by blast
have "tagstate s' addr'' = Some B1"
using addr_orig get_mem_bytes_tagged_tagstate[OF v[unfolded tag]]
by auto
then show "tag' = B1"
using addr_prime Write_mem len_v'
by (auto simp: tagstate_put_mem_bytes)
qed
with addr_overlap aligned sz' have addr': "addr' = addr"
by (auto simp: address_tag_aligned_def dvd_def mult_Suc_right[symmetric]
simp del: mult_Suc_right)
then have v': "v' = v"
using v tag tag' sz' len_v' Write_mem
by (auto simp: get_mem_bytes_put_mem_bytes_same_addr)
then show thesis
using Write_mem cv tag' addr' sz' tag
by (intro Step.prems(2)[of "length t"]) (auto simp: writes_mem_cap_def)
qed
next
case (Write_reg r v rs')
with \<open>get_mem_cap addr (tag_granule ISA) s' = Some c\<close> show thesis
by (auto intro: IH simp: get_mem_bytes_def)
next
case Read
with \<open>get_mem_cap addr (tag_granule ISA) s' = Some c\<close> show thesis
by (auto intro: IH)
qed
qed auto
lemma reads_mem_cap_at_idx_provenance:
assumes read: "t ! i = E_read_memt rk addr (tag_granule ISA) (bytes, B1)"
and c: "cap_of_mem_bytes_method CC bytes B1 = Some c"
and s': "s_run_trace t s = Some s'"
and axioms: "cheri_axioms CC ISA is_fetch has_ex inv_caps t"
and i: "i < length t"
and tagged: "is_tagged_method CC c"
and aligned: "address_tag_aligned ISA addr"
obtains (Initial) "get_mem_cap addr (tag_granule ISA) s = Some c"
| (Update) k wk bytes' r where "k < i"
and "t ! k = E_write_memt wk addr (tag_granule ISA) bytes' B1 r"
and "cap_of_mem_bytes_method CC bytes' B1 = Some c"
proof -
obtain s''
where s'': "s_run_trace (take i t) s = Some s''"
and c': "get_mem_cap addr (tag_granule ISA) s'' = Some c"
using s' i read c tagged
by (cases rule: runTraceS_nth_split; cases "t ! i")
(auto simp: bind_eq_Some_conv reads_mem_cap_def split: if_splits)
have "store_tag_axiom CC ISA (take i t)"
using axioms
by (fastforce simp: cheri_axioms_def store_tag_axiom_def writes_mem_val_at_idx_def bind_eq_Some_conv)
with c' s'' tagged aligned show thesis
by (cases rule: get_mem_cap_run_trace_cases) (auto intro: that)
qed
fun s_invariant :: "('regs sequential_state \<Rightarrow> 'a) \<Rightarrow> 'regval trace \<Rightarrow> 'regs sequential_state \<Rightarrow> bool" where
"s_invariant f [] s = True"
| "s_invariant f (e # t) s = (case s_emit_event e s of Some s' \<Rightarrow> f s' = f s \<and> s_invariant f t s' | None \<Rightarrow> False)"
abbreviation s_invariant_holds :: "('regs sequential_state \<Rightarrow> bool) \<Rightarrow> 'regval trace \<Rightarrow> 'regs sequential_state \<Rightarrow> bool" where
"s_invariant_holds P t s \<equiv> P s \<and> s_invariant P t s"
lemma s_invariant_append:
"s_invariant f (\<beta> @ \<alpha>) s \<longleftrightarrow>
(\<exists>s'. s_invariant f \<beta> s \<and> s_run_trace \<beta> s = Some s' \<and> s_invariant f \<alpha> s')"
by (induction \<beta> arbitrary: s) (auto split: option.splits simp: runTraceS_Cons_tl)
lemma s_invariant_takeI:
assumes "s_invariant f t s"
shows "s_invariant f (take n t) s"
proof -
from assms have "s_invariant f (take n t @ drop n t) s" by auto
then show ?thesis unfolding s_invariant_append by auto
qed
lemma s_invariant_run_trace_eq:
assumes "s_invariant f t s" and "s_run_trace t s = Some s'"
shows "f s' = f s"
using assms
by (induction f t s rule: s_invariant.induct)
(auto split: option.splits elim: runTraceS_ConsE)
definition no_caps_in_translation_tables :: "'regs sequential_state \<Rightarrow> bool" where
"no_caps_in_translation_tables s \<equiv>
\<forall>addr sz c. get_mem_cap addr sz s = Some c \<and> is_tagged_method CC c \<longrightarrow>
addr \<notin> s_translation_tables s"
lemma derivable_available_caps_subseteq_reachable_caps:
assumes axioms: "cheri_axioms CC ISA is_fetch has_ex inv_caps t"
and t: "s_run_trace t s = Some s'"
and translation_table_addrs_invariant: "s_invariant s_translation_tables t s"
and no_caps_in_translation_tables: "s_invariant_holds no_caps_in_translation_tables t s"
shows "derivable (available_caps CC ISA i t) \<subseteq> reachable_caps s"
proof (induction i rule: less_induct)
case (less i)
show ?case proof
fix c
assume "c \<in> derivable (available_caps CC ISA i t)"
then show "c \<in> reachable_caps s"
proof induction
fix c
assume "c \<in> available_caps CC ISA i t"
then show "c \<in> reachable_caps s"
proof (cases rule: available_caps_cases)
case (Reg r v j)
with t have initial: "c \<in> get_reg_caps r s"
by (blast intro: reads_reg_cap_at_idx_from_initial)
show ?thesis
proof cases
assume r: "r \<in> privileged_regs ISA"
then obtain c' where c': "c' \<in> reachable_caps s" and "is_tagged_method CC c'"
and "\<not>is_sealed_method CC c'" and p: "permit_system_access (get_perms_method CC c')"
using Reg less.IH[OF \<open>j < i\<close>] derivable_refl[of "available_caps CC ISA j t"]
by (auto elim!: system_access_permitted_at_idx_available_caps)
then show ?thesis
using Reg
by (auto intro: reachable_caps.SysReg[OF initial r c'])
next
assume "r \<notin> privileged_regs ISA"
then show ?thesis using initial Reg by (auto intro: reachable_caps.Reg)
qed
next
case (Mem wk paddr bytes j sz)
note read = \<open>t ! j = E_read_memt wk paddr sz (bytes, B1)\<close>
note bytes = \<open>cap_of_mem_bytes_method CC bytes B1 = Some c\<close>
have addr: "paddr \<notin> translation_tables ISA (take j t)"
proof
assume paddr_j: "paddr \<in> translation_tables ISA (take j t)"
then have "paddr \<in> s_translation_tables s"
using translation_tables_sound[of "take j t" s] t \<open>j < length t\<close>
by (auto elim: runTraceS_nth_split)
moreover have "paddr \<notin> s_translation_tables s"
proof -
obtain s''
where s'': "s_run_trace (take j t) s = Some s''"
and c_s'': "get_mem_cap paddr sz s'' = Some c"
using t \<open>j < length t\<close> read bytes \<open>is_tagged_method CC c\<close>
by (cases rule: runTraceS_nth_split; cases "t ! j")
(auto simp: bind_eq_Some_conv reads_mem_cap_def split: if_splits)
moreover have "no_caps_in_translation_tables s''"
using no_caps_in_translation_tables s''
using s_invariant_takeI[of no_caps_in_translation_tables t s j]
using s_invariant_run_trace_eq[of no_caps_in_translation_tables "take j t" s s'']
by auto
moreover have "s_translation_tables s'' = s_translation_tables s"
using translation_table_addrs_invariant s''
by (intro s_invariant_run_trace_eq) (auto intro: s_invariant_takeI)
ultimately show ?thesis
using \<open>is_tagged_method CC c\<close>
by (fastforce simp: no_caps_in_translation_tables_def bind_eq_Some_conv)
qed
ultimately show False by blast
qed
then obtain vaddr c'
where vaddr: "translate_address ISA vaddr Load (take j t) = Some paddr"
and c': "c' \<in> derivable (available_caps CC ISA j t)"
"is_tagged_method CC c'" "\<not>is_sealed_method CC c'"
"set (address_range vaddr sz) \<subseteq> get_mem_region_method CC c'"
"permit_load (get_perms_method CC c')"
"permit_load_capability (get_perms_method CC c')"
and sz: "sz = tag_granule ISA"
and aligned: "address_tag_aligned ISA paddr"
using read t axioms \<open>j < length t\<close> \<open>is_tagged_method CC c\<close>
unfolding cheri_axioms_def load_mem_axiom_def reads_mem_cap_def
by (fastforce simp: reads_mem_val_at_idx_def bind_eq_Some_conv cap_derivable_iff_derivable split: if_splits)
have s_vaddr: "s_translate_address vaddr Load s = Some paddr"
using vaddr t \<open>j < length t\<close>
by (blast intro: translate_address_sound[of "take j t"] elim: runTraceS_nth_split)
from read[unfolded sz] bytes t axioms \<open>j < length t\<close> \<open>is_tagged_method CC c\<close> aligned
show ?thesis
proof (cases rule: reads_mem_cap_at_idx_provenance)
case Initial
then show ?thesis
using Mem s_vaddr less.IH[of j] c' aligned sz
by (intro reachable_caps.Mem[of paddr s c vaddr c'])
(auto simp: bind_eq_Some_conv translate_address_tag_aligned_iff permits_cap_load_def)
next
case (Update k wk bytes' r)
then show ?thesis
using axioms \<open>is_tagged_method CC c\<close> \<open>j < length t\<close> \<open>j < i\<close> less.IH[of k]
unfolding cheri_axioms_def store_cap_mem_axiom_def
by (auto simp: writes_mem_cap_at_idx_def writes_mem_cap_Some_iff bind_eq_Some_conv cap_derivable_iff_derivable)
qed
qed
qed (auto intro: reachable_caps.intros)
qed
qed
lemma put_regval_get_mem_cap:
assumes s': "put_reg_val r v s = Some s'"
and "s_translate_address addr acctype s' = s_translate_address addr acctype s"
shows "get_mem_cap addr sz s' = get_mem_cap addr sz s"
using assms by (auto cong: bind_option_cong simp: get_mem_bytes_def)
definition system_access_reachable :: "'regs sequential_state \<Rightarrow> bool" where
"system_access_reachable s \<equiv> \<exists>c \<in> reachable_caps s.
permit_system_access (get_perms_method CC c) \<and> \<not>is_sealed_method CC c"
lemma get_reg_cap_intra_domain_trace_reachable:
assumes r: "c \<in> get_reg_caps r s'"
(*and t: "hasTrace t (instr_sem ISA instr)"*) and s': "s_run_trace t s = Some s'"
and axioms: "cheri_axioms CC ISA is_fetch False False t"
(*and no_exception: "\<not>hasException t (instr_sem ISA instr)"
and no_ccall: "invoked_caps ISA instr t = {}"*)
and translation_table_addrs_invariant: "s_invariant s_translation_tables t s"
and no_caps_in_translation_tables: "s_invariant_holds no_caps_in_translation_tables t s"
and tag: "is_tagged_method CC c"
and priv: "r \<in> privileged_regs ISA \<longrightarrow> system_access_reachable s"
shows "c \<in> reachable_caps s"
proof -
from r obtain v where v: "get_reg_val r s' = Some v" and c: "c \<in> caps_of_regval ISA v"
by (auto simp: bind_eq_Some_conv split: option.splits)
from v c s' show "c \<in> reachable_caps s"
proof (cases rule: get_reg_val_s_run_trace_cases)
case Init
show ?thesis
proof cases
assume r: "r \<in> privileged_regs ISA"
with priv obtain c' where c': "c' \<in> reachable_caps s"
and "permit_system_access (get_perms_method CC c')" and "\<not>is_sealed_method CC c'"
by (auto simp: system_access_reachable_def)
then show ?thesis using Init c tag by (intro reachable_caps.SysReg[OF _ r c']) auto
next
assume "r \<notin> privileged_regs ISA"
then show ?thesis using Init c tag by (intro reachable_caps.Reg) auto
qed
next
case (Update j v')
then have *: "c \<in> writes_reg_caps CC (caps_of_regval ISA) (t ! j)"
and "writes_to_reg (t ! j) = Some r"
using c tag by auto
then have "c \<in> derivable (available_caps CC ISA j t)"
using axioms tag \<open>j < length t\<close>
unfolding cheri_axioms_def store_cap_reg_axiom_def
by (fastforce simp: cap_derivable_iff_derivable)
moreover have "derivable (available_caps CC ISA j t) \<subseteq> reachable_caps s"
using axioms s' translation_table_addrs_invariant no_caps_in_translation_tables
by (intro derivable_available_caps_subseteq_reachable_caps)
ultimately show ?thesis by auto
qed
qed
lemma reachable_caps_trace_intradomain_monotonicity:
assumes axioms: "cheri_axioms CC ISA is_fetch False False t"
and s': "s_run_trace t s = Some s'"
and addr_trans_inv: "s_invariant (\<lambda>s' addr load. s_translate_address addr load s') t s"
and translation_table_addrs_invariant: "s_invariant s_translation_tables t s"
and no_caps_in_translation_tables: "s_invariant_holds no_caps_in_translation_tables t s"
shows "reachable_caps s' \<subseteq> reachable_caps s"
proof
fix c
assume "c \<in> reachable_caps s'"
then show "c \<in> reachable_caps s"
proof induction
case (Reg r c)
then show ?case
using axioms s' translation_table_addrs_invariant no_caps_in_translation_tables
by (intro get_reg_cap_intra_domain_trace_reachable) auto
next
case (SysReg r c c')
then show ?case
using axioms s' translation_table_addrs_invariant no_caps_in_translation_tables
by (intro get_reg_cap_intra_domain_trace_reachable) (auto simp: system_access_reachable_def)
next
case (Mem addr c vaddr c')
then have c: "get_mem_cap addr (tag_granule ISA) s' = Some c"
and aligned: "address_tag_aligned ISA addr"
by (auto split: if_splits)
have axiom: "store_tag_axiom CC ISA t"
using axioms
by (auto simp: cheri_axioms_def)
from c s' \<open>is_tagged_method CC c\<close> aligned axiom show ?case
proof (cases rule: get_mem_cap_run_trace_cases)
case Initial
have "s_translate_address vaddr Load s' = s_translate_address vaddr Load s"
using s_invariant_run_trace_eq[OF addr_trans_inv s']
by meson
then show ?thesis
using Initial Mem
by (intro reachable_caps.Mem[of addr s c vaddr c']) (auto split: if_splits)
next
case (Update k wk bytes r)
have "derivable (available_caps CC ISA k t) \<subseteq> reachable_caps s"
using assms axioms
by (intro derivable_available_caps_subseteq_reachable_caps)
then show ?thesis
using Update \<open>is_tagged_method CC c\<close> axioms
unfolding cheri_axioms_def store_cap_mem_axiom_def cap_derivable_iff_derivable
by (auto simp: writes_mem_cap_at_idx_def writes_mem_cap_Some_iff)
qed
qed (auto intro: reachable_caps.intros)
qed
lemma reachable_caps_instr_trace_intradomain_monotonicity:
assumes t: "hasTrace t (instr_sem ISA instr)"
and ta: "instr_assms t"
and s': "s_run_trace t s = Some s'"
and no_exception: "\<not>instr_raises_ex ISA instr t"
and no_ccall: "\<not>invokes_caps ISA instr t"
and addr_trans_inv: "s_invariant (\<lambda>s' addr load. s_translate_address addr load s') t s"
and translation_table_addrs_invariant: "s_invariant s_translation_tables t s"
and no_caps_in_translation_tables: "s_invariant_holds no_caps_in_translation_tables t s"
shows "reachable_caps s' \<subseteq> reachable_caps s"
using assms instr_cheri_axioms[OF t ta]
by (intro reachable_caps_trace_intradomain_monotonicity) auto
lemma reachable_caps_fetch_trace_intradomain_monotonicity:
assumes t: "hasTrace t (instr_fetch ISA)"
and ta: "fetch_assms t"
and s': "s_run_trace t s = Some s'"
and no_exception: "\<not>fetch_raises_ex ISA t"
and addr_trans_inv: "s_invariant (\<lambda>s' addr load. s_translate_address addr load s') t s"
and translation_table_addrs_invariant: "s_invariant s_translation_tables t s"
and no_caps_in_translation_tables: "s_invariant_holds no_caps_in_translation_tables t s"
shows "reachable_caps s' \<subseteq> reachable_caps s"
using assms fetch_cheri_axioms[OF t ta]
by (intro reachable_caps_trace_intradomain_monotonicity) auto
end
text \<open>Multi-instruction sequences\<close>
fun fetch_execute_loop :: "('cap, 'regval, 'instr, 'e) isa \<Rightarrow> nat \<Rightarrow> ('regval, unit, 'e) monad" where
"fetch_execute_loop ISA (Suc bound) = (instr_fetch ISA \<bind> instr_sem ISA) \<then> fetch_execute_loop ISA bound"
| "fetch_execute_loop ISA 0 = return ()"
fun instrs_raise_ex :: "('cap, 'regval, 'instr, 'e) isa \<Rightarrow> nat \<Rightarrow> 'regval trace \<Rightarrow> bool" where
"instrs_raise_ex ISA (Suc bound) t =
(\<exists>tf t'. t = tf @ t' \<and> hasTrace tf (instr_fetch ISA) \<and>
(fetch_raises_ex ISA tf \<or>
(\<exists>instr ti t''. t' = ti @ t'' \<and>
runTrace tf (instr_fetch ISA) = Some (Done instr) \<and>
hasTrace ti (instr_sem ISA instr) \<and>
(instr_raises_ex ISA instr ti \<or>
instrs_raise_ex ISA bound t''))))"
| "instrs_raise_ex ISA 0 t = False"
fun instrs_invoke_caps :: "('cap, 'regval, 'instr, 'e) isa \<Rightarrow> nat \<Rightarrow> 'regval trace \<Rightarrow> bool" where
"instrs_invoke_caps ISA (Suc bound) t =
(\<exists>tf t'. t = tf @ t' \<and> hasTrace tf (instr_fetch ISA) \<and>
(\<exists>instr ti t''. t' = ti @ t'' \<and>
runTrace tf (instr_fetch ISA) = Some (Done instr) \<and>
hasTrace ti (instr_sem ISA instr) \<and>
(invokes_caps ISA instr ti \<or>
instrs_invoke_caps ISA bound t'')))"
| "instrs_invoke_caps ISA 0 t = False"
context CHERI_ISA_State
begin
lemma reachable_caps_instrs_trace_intradomain_monotonicity:
assumes t: "hasTrace t (fetch_execute_loop ISA n)"
and ta: "fetch_assms t"
and s': "s_run_trace t s = Some s'"
and no_exception: "\<not>instrs_raise_ex ISA n t"
and no_ccall: "\<not>instrs_invoke_caps ISA n t"
and addr_trans_inv: "s_invariant (\<lambda>s' addr load. s_translate_address addr load s') t s"
and translation_table_addrs_invariant: "s_invariant s_translation_tables t s"
and no_caps_in_translation_tables: "s_invariant_holds no_caps_in_translation_tables t s"
shows "reachable_caps s' \<subseteq> reachable_caps s"
proof (use assms in \<open>induction n arbitrary: s t\<close>)
case 0
then show ?case by (auto simp: return_def hasTrace_iff_Traces_final)
next
case (Suc n)
then obtain m'
where "(instr_fetch ISA \<bind> (\<lambda>instr. \<lbrakk>instr\<rbrakk> \<then> fetch_execute_loop ISA n), t, m') \<in> Traces"
and m': "final m'"
by (auto simp: hasTrace_iff_Traces_final)
then show ?case
proof (cases rule: bind_Traces_cases)
case (Left m'')
then have "hasTrace t (instr_fetch ISA)"
using m'
by (auto elim!: final_bind_cases) (auto simp: hasTrace_iff_Traces_final final_def)
then show ?thesis
using Suc.prems
by (intro reachable_caps_fetch_trace_intradomain_monotonicity) auto
next
case (Bind tf instr t')
obtain s'' where s'': "s_run_trace tf s = Some s''" and t': "s_run_trace t' s'' = Some s'"
using Bind Suc
by (auto elim: runTraceS_appendE)
have tf: "hasTrace tf (instr_fetch ISA)"
using Bind
by (auto simp: hasTrace_iff_Traces_final final_def)
have invs':
"s_invariant (\<lambda>s' addr load. s_translate_address addr load s') t' s''"
"s_invariant s_translation_tables t' s''"
"s_invariant_holds no_caps_in_translation_tables t' s''"
using tf s'' Bind Suc.prems
using s_invariant_run_trace_eq[of no_caps_in_translation_tables tf s s'']
by (auto simp: s_invariant_append)
have ta': "fetch_assms tf" "instr_assms t'"
using Bind Suc.prems fetch_assms_appendE
by auto
from \<open>(\<lbrakk>instr\<rbrakk> \<then> fetch_execute_loop ISA n, t', m') \<in> Traces\<close>
have "reachable_caps s' \<subseteq> reachable_caps s''"
proof (cases rule: bind_Traces_cases)
case (Left m'')
then have "hasTrace t' \<lbrakk>instr\<rbrakk>"
using m'
by (auto elim!: final_bind_cases) (auto simp: hasTrace_iff_Traces_final final_def)
then show ?thesis
using tf t' s'' Bind Suc.prems invs' ta'
by (intro reachable_caps_instr_trace_intradomain_monotonicity)
(auto simp: runTrace_iff_Traces)
next
case (Bind ti am t'')
obtain s''' where s''': "s_run_trace ti s'' = Some s'''" and t'': "s_run_trace t'' s''' = Some s'"
using Bind t'
by (auto elim: runTraceS_appendE)
have ti: "hasTrace ti \<lbrakk>instr\<rbrakk>"
using Bind
by (auto simp: hasTrace_iff_Traces_final final_def)
have invs'':
"s_invariant (\<lambda>s' addr load. s_translate_address addr load s') t'' s'''"
"s_invariant s_translation_tables t'' s'''"
"s_invariant_holds no_caps_in_translation_tables t'' s'''"
using invs' s''' Bind
using s_invariant_run_trace_eq[of no_caps_in_translation_tables ti s'' s''']
by (auto simp: s_invariant_append)
have ta'': "instr_assms ti" "fetch_assms t''"
using Bind ta' instr_assms_appendE
by auto
have no_exception': "\<not>fetch_raises_ex ISA tf" "\<not>instr_raises_ex ISA instr ti"
and no_ccall': "\<not>invokes_caps ISA instr ti"
and no_exception'': "\<not>instrs_raise_ex ISA n t''"
and no_ccall'': "\<not>instrs_invoke_caps ISA n t''"
using ti tf Suc.prems Bind \<open>t = tf @ t'\<close>
using \<open>Run (instr_fetch ISA) tf instr\<close>
by (auto simp: runTrace_iff_Traces)
then have "reachable_caps s' \<subseteq> reachable_caps s'''"
using Bind m' t'' invs'' ta''
by (intro Suc.IH) (auto simp: hasTrace_iff_Traces_final final_def)
also have "reachable_caps s''' \<subseteq> reachable_caps s''"
using ti s''' no_exception' no_ccall' invs' \<open>t' = ti @ t''\<close> ta''
by (intro reachable_caps_instr_trace_intradomain_monotonicity)
(auto simp: s_invariant_append)
finally show ?thesis .
qed
also have "reachable_caps s'' \<subseteq> reachable_caps s"
using tf s'' Bind Suc.prems ta'
by (intro reachable_caps_fetch_trace_intradomain_monotonicity)
(auto simp: s_invariant_append)
finally show ?thesis .
qed
qed
end
end
|
import phase2.approximation
open set
open_locale classical
universe u
namespace con_nf
variables [params.{u}] (α : Λ) [position_data.{}] [phase_2_assumptions α] {β : type_index}
(π : near_litter_approx) (A : extended_index β)
namespace near_litter_approx
def id_on_flexible : local_perm litter := {
to_fun := id,
inv_fun := id,
domain := {L | flexible α L A} \ π.litter_perm.domain,
to_fun_domain' := λ L h, h,
inv_fun_domain' := λ L h, h,
left_inv' := λ L h, rfl,
right_inv' := λ L h, rfl,
}
lemma id_on_flexible_domain :
(id_on_flexible α π A).domain = {L | flexible α L A} \ π.litter_perm.domain := rfl
lemma id_on_flexible_domain_disjoint :
disjoint π.litter_perm.domain (id_on_flexible α π A).domain :=
by rw [disjoint_iff_inter_eq_empty, id_on_flexible_domain, inter_diff_self]
noncomputable def flexible_completion_litter_perm : local_perm litter :=
local_perm.piecewise π.litter_perm (id_on_flexible α π A) (id_on_flexible_domain_disjoint α π A)
lemma flexible_completion_litter_perm_domain' :
(flexible_completion_litter_perm α π A).domain = π.litter_perm.domain ∪ {L | flexible α L A} :=
by rw [flexible_completion_litter_perm, local_perm.piecewise_domain,
id_on_flexible_domain, union_diff_self]
noncomputable def flexible_completion : near_litter_approx := {
atom_perm := π.atom_perm,
litter_perm := flexible_completion_litter_perm α π A,
domain_small := π.domain_small,
}
lemma flexible_completion_litter_perm_domain :
(flexible_completion α π A).litter_perm.domain = π.litter_perm.domain ∪ {L | flexible α L A} :=
by rw [flexible_completion, flexible_completion_litter_perm_domain']
lemma flexible_completion_litter_perm_domain_free (hπ : π.free α A) :
(flexible_completion α π A).litter_perm.domain = {L | flexible α L A} :=
begin
rw [flexible_completion_litter_perm_domain, union_eq_right_iff_subset],
exact λ L hL, hπ L hL,
end
end near_litter_approx
end con_nf
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Yury Kudryashov, Neil Strickland
! This file was ported from Lean 3 source module algebra.ring.semiconj
! leanprover-community/mathlib commit 70d50ecfd4900dd6d328da39ab7ebd516abe4025
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Algebra.Group.Semiconj
import Mathlib.Algebra.Ring.Defs
/-!
# Semirings and rings
This file gives lemmas about semirings, rings and domains.
This is analogous to `Mathlib.Algebra.Group.Basic`,
the difference being that the former is about `+` and `*` separately, while
the present file is about their interaction.
For the definitions of semirings and rings see `Mathlib.Algebra.Ring.Defs`.
-/
universe u v w x
variable {α : Type u} {β : Type v} {γ : Type w} {R : Type x}
open Function
namespace SemiconjBy
@[simp]
theorem add_right [Distrib R] {a x y x' y' : R} (h : SemiconjBy a x y) (h' : SemiconjBy a x' y') :
SemiconjBy a (x + x') (y + y') := by
simp only [SemiconjBy, left_distrib, right_distrib, h.eq, h'.eq]
#align semiconj_by.add_right SemiconjBy.add_right
@[simp]
theorem add_left [Distrib R] {a b x y : R} (ha : SemiconjBy a x y) (hb : SemiconjBy b x y) :
SemiconjBy (a + b) x y := by
simp only [SemiconjBy, left_distrib, right_distrib, ha.eq, hb.eq]
#align semiconj_by.add_left SemiconjBy.add_left
section
variable [Mul R] [HasDistribNeg R] {a x y : R}
theorem neg_right (h : SemiconjBy a x y) : SemiconjBy a (-x) (-y) := by
simp only [SemiconjBy, h.eq, neg_mul, mul_neg]
#align semiconj_by.neg_right SemiconjBy.neg_right
@[simp]
theorem neg_right_iff : SemiconjBy a (-x) (-y) ↔ SemiconjBy a x y :=
⟨fun h => neg_neg x ▸ neg_neg y ▸ h.neg_right, SemiconjBy.neg_right⟩
#align semiconj_by.neg_right_iff SemiconjBy.neg_right_iff
theorem neg_left (h : SemiconjBy a x y) : SemiconjBy (-a) x y := by
simp only [SemiconjBy, h.eq, neg_mul, mul_neg]
#align semiconj_by.neg_left SemiconjBy.neg_left
@[simp]
theorem neg_left_iff : SemiconjBy (-a) x y ↔ SemiconjBy a x y :=
⟨fun h => neg_neg a ▸ h.neg_left, SemiconjBy.neg_left⟩
#align semiconj_by.neg_left_iff SemiconjBy.neg_left_iff
end
section
variable [MulOneClass R] [HasDistribNeg R] {a x y : R}
-- porting note: `simpNF` told me to remove `simp` attribute
theorem neg_one_right (a : R) : SemiconjBy a (-1) (-1) :=
(one_right a).neg_right
#align semiconj_by.neg_one_right SemiconjBy.neg_one_right
-- porting note: `simpNF` told me to remove `simp` attribute
theorem neg_one_left (x : R) : SemiconjBy (-1) x x :=
(SemiconjBy.one_left x).neg_left
#align semiconj_by.neg_one_left SemiconjBy.neg_one_left
end
section
variable [NonUnitalNonAssocRing R] {a b x y x' y' : R}
@[simp]
theorem sub_right (h : SemiconjBy a x y) (h' : SemiconjBy a x' y') :
SemiconjBy a (x - x') (y - y') := by
simpa only [sub_eq_add_neg] using h.add_right h'.neg_right
#align semiconj_by.sub_right SemiconjBy.sub_right
@[simp]
theorem sub_left (ha : SemiconjBy a x y) (hb : SemiconjBy b x y) :
SemiconjBy (a - b) x y := by
simpa only [sub_eq_add_neg] using ha.add_left hb.neg_left
#align semiconj_by.sub_left SemiconjBy.sub_left
end
end SemiconjBy
|
Formal statement is: lemma at_right_to_top: "(at_right (0::real)) = filtermap inverse at_top" Informal statement is: The filter of right neighborhoods of $0$ is equal to the filter of neighborhoods of $\infty$ under the map $x \mapsto 1/x$. |
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Animating the CompCert C semantics *)
Require Import FunInd.
Require Import Axioms Classical.
Require Import String Coqlib Decidableplus.
Require Import Errors Maps Integers Floats.
Require Import AST Values Memory Events Globalenvs Builtins Determinism.
Require Import Ctypes Cop Csyntax Csem.
Require Cstrategy.
Local Open Scope string_scope.
Local Open Scope list_scope.
(** Error monad with options or lists *)
Notation "'do' X <- A ; B" := (match A with Some X => B | None => None end)
(at level 200, X ident, A at level 100, B at level 200)
: option_monad_scope.
Notation "'do' X , Y <- A ; B" := (match A with Some (X, Y) => B | None => None end)
(at level 200, X ident, Y ident, A at level 100, B at level 200)
: option_monad_scope.
Notation "'do' X , Y , Z <- A ; B" := (match A with Some (X, Y, Z) => B | None => None end)
(at level 200, X ident, Y ident, Z ident, A at level 100, B at level 200)
: option_monad_scope.
Notation " 'check' A ; B" := (if A then B else None)
(at level 200, A at level 100, B at level 200)
: option_monad_scope.
Notation "'do' X <- A ; B" := (match A with Some X => B | None => nil end)
(at level 200, X ident, A at level 100, B at level 200)
: list_monad_scope.
Notation " 'check' A ; B" := (if A then B else nil)
(at level 200, A at level 100, B at level 200)
: list_monad_scope.
Definition is_val (a: expr) : option (val * type) :=
match a with
| Eval v ty => Some(v, ty)
| _ => None
end.
Lemma is_val_inv:
forall a v ty, is_val a = Some(v, ty) -> a = Eval v ty.
Proof.
intros until ty. destruct a; simpl; congruence.
Qed.
Definition is_loc (a: expr) : option (block * ptrofs * type) :=
match a with
| Eloc b ofs ty => Some(b, ofs, ty)
| _ => None
end.
Lemma is_loc_inv:
forall a b ofs ty, is_loc a = Some(b, ofs, ty) -> a = Eloc b ofs ty.
Proof.
intros until ty. destruct a; simpl; congruence.
Qed.
Local Open Scope option_monad_scope.
Fixpoint is_val_list (al: exprlist) : option (list (val * type)) :=
match al with
| Enil => Some nil
| Econs a1 al => do vt1 <- is_val a1; do vtl <- is_val_list al; Some(vt1::vtl)
end.
Definition is_skip (s: statement) : {s = Sskip} + {s <> Sskip}.
Proof.
destruct s; (left; congruence) || (right; congruence).
Defined.
(** * Events, volatile memory accesses, and external functions. *)
Section EXEC.
Variable ge: genv.
Definition eventval_of_val (v: val) (t: typ) : option eventval :=
match v with
| Vint i => check (typ_eq t AST.Tint); Some (EVint i)
| Vfloat f => check (typ_eq t AST.Tfloat); Some (EVfloat f)
| Vsingle f => check (typ_eq t AST.Tsingle); Some (EVsingle f)
| Vlong n => check (typ_eq t AST.Tlong); Some (EVlong n)
| Vptr b ofs =>
do id <- Genv.invert_symbol ge b;
check (Genv.public_symbol ge id);
check (typ_eq t AST.Tptr);
Some (EVptr_global id ofs)
| _ => None
end.
Fixpoint list_eventval_of_val (vl: list val) (tl: list typ) : option (list eventval) :=
match vl, tl with
| nil, nil => Some nil
| v1::vl, t1::tl =>
do ev1 <- eventval_of_val v1 t1;
do evl <- list_eventval_of_val vl tl;
Some (ev1 :: evl)
| _, _ => None
end.
Definition val_of_eventval (ev: eventval) (t: typ) : option val :=
match ev with
| EVint i => check (typ_eq t AST.Tint); Some (Vint i)
| EVfloat f => check (typ_eq t AST.Tfloat); Some (Vfloat f)
| EVsingle f => check (typ_eq t AST.Tsingle); Some (Vsingle f)
| EVlong n => check (typ_eq t AST.Tlong); Some (Vlong n)
| EVptr_global id ofs =>
check (Genv.public_symbol ge id);
check (typ_eq t AST.Tptr);
do b <- Genv.find_symbol ge id;
Some (Vptr b ofs)
end.
Ltac mydestr :=
match goal with
| [ |- None = Some _ -> _ ] => let X := fresh "X" in intro X; discriminate
| [ |- Some _ = Some _ -> _ ] => let X := fresh "X" in intro X; inv X
| [ |- match ?x with Some _ => _ | None => _ end = Some _ -> _ ] => destruct x eqn:?; mydestr
| [ |- match ?x with true => _ | false => _ end = Some _ -> _ ] => destruct x eqn:?; mydestr
| [ |- match ?x with left _ => _ | right _ => _ end = Some _ -> _ ] => destruct x; mydestr
| _ => idtac
end.
Lemma eventval_of_val_sound:
forall v t ev, eventval_of_val v t = Some ev -> eventval_match ge ev t v.
Proof.
intros until ev. destruct v; simpl; mydestr; constructor.
auto. apply Genv.invert_find_symbol; auto.
Qed.
Lemma eventval_of_val_complete:
forall ev t v, eventval_match ge ev t v -> eventval_of_val v t = Some ev.
Proof.
induction 1; simpl.
- auto.
- auto.
- auto.
- auto.
- rewrite (Genv.find_invert_symbol _ _ H0). simpl in H; rewrite H.
rewrite dec_eq_true. auto.
Qed.
Lemma list_eventval_of_val_sound:
forall vl tl evl, list_eventval_of_val vl tl = Some evl -> eventval_list_match ge evl tl vl.
Proof with try discriminate.
induction vl; destruct tl; simpl; intros; inv H.
constructor.
destruct (eventval_of_val a t) as [ev1|] eqn:?...
destruct (list_eventval_of_val vl tl) as [evl'|] eqn:?...
inv H1. constructor. apply eventval_of_val_sound; auto. eauto.
Qed.
Lemma list_eventval_of_val_complete:
forall evl tl vl, eventval_list_match ge evl tl vl -> list_eventval_of_val vl tl = Some evl.
Proof.
induction 1; simpl. auto.
rewrite (eventval_of_val_complete _ _ _ H). rewrite IHeventval_list_match. auto.
Qed.
Lemma val_of_eventval_sound:
forall ev t v, val_of_eventval ev t = Some v -> eventval_match ge ev t v.
Proof.
intros until v. destruct ev; simpl; mydestr; constructor; auto.
Qed.
Lemma val_of_eventval_complete:
forall ev t v, eventval_match ge ev t v -> val_of_eventval ev t = Some v.
Proof.
induction 1; simpl.
- auto.
- auto.
- auto.
- auto.
- simpl in *. rewrite H, H0. rewrite dec_eq_true. auto.
Qed.
(** Volatile memory accesses. *)
Definition do_volatile_load (w: world) (chunk: memory_chunk) (m: mem) (b: block) (ofs: ptrofs)
: option (world * trace * val) :=
if Genv.block_is_volatile ge b then
do id <- Genv.invert_symbol ge b;
match nextworld_vload w chunk id ofs with
| None => None
| Some(res, w') =>
do vres <- val_of_eventval res (type_of_chunk chunk);
Some(w', Event_vload chunk id ofs res :: nil, Val.load_result chunk vres)
end
else
do v <- Mem.load chunk m b (Ptrofs.unsigned ofs);
Some(w, E0, v).
Definition do_volatile_store (w: world) (chunk: memory_chunk) (m: mem) (b: block) (ofs: ptrofs) (v: val)
: option (world * trace * mem) :=
if Genv.block_is_volatile ge b then
do id <- Genv.invert_symbol ge b;
do ev <- eventval_of_val (Val.load_result chunk v) (type_of_chunk chunk);
do w' <- nextworld_vstore w chunk id ofs ev;
Some(w', Event_vstore chunk id ofs ev :: nil, m)
else
do m' <- Mem.store chunk m b (Ptrofs.unsigned ofs) v;
Some(w, E0, m').
Lemma do_volatile_load_sound:
forall w chunk m b ofs w' t v,
do_volatile_load w chunk m b ofs = Some(w', t, v) ->
volatile_load ge chunk m b ofs t v /\ possible_trace w t w'.
Proof.
intros until v. unfold do_volatile_load. mydestr.
destruct p as [ev w'']. mydestr.
split. constructor; auto. apply Genv.invert_find_symbol; auto.
apply val_of_eventval_sound; auto.
econstructor. constructor; eauto. constructor.
split. constructor; auto. constructor.
Qed.
Lemma do_volatile_load_complete:
forall w chunk m b ofs w' t v,
volatile_load ge chunk m b ofs t v -> possible_trace w t w' ->
do_volatile_load w chunk m b ofs = Some(w', t, v).
Proof.
unfold do_volatile_load; intros. inv H; simpl in *.
rewrite H1. rewrite (Genv.find_invert_symbol _ _ H2). inv H0. inv H8. inv H6. rewrite H9.
rewrite (val_of_eventval_complete _ _ _ H3). auto.
rewrite H1. rewrite H2. inv H0. auto.
Qed.
Lemma do_volatile_store_sound:
forall w chunk m b ofs v w' t m',
do_volatile_store w chunk m b ofs v = Some(w', t, m') ->
volatile_store ge chunk m b ofs v t m' /\ possible_trace w t w'.
Proof.
intros until m'. unfold do_volatile_store. mydestr.
split. constructor; auto. apply Genv.invert_find_symbol; auto.
apply eventval_of_val_sound; auto.
econstructor. constructor; eauto. constructor.
split. constructor; auto. constructor.
Qed.
Lemma do_volatile_store_complete:
forall w chunk m b ofs v w' t m',
volatile_store ge chunk m b ofs v t m' -> possible_trace w t w' ->
do_volatile_store w chunk m b ofs v = Some(w', t, m').
Proof.
unfold do_volatile_store; intros. inv H; simpl in *.
rewrite H1. rewrite (Genv.find_invert_symbol _ _ H2).
rewrite (eventval_of_val_complete _ _ _ H3).
inv H0. inv H8. inv H6. rewrite H9. auto.
rewrite H1. rewrite H2. inv H0. auto.
Qed.
(** Accessing locations *)
Definition do_deref_loc (w: world) (ty: type) (m: mem) (b: block) (ofs: ptrofs) : option (world * trace * val) :=
match access_mode ty with
| By_value chunk =>
match type_is_volatile ty with
| false => do v <- Mem.loadv chunk m (Vptr b ofs); Some(w, E0, v)
| true => do_volatile_load w chunk m b ofs
end
| By_reference => Some(w, E0, Vptr b ofs)
| By_copy => Some(w, E0, Vptr b ofs)
| _ => None
end.
Definition assign_copy_ok (ty: type) (b: block) (ofs: ptrofs) (b': block) (ofs': ptrofs) : Prop :=
(alignof_blockcopy ge ty | Ptrofs.unsigned ofs') /\ (alignof_blockcopy ge ty | Ptrofs.unsigned ofs) /\
(b' <> b \/ Ptrofs.unsigned ofs' = Ptrofs.unsigned ofs
\/ Ptrofs.unsigned ofs' + sizeof ge ty <= Ptrofs.unsigned ofs
\/ Ptrofs.unsigned ofs + sizeof ge ty <= Ptrofs.unsigned ofs').
Remark check_assign_copy:
forall (ty: type) (b: block) (ofs: ptrofs) (b': block) (ofs': ptrofs),
{ assign_copy_ok ty b ofs b' ofs' } + {~ assign_copy_ok ty b ofs b' ofs' }.
Proof with try (right; intuition omega).
intros. unfold assign_copy_ok.
destruct (Zdivide_dec (alignof_blockcopy ge ty) (Ptrofs.unsigned ofs')); auto...
destruct (Zdivide_dec (alignof_blockcopy ge ty) (Ptrofs.unsigned ofs)); auto...
assert (Y: {b' <> b \/
Ptrofs.unsigned ofs' = Ptrofs.unsigned ofs \/
Ptrofs.unsigned ofs' + sizeof ge ty <= Ptrofs.unsigned ofs \/
Ptrofs.unsigned ofs + sizeof ge ty <= Ptrofs.unsigned ofs'} +
{~(b' <> b \/
Ptrofs.unsigned ofs' = Ptrofs.unsigned ofs \/
Ptrofs.unsigned ofs' + sizeof ge ty <= Ptrofs.unsigned ofs \/
Ptrofs.unsigned ofs + sizeof ge ty <= Ptrofs.unsigned ofs')}).
destruct (eq_block b' b); auto.
destruct (zeq (Ptrofs.unsigned ofs') (Ptrofs.unsigned ofs)); auto.
destruct (zle (Ptrofs.unsigned ofs' + sizeof ge ty) (Ptrofs.unsigned ofs)); auto.
destruct (zle (Ptrofs.unsigned ofs + sizeof ge ty) (Ptrofs.unsigned ofs')); auto.
right; intuition omega.
destruct Y... left; intuition omega.
Defined.
Definition do_assign_loc (w: world) (ty: type) (m: mem) (b: block) (ofs: ptrofs) (v: val): option (world * trace * mem) :=
match access_mode ty with
| By_value chunk =>
match type_is_volatile ty with
| false => do m' <- Mem.storev chunk m (Vptr b ofs) v; Some(w, E0, m')
| true => do_volatile_store w chunk m b ofs v
end
| By_copy =>
match v with
| Vptr b' ofs' =>
if check_assign_copy ty b ofs b' ofs' then
do bytes <- Mem.loadbytes m b' (Ptrofs.unsigned ofs') (sizeof ge ty);
do m' <- Mem.storebytes m b (Ptrofs.unsigned ofs) bytes;
Some(w, E0, m')
else None
| _ => None
end
| _ => None
end.
Lemma do_deref_loc_sound:
forall w ty m b ofs w' t v,
do_deref_loc w ty m b ofs = Some(w', t, v) ->
deref_loc ge ty m b ofs t v /\ possible_trace w t w'.
Proof.
unfold do_deref_loc; intros until v.
destruct (access_mode ty) eqn:?; mydestr.
intros. exploit do_volatile_load_sound; eauto. intuition. eapply deref_loc_volatile; eauto.
split. eapply deref_loc_value; eauto. constructor.
split. eapply deref_loc_reference; eauto. constructor.
split. eapply deref_loc_copy; eauto. constructor.
Qed.
Lemma do_deref_loc_complete:
forall w ty m b ofs w' t v,
deref_loc ge ty m b ofs t v -> possible_trace w t w' ->
do_deref_loc w ty m b ofs = Some(w', t, v).
Proof.
unfold do_deref_loc; intros. inv H.
inv H0. rewrite H1; rewrite H2; rewrite H3; auto.
rewrite H1; rewrite H2. apply do_volatile_load_complete; auto.
inv H0. rewrite H1. auto.
inv H0. rewrite H1. auto.
Qed.
Lemma do_assign_loc_sound:
forall w ty m b ofs v w' t m',
do_assign_loc w ty m b ofs v = Some(w', t, m') ->
assign_loc ge ty m b ofs v t m' /\ possible_trace w t w'.
Proof.
unfold do_assign_loc; intros until m'.
destruct (access_mode ty) eqn:?; mydestr.
intros. exploit do_volatile_store_sound; eauto. intuition. eapply assign_loc_volatile; eauto.
split. eapply assign_loc_value; eauto. constructor.
destruct v; mydestr. destruct a as [P [Q R]].
split. eapply assign_loc_copy; eauto. constructor.
Qed.
Lemma do_assign_loc_complete:
forall w ty m b ofs v w' t m',
assign_loc ge ty m b ofs v t m' -> possible_trace w t w' ->
do_assign_loc w ty m b ofs v = Some(w', t, m').
Proof.
unfold do_assign_loc; intros. inv H.
inv H0. rewrite H1; rewrite H2; rewrite H3; auto.
rewrite H1; rewrite H2. apply do_volatile_store_complete; auto.
rewrite H1. destruct (check_assign_copy ty b ofs b' ofs').
inv H0. rewrite H5; rewrite H6; auto.
elim n. red; tauto.
Qed.
(** External calls *)
Variable do_external_function:
string -> signature -> Senv.t -> world -> list val -> mem -> option (world * trace * val * mem).
Hypothesis do_external_function_sound:
forall id sg ge vargs m t vres m' w w',
do_external_function id sg ge w vargs m = Some(w', t, vres, m') ->
external_functions_sem id sg ge vargs m t vres m' /\ possible_trace w t w'.
Hypothesis do_external_function_complete:
forall id sg ge vargs m t vres m' w w',
external_functions_sem id sg ge vargs m t vres m' ->
possible_trace w t w' ->
do_external_function id sg ge w vargs m = Some(w', t, vres, m').
Variable do_inline_assembly:
string -> signature -> Senv.t -> world -> list val -> mem -> option (world * trace * val * mem).
Hypothesis do_inline_assembly_sound:
forall txt sg ge vargs m t vres m' w w',
do_inline_assembly txt sg ge w vargs m = Some(w', t, vres, m') ->
inline_assembly_sem txt sg ge vargs m t vres m' /\ possible_trace w t w'.
Hypothesis do_inline_assembly_complete:
forall txt sg ge vargs m t vres m' w w',
inline_assembly_sem txt sg ge vargs m t vres m' ->
possible_trace w t w' ->
do_inline_assembly txt sg ge w vargs m = Some(w', t, vres, m').
Definition do_ef_volatile_load (chunk: memory_chunk)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| Vptr b ofs :: nil => do w',t,v <- do_volatile_load w chunk m b ofs; Some(w',t,v,m)
| _ => None
end.
Definition do_ef_volatile_store (chunk: memory_chunk)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| Vptr b ofs :: v :: nil => do w',t,m' <- do_volatile_store w chunk m b ofs v; Some(w',t,Vundef,m')
| _ => None
end.
Definition do_ef_volatile_load_global (chunk: memory_chunk) (id: ident) (ofs: ptrofs)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
do b <- Genv.find_symbol ge id; do_ef_volatile_load chunk w (Vptr b ofs :: vargs) m.
Definition do_ef_volatile_store_global (chunk: memory_chunk) (id: ident) (ofs: ptrofs)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
do b <- Genv.find_symbol ge id; do_ef_volatile_store chunk w (Vptr b ofs :: vargs) m.
Definition do_alloc_size (v: val) : option ptrofs :=
match v with
| Vint n => if Archi.ptr64 then None else Some (Ptrofs.of_int n)
| Vlong n => if Archi.ptr64 then Some (Ptrofs.of_int64 n) else None
| _ => None
end.
Definition do_ef_malloc
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| v :: nil =>
do sz <- do_alloc_size v;
let (m', b) := Mem.alloc m (- size_chunk Mptr) (Ptrofs.unsigned sz) in
do m'' <- Mem.store Mptr m' b (- size_chunk Mptr) v;
Some(w, E0, Vptr b Ptrofs.zero, m'')
| _ => None
end.
Definition do_ef_free
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| Vptr b lo :: nil =>
do vsz <- Mem.load Mptr m b (Ptrofs.unsigned lo - size_chunk Mptr);
do sz <- do_alloc_size vsz;
check (zlt 0 (Ptrofs.unsigned sz));
do m' <- Mem.free m b (Ptrofs.unsigned lo - size_chunk Mptr) (Ptrofs.unsigned lo + Ptrofs.unsigned sz);
Some(w, E0, Vundef, m')
| _ => None
end.
Definition memcpy_args_ok
(sz al: Z) (bdst: block) (odst: Z) (bsrc: block) (osrc: Z) : Prop :=
(al = 1 \/ al = 2 \/ al = 4 \/ al = 8)
/\ sz >= 0 /\ (al | sz)
/\ (sz > 0 -> (al | osrc))
/\ (sz > 0 -> (al | odst))
/\ (bsrc <> bdst \/ osrc = odst \/ osrc + sz <= odst \/ odst + sz <= osrc).
Definition do_ef_memcpy (sz al: Z)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| Vptr bdst odst :: Vptr bsrc osrc :: nil =>
if decide (memcpy_args_ok sz al bdst (Ptrofs.unsigned odst) bsrc (Ptrofs.unsigned osrc)) then
do bytes <- Mem.loadbytes m bsrc (Ptrofs.unsigned osrc) sz;
do m' <- Mem.storebytes m bdst (Ptrofs.unsigned odst) bytes;
Some(w, E0, Vundef, m')
else None
| _ => None
end.
Definition do_ef_annot (text: string) (targs: list typ)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
do args <- list_eventval_of_val vargs targs;
Some(w, Event_annot text args :: E0, Vundef, m).
Definition do_ef_annot_val (text: string) (targ: typ)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| varg :: nil =>
do arg <- eventval_of_val varg targ;
Some(w, Event_annot text (arg :: nil) :: E0, varg, m)
| _ => None
end.
Definition do_ef_debug (kind: positive) (text: ident) (targs: list typ)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
Some(w, E0, Vundef, m).
Definition do_builtin_or_external (name: string) (sg: signature)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match lookup_builtin_function name sg with
| Some bf => match builtin_function_sem bf vargs with Some v => Some(w, E0, v, m) | None => None end
| None => do_external_function name sg ge w vargs m
end.
Definition do_external (ef: external_function):
world -> list val -> mem -> option (world * trace * val * mem) :=
match ef with
| EF_external name sg => do_external_function name sg ge
| EF_builtin name sg => do_builtin_or_external name sg
| EF_runtime name sg => do_builtin_or_external name sg
| EF_vload chunk => do_ef_volatile_load chunk
| EF_vstore chunk => do_ef_volatile_store chunk
| EF_malloc => do_ef_malloc
| EF_free => do_ef_free
| EF_memcpy sz al => do_ef_memcpy sz al
| EF_annot kind text targs => do_ef_annot text targs
| EF_annot_val kind text targ => do_ef_annot_val text targ
| EF_inline_asm text sg clob => do_inline_assembly text sg ge
| EF_debug kind text targs => do_ef_debug kind text targs
end.
Lemma do_ef_external_sound:
forall ef w vargs m w' t vres m',
do_external ef w vargs m = Some(w', t, vres, m') ->
external_call ef ge vargs m t vres m' /\ possible_trace w t w'.
Proof with try congruence.
intros until m'.
assert (SIZE: forall v sz, do_alloc_size v = Some sz -> v = Vptrofs sz).
{ intros until sz; unfold Vptrofs; destruct v; simpl; destruct Archi.ptr64 eqn:SF;
intros EQ; inv EQ; f_equal; symmetry; eauto with ptrofs. }
assert (BF_EX: forall name sg,
do_builtin_or_external name sg w vargs m = Some (w', t, vres, m') ->
builtin_or_external_sem name sg ge vargs m t vres m' /\ possible_trace w t w').
{ unfold do_builtin_or_external, builtin_or_external_sem; intros.
destruct (lookup_builtin_function name sg ) as [bf|].
- destruct (builtin_function_sem bf vargs) as [vres1|] eqn:BF; inv H.
split. constructor; auto. constructor.
- eapply do_external_function_sound; eauto.
}
destruct ef; simpl.
(* EF_external *)
eapply do_external_function_sound; eauto.
(* EF_builtin *)
eapply BF_EX; eauto.
(* EF_runtime *)
eapply BF_EX; eauto.
(* EF_vload *)
unfold do_ef_volatile_load. destruct vargs... destruct v... destruct vargs...
mydestr. destruct p as [[w'' t''] v]; mydestr.
exploit do_volatile_load_sound; eauto. intuition. econstructor; eauto.
auto.
(* EF_vstore *)
unfold do_ef_volatile_store. destruct vargs... destruct v... destruct vargs... destruct vargs...
mydestr. destruct p as [[w'' t''] m'']. mydestr.
exploit do_volatile_store_sound; eauto. intuition. econstructor; eauto.
auto.
(* EF_malloc *)
unfold do_ef_malloc. destruct vargs... destruct vargs... mydestr.
destruct (Mem.alloc m (- size_chunk Mptr) (Ptrofs.unsigned i)) as [m1 b] eqn:?. mydestr.
split. apply SIZE in Heqo. subst v. econstructor; eauto. constructor.
(* EF_free *)
unfold do_ef_free. destruct vargs... destruct v... destruct vargs...
mydestr. split. apply SIZE in Heqo0. econstructor; eauto. congruence. omega. constructor.
(* EF_memcpy *)
unfold do_ef_memcpy. destruct vargs... destruct v... destruct vargs...
destruct v... destruct vargs... mydestr.
apply Decidable_sound in Heqb1. red in Heqb1.
split. econstructor; eauto; tauto. constructor.
(* EF_annot *)
unfold do_ef_annot. mydestr.
split. constructor. apply list_eventval_of_val_sound; auto.
econstructor. constructor; eauto. constructor.
(* EF_annot_val *)
unfold do_ef_annot_val. destruct vargs... destruct vargs... mydestr.
split. constructor. apply eventval_of_val_sound; auto.
econstructor. constructor; eauto. constructor.
(* EF_inline_asm *)
eapply do_inline_assembly_sound; eauto.
(* EF_debug *)
unfold do_ef_debug. mydestr. split; constructor.
Qed.
Lemma do_ef_external_complete:
forall ef w vargs m w' t vres m',
external_call ef ge vargs m t vres m' -> possible_trace w t w' ->
do_external ef w vargs m = Some(w', t, vres, m').
Proof.
intros.
assert (SIZE: forall n, do_alloc_size (Vptrofs n) = Some n).
{ unfold Vptrofs, do_alloc_size; intros; destruct Archi.ptr64 eqn:SF.
rewrite Ptrofs.of_int64_to_int64; auto.
rewrite Ptrofs.of_int_to_int; auto. }
assert (BF_EX: forall name sg,
builtin_or_external_sem name sg ge vargs m t vres m' ->
do_builtin_or_external name sg w vargs m = Some (w', t, vres, m')).
{ unfold do_builtin_or_external, builtin_or_external_sem; intros.
destruct (lookup_builtin_function name sg) as [bf|].
- inv H1. inv H0. rewrite H2. auto.
- eapply do_external_function_complete; eauto.
}
destruct ef; simpl in *.
(* EF_external *)
eapply do_external_function_complete; eauto.
(* EF_builtin *)
eapply BF_EX; eauto.
(* EF_runtime *)
eapply BF_EX; eauto.
(* EF_vload *)
inv H; unfold do_ef_volatile_load.
exploit do_volatile_load_complete; eauto. intros EQ; rewrite EQ; auto.
(* EF_vstore *)
inv H; unfold do_ef_volatile_store.
exploit do_volatile_store_complete; eauto. intros EQ; rewrite EQ; auto.
(* EF_malloc *)
inv H; unfold do_ef_malloc.
inv H0. erewrite SIZE by eauto. rewrite H1, H2. auto.
(* EF_free *)
inv H; unfold do_ef_free.
inv H0. rewrite H1. erewrite SIZE by eauto. rewrite zlt_true. rewrite H3. auto. omega.
(* EF_memcpy *)
inv H; unfold do_ef_memcpy.
inv H0. rewrite Decidable_complete. rewrite H7; rewrite H8; auto.
red. tauto.
(* EF_annot *)
inv H; unfold do_ef_annot. inv H0. inv H6. inv H4.
rewrite (list_eventval_of_val_complete _ _ _ H1). auto.
(* EF_annot_val *)
inv H; unfold do_ef_annot_val. inv H0. inv H6. inv H4.
rewrite (eventval_of_val_complete _ _ _ H1). auto.
(* EF_inline_asm *)
eapply do_inline_assembly_complete; eauto.
(* EF_debug *)
inv H. inv H0. reflexivity.
Qed.
(** * Reduction of expressions *)
Inductive reduction: Type :=
| Lred (rule: string) (l': expr) (m': mem)
| Rred (rule: string) (r': expr) (m': mem) (t: trace)
| Callred (rule: string) (fd: fundef) (args: list val) (tyres: type) (m': mem)
| Stuckred.
Section EXPRS.
Variable e: env.
Variable w: world.
Fixpoint sem_cast_arguments (vtl: list (val * type)) (tl: typelist) (m: mem) : option (list val) :=
match vtl, tl with
| nil, Tnil => Some nil
| (v1,t1)::vtl, Tcons t1' tl =>
do v <- sem_cast v1 t1 t1' m; do vl <- sem_cast_arguments vtl tl m; Some(v::vl)
| _, _ => None
end.
(** The result of stepping an expression is a list [ll] of possible reducts.
Each element of [ll] is a pair of a context and the result of reducing
inside this context (see type [reduction] above).
The list [ll] is empty if the expression is fully reduced
(it's [Eval] for a r-value and [Eloc] for a l-value).
*)
Definition reducts (A: Type): Type := list ((expr -> A) * reduction).
Definition topred (r: reduction) : reducts expr :=
((fun (x: expr) => x), r) :: nil.
Definition stuck : reducts expr :=
((fun (x: expr) => x), Stuckred) :: nil.
Definition incontext {A B: Type} (ctx: A -> B) (ll: reducts A) : reducts B :=
map (fun z => ((fun (x: expr) => ctx(fst z x)), snd z)) ll.
Definition incontext2 {A1 A2 B: Type}
(ctx1: A1 -> B) (ll1: reducts A1)
(ctx2: A2 -> B) (ll2: reducts A2) : reducts B :=
incontext ctx1 ll1 ++ incontext ctx2 ll2.
Notation "'do' X <- A ; B" := (match A with Some X => B | None => stuck end)
(at level 200, X ident, A at level 100, B at level 200)
: reducts_monad_scope.
Notation "'do' X , Y <- A ; B" := (match A with Some (X, Y) => B | None => stuck end)
(at level 200, X ident, Y ident, A at level 100, B at level 200)
: reducts_monad_scope.
Notation "'do' X , Y , Z <- A ; B" := (match A with Some (X, Y, Z) => B | None => stuck end)
(at level 200, X ident, Y ident, Z ident, A at level 100, B at level 200)
: reducts_monad_scope.
Notation " 'check' A ; B" := (if A then B else stuck)
(at level 200, A at level 100, B at level 200)
: reducts_monad_scope.
Local Open Scope reducts_monad_scope.
Fixpoint step_expr (k: kind) (a: expr) (m: mem): reducts expr :=
match k, a with
| LV, Eloc b ofs ty =>
nil
| LV, Evar x ty =>
match e!x with
| Some(b, ty') =>
check type_eq ty ty';
topred (Lred "red_var_local" (Eloc b Ptrofs.zero ty) m)
| None =>
do b <- Genv.find_symbol ge x;
topred (Lred "red_var_global" (Eloc b Ptrofs.zero ty) m)
end
| LV, Ederef r ty =>
match is_val r with
| Some(Vptr b ofs, ty') =>
topred (Lred "red_deref" (Eloc b ofs ty) m)
| Some _ =>
stuck
| None =>
incontext (fun x => Ederef x ty) (step_expr RV r m)
end
| LV, Efield r f ty =>
match is_val r with
| Some(Vptr b ofs, ty') =>
match ty' with
| Tstruct id _ =>
do co <- ge.(genv_cenv)!id;
match field_offset ge f (co_members co) with
| Error _ => stuck
| OK delta => topred (Lred "red_field_struct" (Eloc b (Ptrofs.add ofs (Ptrofs.repr delta)) ty) m)
end
| Tunion id _ =>
do co <- ge.(genv_cenv)!id;
topred (Lred "red_field_union" (Eloc b ofs ty) m)
| _ => stuck
end
| Some _ =>
stuck
| None =>
incontext (fun x => Efield x f ty) (step_expr RV r m)
end
| RV, Eval v ty =>
nil
| RV, Evalof l ty =>
match is_loc l with
| Some(b, ofs, ty') =>
check type_eq ty ty';
do w',t,v <- do_deref_loc w ty m b ofs;
topred (Rred "red_rvalof" (Eval v ty) m t)
| None =>
incontext (fun x => Evalof x ty) (step_expr LV l m)
end
| RV, Eaddrof l ty =>
match is_loc l with
| Some(b, ofs, ty') => topred (Rred "red_addrof" (Eval (Vptr b ofs) ty) m E0)
| None => incontext (fun x => Eaddrof x ty) (step_expr LV l m)
end
| RV, Eunop op r1 ty =>
match is_val r1 with
| Some(v1, ty1) =>
do v <- sem_unary_operation op v1 ty1 m;
topred (Rred "red_unop" (Eval v ty) m E0)
| None =>
incontext (fun x => Eunop op x ty) (step_expr RV r1 m)
end
| RV, Ebinop op r1 r2 ty =>
match is_val r1, is_val r2 with
| Some(v1, ty1), Some(v2, ty2) =>
do v <- sem_binary_operation ge op v1 ty1 v2 ty2 m;
topred (Rred "red_binop" (Eval v ty) m E0)
| _, _ =>
incontext2 (fun x => Ebinop op x r2 ty) (step_expr RV r1 m)
(fun x => Ebinop op r1 x ty) (step_expr RV r2 m)
end
| RV, Ecast r1 ty =>
match is_val r1 with
| Some(v1, ty1) =>
do v <- sem_cast v1 ty1 ty m;
topred (Rred "red_cast" (Eval v ty) m E0)
| None =>
incontext (fun x => Ecast x ty) (step_expr RV r1 m)
end
| RV, Eseqand r1 r2 ty =>
match is_val r1 with
| Some(v1, ty1) =>
do b <- bool_val v1 ty1 m;
if b then topred (Rred "red_seqand_true" (Eparen r2 type_bool ty) m E0)
else topred (Rred "red_seqand_false" (Eval (Vint Int.zero) ty) m E0)
| None =>
incontext (fun x => Eseqand x r2 ty) (step_expr RV r1 m)
end
| RV, Eseqor r1 r2 ty =>
match is_val r1 with
| Some(v1, ty1) =>
do b <- bool_val v1 ty1 m;
if b then topred (Rred "red_seqor_true" (Eval (Vint Int.one) ty) m E0)
else topred (Rred "red_seqor_false" (Eparen r2 type_bool ty) m E0)
| None =>
incontext (fun x => Eseqor x r2 ty) (step_expr RV r1 m)
end
| RV, Econdition r1 r2 r3 ty =>
match is_val r1 with
| Some(v1, ty1) =>
do b <- bool_val v1 ty1 m;
topred (Rred "red_condition" (Eparen (if b then r2 else r3) ty ty) m E0)
| None =>
incontext (fun x => Econdition x r2 r3 ty) (step_expr RV r1 m)
end
| RV, Esizeof ty' ty =>
topred (Rred "red_sizeof" (Eval (Vptrofs (Ptrofs.repr (sizeof ge ty'))) ty) m E0)
| RV, Ealignof ty' ty =>
topred (Rred "red_alignof" (Eval (Vptrofs (Ptrofs.repr (alignof ge ty'))) ty) m E0)
| RV, Eassign l1 r2 ty =>
match is_loc l1, is_val r2 with
| Some(b, ofs, ty1), Some(v2, ty2) =>
check type_eq ty1 ty;
do v <- sem_cast v2 ty2 ty1 m;
do w',t,m' <- do_assign_loc w ty1 m b ofs v;
topred (Rred "red_assign" (Eval v ty) m' t)
| _, _ =>
incontext2 (fun x => Eassign x r2 ty) (step_expr LV l1 m)
(fun x => Eassign l1 x ty) (step_expr RV r2 m)
end
| RV, Eassignop op l1 r2 tyres ty =>
match is_loc l1, is_val r2 with
| Some(b, ofs, ty1), Some(v2, ty2) =>
check type_eq ty1 ty;
do w',t,v1 <- do_deref_loc w ty1 m b ofs;
let r' := Eassign (Eloc b ofs ty1)
(Ebinop op (Eval v1 ty1) (Eval v2 ty2) tyres) ty1 in
topred (Rred "red_assignop" r' m t)
| _, _ =>
incontext2 (fun x => Eassignop op x r2 tyres ty) (step_expr LV l1 m)
(fun x => Eassignop op l1 x tyres ty) (step_expr RV r2 m)
end
| RV, Epostincr id l ty =>
match is_loc l with
| Some(b, ofs, ty1) =>
check type_eq ty1 ty;
do w',t, v1 <- do_deref_loc w ty m b ofs;
let op := match id with Incr => Oadd | Decr => Osub end in
let r' :=
Ecomma (Eassign (Eloc b ofs ty)
(Ebinop op (Eval v1 ty) (Eval (Vint Int.one) type_int32s) (incrdecr_type ty))
ty)
(Eval v1 ty) ty in
topred (Rred "red_postincr" r' m t)
| None =>
incontext (fun x => Epostincr id x ty) (step_expr LV l m)
end
| RV, Ecomma r1 r2 ty =>
match is_val r1 with
| Some _ =>
check type_eq (typeof r2) ty;
topred (Rred "red_comma" r2 m E0)
| None =>
incontext (fun x => Ecomma x r2 ty) (step_expr RV r1 m)
end
| RV, Eparen r1 tycast ty =>
match is_val r1 with
| Some (v1, ty1) =>
do v <- sem_cast v1 ty1 tycast m;
topred (Rred "red_paren" (Eval v ty) m E0)
| None =>
incontext (fun x => Eparen x tycast ty) (step_expr RV r1 m)
end
| RV, Ecall r1 rargs ty =>
match is_val r1, is_val_list rargs with
| Some(vf, tyf), Some vtl =>
match classify_fun tyf with
| fun_case_f tyargs tyres cconv =>
do fd <- Genv.find_funct ge vf;
do vargs <- sem_cast_arguments vtl tyargs m;
check type_eq (type_of_fundef fd) (Tfunction tyargs tyres cconv);
topred (Callred "red_call" fd vargs ty m)
| _ => stuck
end
| _, _ =>
incontext2 (fun x => Ecall x rargs ty) (step_expr RV r1 m)
(fun x => Ecall r1 x ty) (step_exprlist rargs m)
end
| RV, Ebuiltin ef tyargs rargs ty =>
match is_val_list rargs with
| Some vtl =>
do vargs <- sem_cast_arguments vtl tyargs m;
match do_external ef w vargs m with
| None => stuck
| Some(w',t,v,m') => topred (Rred "red_builtin" (Eval v ty) m' t)
end
| _ =>
incontext (fun x => Ebuiltin ef tyargs x ty) (step_exprlist rargs m)
end
| _, _ => stuck
end
with step_exprlist (rl: exprlist) (m: mem): reducts exprlist :=
match rl with
| Enil =>
nil
| Econs r1 rs =>
incontext2 (fun x => Econs x rs) (step_expr RV r1 m)
(fun x => Econs r1 x) (step_exprlist rs m)
end.
(** Technical properties on safe expressions. *)
Inductive imm_safe_t: kind -> expr -> mem -> Prop :=
| imm_safe_t_val: forall v ty m,
imm_safe_t RV (Eval v ty) m
| imm_safe_t_loc: forall b ofs ty m,
imm_safe_t LV (Eloc b ofs ty) m
| imm_safe_t_lred: forall to C l m l' m',
lred ge e l m l' m' ->
context LV to C ->
imm_safe_t to (C l) m
| imm_safe_t_rred: forall to C r m t r' m' w',
rred ge r m t r' m' -> possible_trace w t w' ->
context RV to C ->
imm_safe_t to (C r) m
| imm_safe_t_callred: forall to C r m fd args ty,
callred ge r m fd args ty ->
context RV to C ->
imm_safe_t to (C r) m.
Remark imm_safe_t_imm_safe:
forall k a m, imm_safe_t k a m -> imm_safe ge e k a m.
Proof.
induction 1.
constructor.
constructor.
eapply imm_safe_lred; eauto.
eapply imm_safe_rred; eauto.
eapply imm_safe_callred; eauto.
Qed.
Fixpoint exprlist_all_values (rl: exprlist) : Prop :=
match rl with
| Enil => True
| Econs (Eval v ty) rl' => exprlist_all_values rl'
| Econs _ _ => False
end.
Definition invert_expr_prop (a: expr) (m: mem) : Prop :=
match a with
| Eloc b ofs ty => False
| Evar x ty =>
exists b,
e!x = Some(b, ty)
\/ (e!x = None /\ Genv.find_symbol ge x = Some b)
| Ederef (Eval v ty1) ty =>
exists b, exists ofs, v = Vptr b ofs
| Efield (Eval v ty1) f ty =>
exists b, exists ofs, v = Vptr b ofs /\
match ty1 with
| Tstruct id _ => exists co delta, ge.(genv_cenv)!id = Some co /\ field_offset ge f (co_members co) = OK delta
| Tunion id _ => exists co, ge.(genv_cenv)!id = Some co
| _ => False
end
| Eval v ty => False
| Evalof (Eloc b ofs ty') ty =>
ty' = ty /\ exists t, exists v, exists w', deref_loc ge ty m b ofs t v /\ possible_trace w t w'
| Eunop op (Eval v1 ty1) ty =>
exists v, sem_unary_operation op v1 ty1 m = Some v
| Ebinop op (Eval v1 ty1) (Eval v2 ty2) ty =>
exists v, sem_binary_operation ge op v1 ty1 v2 ty2 m = Some v
| Ecast (Eval v1 ty1) ty =>
exists v, sem_cast v1 ty1 ty m = Some v
| Eseqand (Eval v1 ty1) r2 ty =>
exists b, bool_val v1 ty1 m = Some b
| Eseqor (Eval v1 ty1) r2 ty =>
exists b, bool_val v1 ty1 m = Some b
| Econdition (Eval v1 ty1) r1 r2 ty =>
exists b, bool_val v1 ty1 m = Some b
| Eassign (Eloc b ofs ty1) (Eval v2 ty2) ty =>
exists v, exists m', exists t, exists w',
ty = ty1 /\ sem_cast v2 ty2 ty1 m = Some v /\ assign_loc ge ty1 m b ofs v t m' /\ possible_trace w t w'
| Eassignop op (Eloc b ofs ty1) (Eval v2 ty2) tyres ty =>
exists t, exists v1, exists w',
ty = ty1 /\ deref_loc ge ty1 m b ofs t v1 /\ possible_trace w t w'
| Epostincr id (Eloc b ofs ty1) ty =>
exists t, exists v1, exists w',
ty = ty1 /\ deref_loc ge ty m b ofs t v1 /\ possible_trace w t w'
| Ecomma (Eval v ty1) r2 ty =>
typeof r2 = ty
| Eparen (Eval v1 ty1) tycast ty =>
exists v, sem_cast v1 ty1 tycast m = Some v
| Ecall (Eval vf tyf) rargs ty =>
exprlist_all_values rargs ->
exists tyargs tyres cconv fd vl,
classify_fun tyf = fun_case_f tyargs tyres cconv
/\ Genv.find_funct ge vf = Some fd
/\ cast_arguments m rargs tyargs vl
/\ type_of_fundef fd = Tfunction tyargs tyres cconv
| Ebuiltin ef tyargs rargs ty =>
exprlist_all_values rargs ->
exists vargs t vres m' w',
cast_arguments m rargs tyargs vargs
/\ external_call ef ge vargs m t vres m'
/\ possible_trace w t w'
| _ => True
end.
Lemma lred_invert:
forall l m l' m', lred ge e l m l' m' -> invert_expr_prop l m.
Proof.
induction 1; red; auto.
exists b; auto.
exists b; auto.
exists b; exists ofs; auto.
exists b; exists ofs; split; auto. exists co, delta; auto.
exists b; exists ofs; split; auto. exists co; auto.
Qed.
Lemma rred_invert:
forall w' r m t r' m', rred ge r m t r' m' -> possible_trace w t w' -> invert_expr_prop r m.
Proof.
induction 1; intros; red; auto.
split; auto; exists t; exists v; exists w'; auto.
exists v; auto.
exists v; auto.
exists v; auto.
exists true; auto. exists false; auto.
exists true; auto. exists false; auto.
exists b; auto.
exists v; exists m'; exists t; exists w'; auto.
exists t; exists v1; exists w'; auto.
exists t; exists v1; exists w'; auto.
exists v; auto.
intros; exists vargs; exists t; exists vres; exists m'; exists w'; auto.
Qed.
Lemma callred_invert:
forall r fd args ty m,
callred ge r m fd args ty ->
invert_expr_prop r m.
Proof.
intros. inv H. simpl.
intros. exists tyargs, tyres, cconv, fd, args; auto.
Qed.
Scheme context_ind2 := Minimality for context Sort Prop
with contextlist_ind2 := Minimality for contextlist Sort Prop.
Combined Scheme context_contextlist_ind from context_ind2, contextlist_ind2.
Lemma invert_expr_context:
(forall from to C, context from to C ->
forall a m,
invert_expr_prop a m ->
invert_expr_prop (C a) m)
/\(forall from C, contextlist from C ->
forall a m,
invert_expr_prop a m ->
~exprlist_all_values (C a)).
Proof.
apply context_contextlist_ind; intros; try (exploit H0; [eauto|intros]); simpl.
auto.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
auto.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct e1; auto; destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct e1; auto; destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct e1; auto; destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct e1; auto. intros. elim (H0 a m); auto.
intros. elim (H0 a m); auto.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
red; intros. destruct (C a); auto.
red; intros. destruct e1; auto. elim (H0 a m); auto.
Qed.
Lemma imm_safe_t_inv:
forall k a m,
imm_safe_t k a m ->
match a with
| Eloc _ _ _ => True
| Eval _ _ => True
| _ => invert_expr_prop a m
end.
Proof.
destruct invert_expr_context as [A B].
intros. inv H.
auto.
auto.
assert (invert_expr_prop (C l) m).
eapply A; eauto. eapply lred_invert; eauto.
red in H. destruct (C l); auto; contradiction.
assert (invert_expr_prop (C r) m).
eapply A; eauto. eapply rred_invert; eauto.
red in H. destruct (C r); auto; contradiction.
assert (invert_expr_prop (C r) m).
eapply A; eauto. eapply callred_invert; eauto.
red in H. destruct (C r); auto; contradiction.
Qed.
(** Soundness: if [step_expr] returns [Some ll], then every element
of [ll] is a reduct. *)
Lemma context_compose:
forall k2 k3 C2, context k2 k3 C2 ->
forall k1 C1, context k1 k2 C1 ->
context k1 k3 (fun x => C2(C1 x))
with contextlist_compose:
forall k2 C2, contextlist k2 C2 ->
forall k1 C1, context k1 k2 C1 ->
contextlist k1 (fun x => C2(C1 x)).
Proof.
induction 1; intros; try (constructor; eauto).
replace (fun x => C1 x) with C1. auto. apply extensionality; auto.
induction 1; intros; constructor; eauto.
Qed.
Local Hint Constructors context contextlist : core.
Local Hint Resolve context_compose contextlist_compose : core.
Definition reduction_ok (k: kind) (a: expr) (m: mem) (rd: reduction) : Prop :=
match k, rd with
| LV, Lred _ l' m' => lred ge e a m l' m'
| RV, Rred _ r' m' t => rred ge a m t r' m' /\ exists w', possible_trace w t w'
| RV, Callred _ fd args tyres m' => callred ge a m fd args tyres /\ m' = m
| LV, Stuckred => ~imm_safe_t k a m
| RV, Stuckred => ~imm_safe_t k a m
| _, _ => False
end.
Definition reducts_ok (k: kind) (a: expr) (m: mem) (ll: reducts expr) : Prop :=
(forall C rd,
In (C, rd) ll ->
exists a', exists k', context k' k C /\ a = C a' /\ reduction_ok k' a' m rd)
/\ (ll = nil -> match k with LV => is_loc a <> None | RV => is_val a <> None end).
Definition list_reducts_ok (al: exprlist) (m: mem) (ll: reducts exprlist) : Prop :=
(forall C rd,
In (C, rd) ll ->
exists a', exists k', contextlist k' C /\ al = C a' /\ reduction_ok k' a' m rd)
/\ (ll = nil -> is_val_list al <> None).
Ltac monadInv :=
match goal with
| [ H: match ?x with Some _ => _ | None => None end = Some ?y |- _ ] =>
destruct x eqn:?; [monadInv|discriminate]
| [ H: match ?x with left _ => _ | right _ => None end = Some ?y |- _ ] =>
destruct x; [monadInv|discriminate]
| _ => idtac
end.
Lemma sem_cast_arguments_sound:
forall m rargs vtl tyargs vargs,
is_val_list rargs = Some vtl ->
sem_cast_arguments vtl tyargs m = Some vargs ->
cast_arguments m rargs tyargs vargs.
Proof.
induction rargs; simpl; intros.
inv H. destruct tyargs; simpl in H0; inv H0. constructor.
monadInv. inv H. simpl in H0. destruct p as [v1 t1]. destruct tyargs; try congruence. monadInv.
inv H0. rewrite (is_val_inv _ _ _ Heqo). constructor. auto. eauto.
Qed.
Lemma sem_cast_arguments_complete:
forall m al tyl vl,
cast_arguments m al tyl vl ->
exists vtl, is_val_list al = Some vtl /\ sem_cast_arguments vtl tyl m = Some vl.
Proof.
induction 1.
exists (@nil (val * type)); auto.
destruct IHcast_arguments as [vtl [A B]].
exists ((v, ty) :: vtl); simpl. rewrite A; rewrite B; rewrite H. auto.
Qed.
Lemma topred_ok:
forall k a m rd,
reduction_ok k a m rd ->
reducts_ok k a m (topred rd).
Proof.
intros. unfold topred; split; simpl; intros.
destruct H0; try contradiction. inv H0. exists a; exists k; auto.
congruence.
Qed.
Lemma stuck_ok:
forall k a m,
~imm_safe_t k a m ->
reducts_ok k a m stuck.
Proof.
intros. unfold stuck; split; simpl; intros.
destruct H0; try contradiction. inv H0. exists a; exists k; intuition. red. destruct k; auto.
congruence.
Qed.
Lemma wrong_kind_ok:
forall k a m,
k <> Cstrategy.expr_kind a ->
reducts_ok k a m stuck.
Proof.
intros. apply stuck_ok. red; intros. exploit Cstrategy.imm_safe_kind; eauto.
eapply imm_safe_t_imm_safe; eauto.
Qed.
Lemma not_invert_ok:
forall k a m,
match a with
| Eloc _ _ _ => False
| Eval _ _ => False
| _ => invert_expr_prop a m -> False
end ->
reducts_ok k a m stuck.
Proof.
intros. apply stuck_ok. red; intros.
exploit imm_safe_t_inv; eauto. destruct a; auto.
Qed.
Lemma incontext_ok:
forall k a m C res k' a',
reducts_ok k' a' m res ->
a = C a' ->
context k' k C ->
match k' with LV => is_loc a' = None | RV => is_val a' = None end ->
reducts_ok k a m (incontext C res).
Proof.
unfold reducts_ok, incontext; intros. destruct H. split; intros.
exploit list_in_map_inv; eauto. intros [[C1 rd1] [P Q]]. inv P.
exploit H; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eapply context_compose; eauto. rewrite V; auto.
destruct res; simpl in H4; try congruence. destruct k'; intuition congruence.
Qed.
Lemma incontext2_ok:
forall k a m k1 a1 res1 k2 a2 res2 C1 C2,
reducts_ok k1 a1 m res1 ->
reducts_ok k2 a2 m res2 ->
a = C1 a1 -> a = C2 a2 ->
context k1 k C1 -> context k2 k C2 ->
match k1 with LV => is_loc a1 = None | RV => is_val a1 = None end
\/ match k2 with LV => is_loc a2 = None | RV => is_val a2 = None end ->
reducts_ok k a m (incontext2 C1 res1 C2 res2).
Proof.
unfold reducts_ok, incontext2, incontext; intros. destruct H; destruct H0; split; intros.
destruct (in_app_or _ _ _ H8).
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eapply context_compose; eauto. rewrite V; auto.
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H0; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eapply context_compose; eauto. rewrite H2; rewrite V; auto.
destruct res1; simpl in H8; try congruence. destruct res2; simpl in H8; try congruence.
destruct H5. destruct k1; intuition congruence. destruct k2; intuition congruence.
Qed.
Lemma incontext_list_ok:
forall ef tyargs al ty m res,
list_reducts_ok al m res ->
is_val_list al = None ->
reducts_ok RV (Ebuiltin ef tyargs al ty) m
(incontext (fun x => Ebuiltin ef tyargs x ty) res).
Proof.
unfold reducts_ok, incontext; intros. destruct H. split; intros.
exploit list_in_map_inv; eauto. intros [[C1 rd1] [P Q]]. inv P.
exploit H; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eauto. rewrite V; auto.
destruct res; simpl in H2. elim H1; auto. congruence.
Qed.
Lemma incontext2_list_ok:
forall a1 a2 ty m res1 res2,
reducts_ok RV a1 m res1 ->
list_reducts_ok a2 m res2 ->
is_val a1 = None \/ is_val_list a2 = None ->
reducts_ok RV (Ecall a1 a2 ty) m
(incontext2 (fun x => Ecall x a2 ty) res1
(fun x => Ecall a1 x ty) res2).
Proof.
unfold reducts_ok, incontext2, incontext; intros. destruct H; destruct H0; split; intros.
destruct (in_app_or _ _ _ H4).
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eauto. rewrite V; auto.
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H0; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eauto. rewrite V; auto.
destruct res1; simpl in H4; try congruence. destruct res2; simpl in H4; try congruence.
tauto.
Qed.
Lemma incontext2_list_ok':
forall a1 a2 m res1 res2,
reducts_ok RV a1 m res1 ->
list_reducts_ok a2 m res2 ->
list_reducts_ok (Econs a1 a2) m
(incontext2 (fun x => Econs x a2) res1
(fun x => Econs a1 x) res2).
Proof.
unfold reducts_ok, list_reducts_ok, incontext2, incontext; intros.
destruct H; destruct H0. split; intros.
destruct (in_app_or _ _ _ H3).
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eauto. rewrite V; auto.
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H0; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eauto. rewrite V; auto.
destruct res1; simpl in H3; try congruence. destruct res2; simpl in H3; try congruence.
simpl. destruct (is_val a1). destruct (is_val_list a2). congruence. intuition congruence. intuition congruence.
Qed.
Lemma is_val_list_all_values:
forall al vtl, is_val_list al = Some vtl -> exprlist_all_values al.
Proof.
induction al; simpl; intros. auto.
destruct (is_val r1) as [[v ty]|] eqn:?; try discriminate.
destruct (is_val_list al) as [vtl'|] eqn:?; try discriminate.
rewrite (is_val_inv _ _ _ Heqo). eauto.
Qed.
Ltac myinv :=
match goal with
| [ H: False |- _ ] => destruct H
| [ H: _ /\ _ |- _ ] => destruct H; myinv
| [ H: exists _, _ |- _ ] => destruct H; myinv
| _ => idtac
end.
Theorem step_expr_sound:
forall a k m, reducts_ok k a m (step_expr k a m)
with step_exprlist_sound:
forall al m, list_reducts_ok al m (step_exprlist al m).
Proof with (try (apply not_invert_ok; simpl; intro; myinv; intuition congruence; fail)).
induction a; intros; simpl; destruct k; try (apply wrong_kind_ok; simpl; congruence).
(* Eval *)
split; intros. tauto. simpl; congruence.
(* Evar *)
destruct (e!x) as [[b ty']|] eqn:?.
destruct (type_eq ty ty')...
subst. apply topred_ok; auto. apply red_var_local; auto.
destruct (Genv.find_symbol ge x) as [b|] eqn:?...
apply topred_ok; auto. apply red_var_global; auto.
(* Efield *)
destruct (is_val a) as [[v ty'] | ] eqn:?.
rewrite (is_val_inv _ _ _ Heqo).
destruct v...
destruct ty'...
(* top struct *)
destruct (ge.(genv_cenv)!i0) as [co|] eqn:?...
destruct (field_offset ge f (co_members co)) as [delta|] eqn:?...
apply topred_ok; auto. eapply red_field_struct; eauto.
(* top union *)
destruct (ge.(genv_cenv)!i0) as [co|] eqn:?...
apply topred_ok; auto. eapply red_field_union; eauto.
(* in depth *)
eapply incontext_ok; eauto.
(* Evalof *)
destruct (is_loc a) as [[[b ofs] ty'] | ] eqn:?. rewrite (is_loc_inv _ _ _ _ Heqo).
(* top *)
destruct (type_eq ty ty')... subst ty'.
destruct (do_deref_loc w ty m b ofs) as [[[w' t] v] | ] eqn:?.
exploit do_deref_loc_sound; eauto. intros [A B].
apply topred_ok; auto. red. split. apply red_rvalof; auto. exists w'; auto.
apply not_invert_ok; simpl; intros; myinv. exploit do_deref_loc_complete; eauto. congruence.
(* depth *)
eapply incontext_ok; eauto.
(* Ederef *)
destruct (is_val a) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct v... apply topred_ok; auto. apply red_deref; auto.
(* depth *)
eapply incontext_ok; eauto.
(* Eaddrof *)
destruct (is_loc a) as [[[b ofs] ty'] | ] eqn:?. rewrite (is_loc_inv _ _ _ _ Heqo).
(* top *)
apply topred_ok; auto. split. apply red_addrof; auto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* unop *)
destruct (is_val a) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (sem_unary_operation op v ty' m) as [v'|] eqn:?...
apply topred_ok; auto. split. apply red_unop; auto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* binop *)
destruct (is_val a1) as [[v1 ty1] | ] eqn:?.
destruct (is_val a2) as [[v2 ty2] | ] eqn:?.
rewrite (is_val_inv _ _ _ Heqo). rewrite (is_val_inv _ _ _ Heqo0).
(* top *)
destruct (sem_binary_operation ge op v1 ty1 v2 ty2 m) as [v|] eqn:?...
apply topred_ok; auto. split. apply red_binop; auto. exists w; constructor.
(* depth *)
eapply incontext2_ok; eauto.
eapply incontext2_ok; eauto.
(* cast *)
destruct (is_val a) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (sem_cast v ty' ty m) as [v'|] eqn:?...
apply topred_ok; auto. split. apply red_cast; auto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* seqand *)
destruct (is_val a1) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (bool_val v ty' m) as [v'|] eqn:?... destruct v'.
apply topred_ok; auto. split. eapply red_seqand_true; eauto. exists w; constructor.
apply topred_ok; auto. split. eapply red_seqand_false; eauto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* seqor *)
destruct (is_val a1) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (bool_val v ty' m) as [v'|] eqn:?... destruct v'.
apply topred_ok; auto. split. eapply red_seqor_true; eauto. exists w; constructor.
apply topred_ok; auto. split. eapply red_seqor_false; eauto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* condition *)
destruct (is_val a1) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (bool_val v ty' m) as [v'|] eqn:?...
apply topred_ok; auto. split. eapply red_condition; eauto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* sizeof *)
apply topred_ok; auto. split. apply red_sizeof. exists w; constructor.
(* alignof *)
apply topred_ok; auto. split. apply red_alignof. exists w; constructor.
(* assign *)
destruct (is_loc a1) as [[[b ofs] ty1] | ] eqn:?.
destruct (is_val a2) as [[v2 ty2] | ] eqn:?.
rewrite (is_loc_inv _ _ _ _ Heqo). rewrite (is_val_inv _ _ _ Heqo0).
(* top *)
destruct (type_eq ty1 ty)... subst ty1.
destruct (sem_cast v2 ty2 ty m) as [v|] eqn:?...
destruct (do_assign_loc w ty m b ofs v) as [[[w' t] m']|] eqn:?.
exploit do_assign_loc_sound; eauto. intros [P Q].
apply topred_ok; auto. split. apply red_assign; auto. exists w'; auto.
apply not_invert_ok; simpl; intros; myinv. exploit do_assign_loc_complete; eauto. congruence.
(* depth *)
eapply incontext2_ok; eauto.
eapply incontext2_ok; eauto.
(* assignop *)
destruct (is_loc a1) as [[[b ofs] ty1] | ] eqn:?.
destruct (is_val a2) as [[v2 ty2] | ] eqn:?.
rewrite (is_loc_inv _ _ _ _ Heqo). rewrite (is_val_inv _ _ _ Heqo0).
(* top *)
destruct (type_eq ty1 ty)... subst ty1.
destruct (do_deref_loc w ty m b ofs) as [[[w' t] v] | ] eqn:?.
exploit do_deref_loc_sound; eauto. intros [A B].
apply topred_ok; auto. red. split. apply red_assignop; auto. exists w'; auto.
apply not_invert_ok; simpl; intros; myinv. exploit do_deref_loc_complete; eauto. congruence.
(* depth *)
eapply incontext2_ok; eauto.
eapply incontext2_ok; eauto.
(* postincr *)
destruct (is_loc a) as [[[b ofs] ty'] | ] eqn:?. rewrite (is_loc_inv _ _ _ _ Heqo).
(* top *)
destruct (type_eq ty' ty)... subst ty'.
destruct (do_deref_loc w ty m b ofs) as [[[w' t] v] | ] eqn:?.
exploit do_deref_loc_sound; eauto. intros [A B].
apply topred_ok; auto. red. split. apply red_postincr; auto. exists w'; auto.
apply not_invert_ok; simpl; intros; myinv. exploit do_deref_loc_complete; eauto. congruence.
(* depth *)
eapply incontext_ok; eauto.
(* comma *)
destruct (is_val a1) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (type_eq (typeof a2) ty)... subst ty.
apply topred_ok; auto. split. apply red_comma; auto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* call *)
destruct (is_val a) as [[vf tyf] | ] eqn:?.
destruct (is_val_list rargs) as [vtl | ] eqn:?.
rewrite (is_val_inv _ _ _ Heqo). exploit is_val_list_all_values; eauto. intros ALLVAL.
(* top *)
destruct (classify_fun tyf) as [tyargs tyres cconv|] eqn:?...
destruct (Genv.find_funct ge vf) as [fd|] eqn:?...
destruct (sem_cast_arguments vtl tyargs m) as [vargs|] eqn:?...
destruct (type_eq (type_of_fundef fd) (Tfunction tyargs tyres cconv))...
apply topred_ok; auto. red. split; auto. eapply red_call; eauto.
eapply sem_cast_arguments_sound; eauto.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv. congruence.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv.
exploit sem_cast_arguments_complete; eauto. intros [vtl' [P Q]]. congruence.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv. congruence.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv. congruence.
(* depth *)
eapply incontext2_list_ok; eauto.
eapply incontext2_list_ok; eauto.
(* builtin *)
destruct (is_val_list rargs) as [vtl | ] eqn:?.
exploit is_val_list_all_values; eauto. intros ALLVAL.
(* top *)
destruct (sem_cast_arguments vtl tyargs m) as [vargs|] eqn:?...
destruct (do_external ef w vargs m) as [[[[? ?] v] m'] | ] eqn:?...
exploit do_ef_external_sound; eauto. intros [EC PT].
apply topred_ok; auto. red. split; auto. eapply red_builtin; eauto.
eapply sem_cast_arguments_sound; eauto.
exists w0; auto.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv.
assert (x = vargs).
exploit sem_cast_arguments_complete; eauto. intros [vtl' [A B]]. congruence.
subst x. exploit do_ef_external_complete; eauto. congruence.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv.
exploit sem_cast_arguments_complete; eauto. intros [vtl' [A B]]. congruence.
(* depth *)
eapply incontext_list_ok; eauto.
(* loc *)
split; intros. tauto. simpl; congruence.
(* paren *)
destruct (is_val a) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (sem_cast v ty' tycast m) as [v'|] eqn:?...
apply topred_ok; auto. split. apply red_paren; auto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
induction al; simpl; intros.
(* nil *)
split; intros. tauto. simpl; congruence.
(* cons *)
eapply incontext2_list_ok'; eauto.
Qed.
Lemma step_exprlist_val_list:
forall m al, is_val_list al <> None -> step_exprlist al m = nil.
Proof.
induction al; simpl; intros.
auto.
destruct (is_val r1) as [[v1 ty1]|] eqn:?; try congruence.
destruct (is_val_list al) eqn:?; try congruence.
rewrite (is_val_inv _ _ _ Heqo).
rewrite IHal. auto. congruence.
Qed.
(** Completeness part 1: [step_expr] contains all possible non-error reducts. *)
Lemma lred_topred:
forall l1 m1 l2 m2,
lred ge e l1 m1 l2 m2 ->
exists rule, step_expr LV l1 m1 = topred (Lred rule l2 m2).
Proof.
induction 1; simpl.
(* var local *)
rewrite H. rewrite dec_eq_true. econstructor; eauto.
(* var global *)
rewrite H; rewrite H0. econstructor; eauto.
(* deref *)
econstructor; eauto.
(* field struct *)
rewrite H, H0; econstructor; eauto.
(* field union *)
rewrite H; econstructor; eauto.
Qed.
Lemma rred_topred:
forall w' r1 m1 t r2 m2,
rred ge r1 m1 t r2 m2 -> possible_trace w t w' ->
exists rule, step_expr RV r1 m1 = topred (Rred rule r2 m2 t).
Proof.
induction 1; simpl; intros.
(* valof *)
rewrite dec_eq_true.
rewrite (do_deref_loc_complete _ _ _ _ _ _ _ _ H H0). econstructor; eauto.
(* addrof *)
inv H. econstructor; eauto.
(* unop *)
inv H0. rewrite H; econstructor; eauto.
(* binop *)
inv H0. rewrite H; econstructor; eauto.
(* cast *)
inv H0. rewrite H; econstructor; eauto.
(* seqand *)
inv H0. rewrite H; econstructor; eauto.
inv H0. rewrite H; econstructor; eauto.
(* seqor *)
inv H0. rewrite H; econstructor; eauto.
inv H0. rewrite H; econstructor; eauto.
(* condition *)
inv H0. rewrite H; econstructor; eauto.
(* sizeof *)
inv H. econstructor; eauto.
(* alignof *)
inv H. econstructor; eauto.
(* assign *)
rewrite dec_eq_true. rewrite H. rewrite (do_assign_loc_complete _ _ _ _ _ _ _ _ _ H0 H1).
econstructor; eauto.
(* assignop *)
rewrite dec_eq_true. rewrite (do_deref_loc_complete _ _ _ _ _ _ _ _ H H0).
econstructor; eauto.
(* postincr *)
rewrite dec_eq_true. subst. rewrite (do_deref_loc_complete _ _ _ _ _ _ _ _ H H1).
econstructor; eauto.
(* comma *)
inv H0. rewrite dec_eq_true. econstructor; eauto.
(* paren *)
inv H0. rewrite H; econstructor; eauto.
(* builtin *)
exploit sem_cast_arguments_complete; eauto. intros [vtl [A B]].
exploit do_ef_external_complete; eauto. intros C.
rewrite A. rewrite B. rewrite C. econstructor; eauto.
Qed.
Lemma callred_topred:
forall a fd args ty m,
callred ge a m fd args ty ->
exists rule, step_expr RV a m = topred (Callred rule fd args ty m).
Proof.
induction 1; simpl.
rewrite H2. exploit sem_cast_arguments_complete; eauto. intros [vtl [A B]].
rewrite A; rewrite H; rewrite B; rewrite H1; rewrite dec_eq_true. econstructor; eauto.
Qed.
Definition reducts_incl {A B: Type} (C: A -> B) (res1: reducts A) (res2: reducts B) : Prop :=
forall C1 rd, In (C1, rd) res1 -> In ((fun x => C(C1 x)), rd) res2.
Lemma reducts_incl_trans:
forall (A1 A2: Type) (C: A1 -> A2) res1 res2, reducts_incl C res1 res2 ->
forall (A3: Type) (C': A2 -> A3) res3,
reducts_incl C' res2 res3 ->
reducts_incl (fun x => C'(C x)) res1 res3.
Proof.
unfold reducts_incl; intros. auto.
Qed.
Lemma reducts_incl_nil:
forall (A B: Type) (C: A -> B) res,
reducts_incl C nil res.
Proof.
intros; red. intros; contradiction.
Qed.
Lemma reducts_incl_val:
forall (A: Type) a m v ty (C: expr -> A) res,
is_val a = Some(v, ty) -> reducts_incl C (step_expr RV a m) res.
Proof.
intros. rewrite (is_val_inv _ _ _ H). apply reducts_incl_nil.
Qed.
Lemma reducts_incl_loc:
forall (A: Type) a m b ofs ty (C: expr -> A) res,
is_loc a = Some(b, ofs, ty) -> reducts_incl C (step_expr LV a m) res.
Proof.
intros. rewrite (is_loc_inv _ _ _ _ H). apply reducts_incl_nil.
Qed.
Lemma reducts_incl_listval:
forall (A: Type) a m vtl (C: exprlist -> A) res,
is_val_list a = Some vtl -> reducts_incl C (step_exprlist a m) res.
Proof.
intros. rewrite step_exprlist_val_list. apply reducts_incl_nil. congruence.
Qed.
Lemma reducts_incl_incontext:
forall (A B: Type) (C: A -> B) res,
reducts_incl C res (incontext C res).
Proof.
unfold reducts_incl, incontext. intros.
set (f := fun z : (expr -> A) * reduction => (fun x : expr => C (fst z x), snd z)).
change (In (f (C1, rd)) (map f res)). apply in_map. auto.
Qed.
Lemma reducts_incl_incontext2_left:
forall (A1 A2 B: Type) (C1: A1 -> B) res1 (C2: A2 -> B) res2,
reducts_incl C1 res1 (incontext2 C1 res1 C2 res2).
Proof.
unfold reducts_incl, incontext2, incontext. intros.
rewrite in_app_iff. left.
set (f := fun z : (expr -> A1) * reduction => (fun x : expr => C1 (fst z x), snd z)).
change (In (f (C0, rd)) (map f res1)). apply in_map; auto.
Qed.
Lemma reducts_incl_incontext2_right:
forall (A1 A2 B: Type) (C1: A1 -> B) res1 (C2: A2 -> B) res2,
reducts_incl C2 res2 (incontext2 C1 res1 C2 res2).
Proof.
unfold reducts_incl, incontext2, incontext. intros.
rewrite in_app_iff. right.
set (f := fun z : (expr -> A2) * reduction => (fun x : expr => C2 (fst z x), snd z)).
change (In (f (C0, rd)) (map f res2)). apply in_map; auto.
Qed.
Local Hint Resolve reducts_incl_val reducts_incl_loc reducts_incl_listval
reducts_incl_incontext reducts_incl_incontext2_left
reducts_incl_incontext2_right : core.
Lemma step_expr_context:
forall from to C, context from to C ->
forall a m, reducts_incl C (step_expr from a m) (step_expr to (C a) m)
with step_exprlist_context:
forall from C, contextlist from C ->
forall a m, reducts_incl C (step_expr from a m) (step_exprlist (C a) m).
Proof.
induction 1; simpl; intros.
(* top *)
red. destruct (step_expr k a m); auto.
try (* no eta in 8.3 *)
(intros;
replace (fun x => C1 x) with C1 by (apply extensionality; auto);
auto).
(* deref *)
eapply reducts_incl_trans with (C' := fun x => Ederef x ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* field *)
eapply reducts_incl_trans with (C' := fun x => Efield x f ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* valof *)
eapply reducts_incl_trans with (C' := fun x => Evalof x ty); eauto.
destruct (is_loc (C a)) as [[[b ofs] ty']|] eqn:?; eauto.
(* addrof *)
eapply reducts_incl_trans with (C' := fun x => Eaddrof x ty); eauto.
destruct (is_loc (C a)) as [[[b ofs] ty']|] eqn:?; eauto.
(* unop *)
eapply reducts_incl_trans with (C' := fun x => Eunop op x ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* binop left *)
eapply reducts_incl_trans with (C' := fun x => Ebinop op x e2 ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* binop right *)
eapply reducts_incl_trans with (C' := fun x => Ebinop op e1 x ty); eauto.
destruct (is_val e1) as [[v1 ty1]|] eqn:?; eauto.
destruct (is_val (C a)) as [[v2 ty2]|] eqn:?; eauto.
(* cast *)
eapply reducts_incl_trans with (C' := fun x => Ecast x ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* seqand *)
eapply reducts_incl_trans with (C' := fun x => Eseqand x r2 ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* seqor *)
eapply reducts_incl_trans with (C' := fun x => Eseqor x r2 ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* condition *)
eapply reducts_incl_trans with (C' := fun x => Econdition x r2 r3 ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* assign left *)
eapply reducts_incl_trans with (C' := fun x => Eassign x e2 ty); eauto.
destruct (is_loc (C a)) as [[[b ofs] ty']|] eqn:?; eauto.
(* assign right *)
eapply reducts_incl_trans with (C' := fun x => Eassign e1 x ty); eauto.
destruct (is_loc e1) as [[[b ofs] ty1]|] eqn:?; eauto.
destruct (is_val (C a)) as [[v2 ty2]|] eqn:?; eauto.
(* assignop left *)
eapply reducts_incl_trans with (C' := fun x => Eassignop op x e2 tyres ty); eauto.
destruct (is_loc (C a)) as [[[b ofs] ty']|] eqn:?; eauto.
(* assignop right *)
eapply reducts_incl_trans with (C' := fun x => Eassignop op e1 x tyres ty); eauto.
destruct (is_loc e1) as [[[b ofs] ty1]|] eqn:?; eauto.
destruct (is_val (C a)) as [[v2 ty2]|] eqn:?; eauto.
(* postincr *)
eapply reducts_incl_trans with (C' := fun x => Epostincr id x ty); eauto.
destruct (is_loc (C a)) as [[[b ofs] ty']|] eqn:?; eauto.
(* call left *)
eapply reducts_incl_trans with (C' := fun x => Ecall x el ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* call right *)
eapply reducts_incl_trans with (C' := fun x => Ecall e1 x ty). apply step_exprlist_context. auto.
destruct (is_val e1) as [[v1 ty1]|] eqn:?; eauto.
destruct (is_val_list (C a)) as [vl|] eqn:?; eauto.
(* builtin *)
eapply reducts_incl_trans with (C' := fun x => Ebuiltin ef tyargs x ty). apply step_exprlist_context. auto.
destruct (is_val_list (C a)) as [vl|] eqn:?; eauto.
(* comma *)
eapply reducts_incl_trans with (C' := fun x => Ecomma x e2 ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* paren *)
eapply reducts_incl_trans with (C' := fun x => Eparen x tycast ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
induction 1; simpl; intros.
(* cons left *)
eapply reducts_incl_trans with (C' := fun x => Econs x el).
apply step_expr_context; eauto. eauto.
(* binop right *)
eapply reducts_incl_trans with (C' := fun x => Econs e1 x).
apply step_exprlist_context; eauto. eauto.
Qed.
(** Completeness part 2: if we can reduce to [Stuckstate], [step_expr]
contains at least one [Stuckred] reduction. *)
Lemma not_stuckred_imm_safe:
forall m a k,
(forall C, ~In (C, Stuckred) (step_expr k a m)) -> imm_safe_t k a m.
Proof.
intros. generalize (step_expr_sound a k m). intros [A B].
destruct (step_expr k a m) as [|[C rd] res] eqn:?.
specialize (B (eq_refl _)). destruct k.
destruct a; simpl in B; try congruence. constructor.
destruct a; simpl in B; try congruence. constructor.
assert (NOTSTUCK: rd <> Stuckred).
red; intros. elim (H C); subst rd; auto with coqlib.
exploit A. eauto with coqlib. intros [a' [k' [P [Q R]]]].
destruct k'; destruct rd; simpl in R; intuition.
subst a. eapply imm_safe_t_lred; eauto.
subst a. destruct H1 as [w' PT]. eapply imm_safe_t_rred; eauto.
subst. eapply imm_safe_t_callred; eauto.
Qed.
Lemma not_imm_safe_stuck_red:
forall m a k C,
context k RV C ->
~imm_safe_t k a m ->
exists C', In (C', Stuckred) (step_expr RV (C a) m).
Proof.
intros.
assert (exists C', In (C', Stuckred) (step_expr k a m)).
destruct (classic (exists C', In (C', Stuckred) (step_expr k a m))); auto.
elim H0. apply not_stuckred_imm_safe. apply not_ex_all_not. auto.
destruct H1 as [C' IN].
specialize (step_expr_context _ _ _ H a m). unfold reducts_incl.
intro.
exists (fun x => (C (C' x))). apply H1; auto.
Qed.
(** Connections between [imm_safe_t] and [imm_safe] *)
Lemma imm_safe_imm_safe_t:
forall k a m,
imm_safe ge e k a m ->
imm_safe_t k a m \/
exists C, exists a1, exists t, exists a1', exists m',
context RV k C /\ a = C a1 /\ rred ge a1 m t a1' m' /\ forall w', ~possible_trace w t w'.
Proof.
intros. inv H.
left. apply imm_safe_t_val.
left. apply imm_safe_t_loc.
left. eapply imm_safe_t_lred; eauto.
destruct (classic (exists w', possible_trace w t w')) as [[w' A] | A].
left. eapply imm_safe_t_rred; eauto.
right. exists C; exists e0; exists t; exists e'; exists m'; intuition. apply A; exists w'; auto.
left. eapply imm_safe_t_callred; eauto.
Qed.
(** A state can "crash the world" if it can make an observable transition
whose trace is not accepted by the external world. *)
Definition can_crash_world (w: world) (S: state) : Prop :=
exists t, exists S', Csem.step ge S t S' /\ forall w', ~possible_trace w t w'.
Theorem not_imm_safe_t:
forall K C a m f k,
context K RV C ->
~imm_safe_t K a m ->
Csem.step ge (ExprState f (C a) k e m) E0 Stuckstate \/ can_crash_world w (ExprState f (C a) k e m).
Proof.
intros. destruct (classic (imm_safe ge e K a m)).
exploit imm_safe_imm_safe_t; eauto.
intros [A | [C1 [a1 [t [a1' [m' [A [B [D E]]]]]]]]]. contradiction.
right. red. exists t; econstructor; split; auto.
left. rewrite B. eapply step_rred with (C := fun x => C(C1 x)). eauto. eauto.
left. left. eapply step_stuck; eauto.
Qed.
End EXPRS.
(** * Transitions over states. *)
Fixpoint do_alloc_variables (e: env) (m: mem) (l: list (ident * type)) {struct l} : env * mem :=
match l with
| nil => (e,m)
| (id, ty) :: l' =>
let (m1,b1) := Mem.alloc m 0 (sizeof ge ty) in
do_alloc_variables (PTree.set id (b1, ty) e) m1 l'
end.
Lemma do_alloc_variables_sound:
forall l e m, alloc_variables ge e m l (fst (do_alloc_variables e m l)) (snd (do_alloc_variables e m l)).
Proof.
induction l; intros; simpl.
constructor.
destruct a as [id ty]. destruct (Mem.alloc m 0 (sizeof ge ty)) as [m1 b1] eqn:?; simpl.
econstructor; eauto.
Qed.
Lemma do_alloc_variables_complete:
forall e1 m1 l e2 m2, alloc_variables ge e1 m1 l e2 m2 ->
do_alloc_variables e1 m1 l = (e2, m2).
Proof.
induction 1; simpl.
auto.
rewrite H; rewrite IHalloc_variables; auto.
Qed.
Function sem_bind_parameters (w: world) (e: env) (m: mem) (l: list (ident * type)) (lv: list val)
{struct l} : option mem :=
match l, lv with
| nil, nil => Some m
| (id, ty) :: params, v1::lv =>
match PTree.get id e with
| Some (b, ty') =>
check (type_eq ty ty');
do w', t, m1 <- do_assign_loc w ty m b Ptrofs.zero v1;
match t with nil => sem_bind_parameters w e m1 params lv | _ => None end
| None => None
end
| _, _ => None
end.
Lemma sem_bind_parameters_sound : forall w e m l lv m',
sem_bind_parameters w e m l lv = Some m' ->
bind_parameters ge e m l lv m'.
Proof.
intros; functional induction (sem_bind_parameters w e m l lv); try discriminate.
inversion H; constructor; auto.
exploit do_assign_loc_sound; eauto. intros [A B]. econstructor; eauto.
Qed.
Lemma sem_bind_parameters_complete : forall w e m l lv m',
bind_parameters ge e m l lv m' ->
sem_bind_parameters w e m l lv = Some m'.
Proof.
induction 1; simpl; auto.
rewrite H. rewrite dec_eq_true.
assert (possible_trace w E0 w) by constructor.
rewrite (do_assign_loc_complete _ _ _ _ _ _ _ _ _ H0 H2).
simpl. auto.
Qed.
Inductive transition : Type := TR (rule: string) (t: trace) (S': state).
Definition expr_final_state (f: function) (k: cont) (e: env) (C_rd: (expr -> expr) * reduction) :=
match snd C_rd with
| Lred rule a m => TR rule E0 (ExprState f (fst C_rd a) k e m)
| Rred rule a m t => TR rule t (ExprState f (fst C_rd a) k e m)
| Callred rule fd vargs ty m => TR rule E0 (Callstate fd vargs (Kcall f e (fst C_rd) ty k) m)
| Stuckred => TR "step_stuck" E0 Stuckstate
end.
Local Open Scope list_monad_scope.
Definition ret (rule: string) (S: state) : list transition :=
TR rule E0 S :: nil.
Definition do_step (w: world) (s: state) : list transition :=
match s with
| ExprState f a k e m =>
match is_val a with
| Some(v, ty) =>
match k with
| Kdo k => ret "step_do_2" (State f Sskip k e m )
| Kifthenelse s1 s2 k =>
do b <- bool_val v ty m;
ret "step_ifthenelse_2" (State f (if b then s1 else s2) k e m)
| Kwhile1 x s k =>
do b <- bool_val v ty m;
if b
then ret "step_while_true" (State f s (Kwhile2 x s k) e m)
else ret "step_while_false" (State f Sskip k e m)
| Kdowhile2 x s k =>
do b <- bool_val v ty m;
if b
then ret "step_dowhile_true" (State f (Sdowhile x s) k e m)
else ret "step_dowhile_false" (State f Sskip k e m)
| Kfor2 a2 a3 s k =>
do b <- bool_val v ty m;
if b
then ret "step_for_true" (State f s (Kfor3 a2 a3 s k) e m)
else ret "step_for_false" (State f Sskip k e m)
| Kreturn k =>
do v' <- sem_cast v ty f.(fn_return) m;
do m' <- Mem.free_list m (blocks_of_env ge e);
ret "step_return_2" (Returnstate v' (call_cont k) m')
| Kswitch1 sl k =>
do n <- sem_switch_arg v ty;
ret "step_expr_switch" (State f (seq_of_labeled_statement (select_switch n sl)) (Kswitch2 k) e m)
| _ => nil
end
| None =>
map (expr_final_state f k e) (step_expr e w RV a m)
end
| State f (Sdo x) k e m =>
ret "step_do_1" (ExprState f x (Kdo k) e m)
| State f (Ssequence s1 s2) k e m =>
ret "step_seq" (State f s1 (Kseq s2 k) e m)
| State f Sskip (Kseq s k) e m =>
ret "step_skip_seq" (State f s k e m)
| State f Scontinue (Kseq s k) e m =>
ret "step_continue_seq" (State f Scontinue k e m)
| State f Sbreak (Kseq s k) e m =>
ret "step_break_seq" (State f Sbreak k e m)
| State f (Sifthenelse a s1 s2) k e m =>
ret "step_ifthenelse_1" (ExprState f a (Kifthenelse s1 s2 k) e m)
| State f (Swhile x s) k e m =>
ret "step_while" (ExprState f x (Kwhile1 x s k) e m)
| State f (Sskip|Scontinue) (Kwhile2 x s k) e m =>
ret "step_skip_or_continue_while" (State f (Swhile x s) k e m)
| State f Sbreak (Kwhile2 x s k) e m =>
ret "step_break_while" (State f Sskip k e m)
| State f (Sdowhile a s) k e m =>
ret "step_dowhile" (State f s (Kdowhile1 a s k) e m)
| State f (Sskip|Scontinue) (Kdowhile1 x s k) e m =>
ret "step_skip_or_continue_dowhile" (ExprState f x (Kdowhile2 x s k) e m)
| State f Sbreak (Kdowhile1 x s k) e m =>
ret "step_break_dowhile" (State f Sskip k e m)
| State f (Sfor a1 a2 a3 s) k e m =>
if is_skip a1
then ret "step_for" (ExprState f a2 (Kfor2 a2 a3 s k) e m)
else ret "step_for_start" (State f a1 (Kseq (Sfor Sskip a2 a3 s) k) e m)
| State f (Sskip|Scontinue) (Kfor3 a2 a3 s k) e m =>
ret "step_skip_or_continue_for3" (State f a3 (Kfor4 a2 a3 s k) e m)
| State f Sbreak (Kfor3 a2 a3 s k) e m =>
ret "step_break_for3" (State f Sskip k e m)
| State f Sskip (Kfor4 a2 a3 s k) e m =>
ret "step_skip_for4" (State f (Sfor Sskip a2 a3 s) k e m)
| State f (Sreturn None) k e m =>
do m' <- Mem.free_list m (blocks_of_env ge e);
ret "step_return_0" (Returnstate Vundef (call_cont k) m')
| State f (Sreturn (Some x)) k e m =>
ret "step_return_1" (ExprState f x (Kreturn k) e m)
| State f Sskip ((Kstop | Kcall _ _ _ _ _) as k) e m =>
do m' <- Mem.free_list m (blocks_of_env ge e);
ret "step_skip_call" (Returnstate Vundef k m')
| State f (Sswitch x sl) k e m =>
ret "step_switch" (ExprState f x (Kswitch1 sl k) e m)
| State f (Sskip|Sbreak) (Kswitch2 k) e m =>
ret "step_skip_break_switch" (State f Sskip k e m)
| State f Scontinue (Kswitch2 k) e m =>
ret "step_continue_switch" (State f Scontinue k e m)
| State f (Slabel lbl s) k e m =>
ret "step_label" (State f s k e m)
| State f (Sgoto lbl) k e m =>
match find_label lbl f.(fn_body) (call_cont k) with
| Some(s', k') => ret "step_goto" (State f s' k' e m)
| None => nil
end
| Callstate (Internal f) vargs k m =>
check (list_norepet_dec ident_eq (var_names (fn_params f) ++ var_names (fn_vars f)));
let (e,m1) := do_alloc_variables empty_env m (f.(fn_params) ++ f.(fn_vars)) in
do m2 <- sem_bind_parameters w e m1 f.(fn_params) vargs;
ret "step_internal_function" (State f f.(fn_body) k e m2)
| Callstate (External ef _ _ _) vargs k m =>
match do_external ef w vargs m with
| None => nil
| Some(w',t,v,m') => TR "step_external_function" t (Returnstate v k m') :: nil
end
| Returnstate v (Kcall f e C ty k) m =>
ret "step_returnstate" (ExprState f (C (Eval v ty)) k e m)
| _ => nil
end.
Ltac myinv :=
match goal with
| [ |- In _ nil -> _ ] => let X := fresh "X" in intro X; elim X
| [ |- In _ (ret _ _) -> _ ] =>
let X := fresh "X" in
intro X; elim X; clear X;
[let EQ := fresh "EQ" in intro EQ; unfold ret in EQ; inv EQ; myinv | myinv]
| [ |- In _ (_ :: nil) -> _ ] =>
let X := fresh "X" in
intro X; elim X; clear X; [let EQ := fresh "EQ" in intro EQ; inv EQ; myinv | myinv]
| [ |- In _ (match ?x with Some _ => _ | None => _ end) -> _ ] => destruct x eqn:?; myinv
| [ |- In _ (match ?x with false => _ | true => _ end) -> _ ] => destruct x eqn:?; myinv
| [ |- In _ (match ?x with left _ => _ | right _ => _ end) -> _ ] => destruct x; myinv
| _ => idtac
end.
Local Hint Extern 3 => exact I : core.
Theorem do_step_sound:
forall w S rule t S',
In (TR rule t S') (do_step w S) ->
Csem.step ge S t S' \/ (t = E0 /\ S' = Stuckstate /\ can_crash_world w S).
Proof with try (left; right; econstructor; eauto; fail).
intros until S'. destruct S; simpl.
(* State *)
destruct s; myinv...
(* skip *)
destruct k; myinv...
(* break *)
destruct k; myinv...
(* continue *)
destruct k; myinv...
(* goto *)
destruct p as [s' k']. myinv...
(* ExprState *)
destruct (is_val r) as [[v ty]|] eqn:?.
(* expression is a value *)
rewrite (is_val_inv _ _ _ Heqo).
destruct k; myinv...
(* expression reduces *)
intros. exploit list_in_map_inv; eauto. intros [[C rd] [A B]].
generalize (step_expr_sound e w r RV m). unfold reducts_ok. intros [P Q].
exploit P; eauto. intros [a' [k' [CTX [EQ RD]]]].
unfold expr_final_state in A. simpl in A.
destruct k'; destruct rd; inv A; simpl in RD; try contradiction.
(* lred *)
left; left; apply step_lred; auto.
(* stuck lred *)
exploit not_imm_safe_t; eauto. intros [R | R]; eauto.
(* rred *)
destruct RD. left; left; apply step_rred; auto.
(* callred *)
destruct RD; subst m'. left; left; apply step_call; eauto.
(* stuck rred *)
exploit not_imm_safe_t; eauto. intros [R | R]; eauto.
(* callstate *)
destruct fd; myinv.
(* internal *)
destruct (do_alloc_variables empty_env m (fn_params f ++ fn_vars f)) as [e m1] eqn:?.
myinv. left; right; apply step_internal_function with m1. auto.
change e with (fst (e,m1)). change m1 with (snd (e,m1)) at 2. rewrite <- Heqp.
apply do_alloc_variables_sound. eapply sem_bind_parameters_sound; eauto.
(* external *)
destruct p as [[[w' tr] v] m']. myinv. left; right; constructor.
eapply do_ef_external_sound; eauto.
(* returnstate *)
destruct k; myinv...
(* stuckstate *)
contradiction.
Qed.
Remark estep_not_val:
forall f a k e m t S, estep ge (ExprState f a k e m) t S -> is_val a = None.
Proof.
intros.
assert (forall b from to C, context from to C -> (from = to /\ C = fun x => x) \/ is_val (C b) = None).
induction 1; simpl; auto.
inv H.
destruct (H0 a0 _ _ _ H9) as [[A B] | A]. subst. inv H8; auto. auto.
destruct (H0 a0 _ _ _ H9) as [[A B] | A]. subst. inv H8; auto. auto.
destruct (H0 a0 _ _ _ H9) as [[A B] | A]. subst. inv H8; auto. auto.
destruct (H0 a0 _ _ _ H8) as [[A B] | A]. subst. destruct a0; auto. elim H9. constructor. auto.
Qed.
Theorem do_step_complete:
forall w S t S' w',
possible_trace w t w' -> Csem.step ge S t S' -> exists rule, In (TR rule t S') (do_step w S).
Proof with (unfold ret; eauto with coqlib).
intros until w'; intros PT H.
destruct H.
(* Expression step *)
inversion H; subst; exploit estep_not_val; eauto; intro NOTVAL.
(* lred *)
unfold do_step; rewrite NOTVAL.
exploit lred_topred; eauto. instantiate (1 := w). intros (rule & STEP).
exists rule. change (TR rule E0 (ExprState f (C a') k e m')) with (expr_final_state f k e (C, Lred rule a' m')).
apply in_map.
generalize (step_expr_context e w _ _ _ H1 a m). unfold reducts_incl.
intro. replace C with (fun x => C x). apply H2.
rewrite STEP. unfold topred; auto with coqlib.
apply extensionality; auto.
(* rred *)
unfold do_step; rewrite NOTVAL.
exploit rred_topred; eauto. instantiate (1 := e). intros (rule & STEP).
exists rule.
change (TR rule t (ExprState f (C a') k e m')) with (expr_final_state f k e (C, Rred rule a' m' t)).
apply in_map.
generalize (step_expr_context e w _ _ _ H1 a m). unfold reducts_incl.
intro. replace C with (fun x => C x). apply H2.
rewrite STEP; unfold topred; auto with coqlib.
apply extensionality; auto.
(* callred *)
unfold do_step; rewrite NOTVAL.
exploit callred_topred; eauto. instantiate (1 := w). instantiate (1 := e).
intros (rule & STEP). exists rule.
change (TR rule E0 (Callstate fd vargs (Kcall f e C ty k) m)) with (expr_final_state f k e (C, Callred rule fd vargs ty m)).
apply in_map.
generalize (step_expr_context e w _ _ _ H1 a m). unfold reducts_incl.
intro. replace C with (fun x => C x). apply H2.
rewrite STEP; unfold topred; auto with coqlib.
apply extensionality; auto.
(* stuck *)
exploit not_imm_safe_stuck_red. eauto. red; intros; elim H1. eapply imm_safe_t_imm_safe. eauto.
instantiate (1 := w). intros [C' IN].
simpl do_step. rewrite NOTVAL.
exists "step_stuck".
change (TR "step_stuck" E0 Stuckstate) with (expr_final_state f k e (C', Stuckred)).
apply in_map. auto.
(* Statement step *)
inv H; simpl; econstructor...
rewrite H0...
rewrite H0...
rewrite H0...
destruct H0; subst s0...
destruct H0; subst s0...
rewrite H0...
rewrite H0...
rewrite pred_dec_false...
rewrite H0...
rewrite H0...
destruct H0; subst x...
rewrite H0...
rewrite H0; rewrite H1...
rewrite H1. red in H0. destruct k; try contradiction...
rewrite H0...
destruct H0; subst x...
rewrite H0...
(* Call step *)
rewrite pred_dec_true; auto. rewrite (do_alloc_variables_complete _ _ _ _ _ H1).
rewrite (sem_bind_parameters_complete _ _ _ _ _ _ H2)...
exploit do_ef_external_complete; eauto. intro EQ; rewrite EQ. auto with coqlib.
Qed.
End EXEC.
Local Open Scope option_monad_scope.
Definition do_initial_state (p: program): option (genv * state) :=
let ge := globalenv p in
do m0 <- Genv.init_mem p;
do b <- Genv.find_symbol ge p.(prog_main);
do f <- Genv.find_funct_ptr ge b;
check (type_eq (type_of_fundef f) (Tfunction Tnil type_int32s cc_default));
Some (ge, Callstate f nil Kstop m0).
Definition at_final_state (S: state): option int :=
match S with
| Returnstate (Vint r) Kstop m => Some r
| _ => None
end.
|
theory Library_Misc
imports Probability "~~/src/HOL/Library/ContNotDenum"
begin
(* TODO: Move and merge with has_integral_lebesgue_integral *)
lemma isCont_indicator:
fixes x :: "'a::{t2_space}"
shows "isCont (indicator A :: 'a \<Rightarrow> real) x = (x \<notin> frontier A)"
proof -
have *: "!! A x. (indicator A x > (0 :: real)) = (x \<in> A)"
by (case_tac "x : A", auto)
have **: "!! A x. (indicator A x < (1 :: real)) = (x \<notin> A)"
by (case_tac "x : A", auto)
show ?thesis
apply (auto simp add: frontier_def)
(* calling auto here produces a strange error message *)
apply (subst (asm) continuous_at_open)
apply (case_tac "x \<in> A", simp_all)
apply (drule_tac x = "{0<..}" in spec, clarsimp simp add: *)
apply (erule interiorI, assumption, force)
apply (drule_tac x = "{..<1}" in spec, clarsimp simp add: **)
apply (subst (asm) closure_interior, auto, erule notE)
apply (erule interiorI, auto)
apply (subst (asm) closure_interior, simp)
apply (rule continuous_on_interior)
prefer 2 apply assumption
apply (rule continuous_on_eq [where f = "\<lambda>x. 0"], auto intro: continuous_on_const)
apply (rule continuous_on_interior)
prefer 2 apply assumption
by (rule continuous_on_eq [where f = "\<lambda>x. 1"], auto intro: continuous_on_const)
qed
(* Should work for more general types than reals? *)
lemma is_real_interval:
assumes S: "is_interval S"
shows "\<exists>a b::real. S = {} \<or> S = UNIV \<or> S = {..<b} \<or> S = {..b} \<or> S = {a<..} \<or> S = {a..} \<or>
S = {a<..<b} \<or> S = {a<..b} \<or> S = {a..<b} \<or> S = {a..b}"
using S unfolding is_interval_1 by (blast intro: interval_cases)
lemma real_interval_borel_measurable:
assumes "is_interval (S::real set)"
shows "S \<in> sets borel"
proof -
from assms is_real_interval have "\<exists>a b::real. S = {} \<or> S = UNIV \<or> S = {..<b} \<or> S = {..b} \<or>
S = {a<..} \<or> S = {a..} \<or> S = {a<..<b} \<or> S = {a<..b} \<or> S = {a..<b} \<or> S = {a..b}" by auto
then guess a ..
then guess b ..
thus ?thesis
by auto
qed
lemma borel_measurable_mono:
fixes f :: "real \<Rightarrow> real"
assumes "mono f"
shows "f \<in> borel_measurable borel"
proof (subst borel_measurable_iff_ge, auto simp add:)
fix a :: real
have "is_interval {w. a \<le> f w}" using is_interval_1 assms(1) order.trans unfolding mono_def
by (auto simp add:, metis)
thus "{w. a \<le> f w} \<in> sets borel" using real_interval_borel_measurable by auto
qed
lemma continuous_within_open: "a \<in> A \<Longrightarrow> open A \<Longrightarrow> (continuous (at a within A) f) = isCont f a"
by (simp add: continuous_within, rule Lim_within_open)
lemma has_vector_derivative_weaken:
fixes x D and f g s t
assumes f: "(f has_vector_derivative D) (at x within t)"
and "x \<in> s" "s \<subseteq> t"
and "\<And>x. x \<in> s \<Longrightarrow> f x = g x"
shows "(g has_vector_derivative D) (at x within s)"
proof -
have "(f has_vector_derivative D) (at x within s) \<longleftrightarrow> (g has_vector_derivative D) (at x within s)"
unfolding has_vector_derivative_def has_derivative_iff_norm
using assms by (intro conj_cong Lim_cong_within refl) auto
then show ?thesis
using has_vector_derivative_within_subset[OF f `s \<subseteq> t`] by simp
qed
lemma DERIV_image_chain': "(f has_field_derivative D) (at x within s) \<Longrightarrow>
(g has_field_derivative E) (at (f x) within (f ` s)) \<Longrightarrow>
((\<lambda>x. g (f x)) has_field_derivative E * D) (at x within s)"
by (drule (1) DERIV_image_chain, simp add: comp_def)
(* This should have been in the library, like convergent_limsup_cl. *)
lemma convergent_liminf_cl:
fixes X :: "nat \<Rightarrow> 'a::{complete_linorder,linorder_topology}"
shows "convergent X \<Longrightarrow> liminf X = lim X"
by (auto simp: convergent_def limI lim_imp_Liminf)
lemma bdd_below_closure:
fixes A :: "real set"
assumes "bdd_below A"
shows "bdd_below (closure A)"
proof -
from assms obtain m where "\<And>x. x \<in> A \<Longrightarrow> m \<le> x" unfolding bdd_below_def by auto
hence "A \<subseteq> {m..}" by auto
hence "closure A \<subseteq> {m..}" using closed_real_atLeast closure_minimal by auto
thus ?thesis unfolding bdd_below_def by auto
qed
lemma closed_subset_contains_Inf:
fixes A C :: "real set"
shows "closed C \<Longrightarrow> A \<subseteq> C \<Longrightarrow> A \<noteq> {} \<Longrightarrow> bdd_below A \<Longrightarrow> Inf A \<in> C"
by (metis closure_contains_Inf closure_minimal subset_eq)
lemma atLeastAtMost_subset_contains_Inf:
fixes A :: "real set" and a b :: real
shows "A \<noteq> {} \<Longrightarrow> a \<le> b \<Longrightarrow> A \<subseteq> {a..b} \<Longrightarrow> Inf A \<in> {a..b}"
by (rule closed_subset_contains_Inf)
(auto intro: closed_real_atLeastAtMost intro!: bdd_belowI[of A a])
lemma convergent_real_imp_convergent_ereal:
assumes "convergent a"
shows "convergent (\<lambda>n. ereal (a n))" and "lim (\<lambda>n. ereal (a n)) = ereal (lim a)"
proof -
from assms obtain L where L: "a ----> L" unfolding convergent_def ..
hence lim: "(\<lambda>n. ereal (a n)) ----> ereal L" using lim_ereal by auto
thus "convergent (\<lambda>n. ereal (a n))" unfolding convergent_def ..
thus "lim (\<lambda>n. ereal (a n)) = ereal (lim a)" using lim L limI by metis
qed
lemma abs_bounds: "x \<le> y \<Longrightarrow> -x \<le> y \<Longrightarrow> abs (x :: ereal) \<le> y"
by (metis abs_ereal_ge0 abs_ereal_uminus ereal_0_le_uminus_iff linear)
lemma real_arbitrarily_close_eq:
fixes x y :: real
assumes "\<And>\<epsilon>. \<epsilon> > 0 \<Longrightarrow> abs (x - y) \<le> \<epsilon>"
shows "x = y"
by (metis abs_le_zero_iff assms dense_ge eq_iff_diff_eq_0)
lemma real_interval_avoid_countable_set:
fixes a b :: real and A :: "real set"
assumes "a < b" and "countable A"
shows "\<exists>x. x \<in> {a<..<b} \<and> x \<notin> A"
proof -
from `countable A` have "countable (A \<inter> {a<..<b})" by auto
moreover with `a < b` have "\<not> countable {a<..<b}"
by (simp add: uncountable_open_interval)
ultimately have "A \<inter> {a<..<b} \<noteq> {a<..<b}" by auto
hence "A \<inter> {a<..<b} \<subset> {a<..<b}"
by (intro psubsetI, auto)
hence "\<exists>x. x \<in> {a<..<b} - A \<inter> {a<..<b}"
by (rule psubset_imp_ex_mem)
thus ?thesis by auto
qed
(* TODO: move this somewhere else *)
lemma continuous_on_vector_derivative:
"(\<And>x. x \<in> S \<Longrightarrow> (f has_vector_derivative f' x) (at x within S)) \<Longrightarrow> continuous_on S f"
by (auto simp: continuous_on_eq_continuous_within intro!: has_vector_derivative_continuous)
(* the dual version is in Convex_Euclidean_Space.thy *)
lemma interior_real_Iic:
fixes a :: real
shows "interior {..a} = {..<a}"
proof -
{
fix y
assume "a > y"
then have "y \<in> interior {..a}"
apply (simp add: mem_interior)
apply (rule_tac x="(a-y)" in exI)
apply (auto simp add: dist_norm)
done
}
moreover
{
fix y
assume "y \<in> interior {..a}"
then obtain e where e: "e > 0" "cball y e \<subseteq> {..a}"
using mem_interior_cball[of y "{..a}"] by auto
moreover from e have "y + e \<in> cball y e"
by (auto simp add: cball_def dist_norm)
ultimately have "a \<ge> y + e" by auto
then have "a > y" using e by auto
}
ultimately show ?thesis by auto
qed
lemma frontier_real_Iic:
fixes a :: real
shows "frontier {..a} = {a}"
unfolding frontier_def by (auto simp add: interior_real_Iic)
(**************************************************)
end |
\documentclass[12pt, right open]{memoir}
\usepackage{graphicx}
\usepackage{tikz}
\usetikzlibrary{matrix,chains,positioning,decorations.pathreplacing,arrows,automata}
\usetikzlibrary{shapes.geometric, calc, intersections}
\usepackage{mathtools}
\usepackage{amsmath}
\usepackage{float}
\floatstyle{boxed}
\restylefloat{figure}
\usepackage{ifthen}
\setcounter{secnumdepth}{5}
\begin{document}
\chapter{Intro}
Sevvai Dosham is also known as Guja Dosham or Guja Dosh.
It is also known as Manglik or Manglik Dosh in the northern part of our country.
In a horoscope, if Sevvai (Mars in English and Mangal in Hindi) is in the 2nd, 4th, 7th, 8th or 12th houses from the Lagna or Chandran or Sukran, the horoscope is supposed to suffer from Sevvai Dosham.
A horoscope with Sevvai Dosham should not be considered as matching for marriage with a horoscope which does not suffer from Sevvai Dosham.
This is the general rule. If a horoscope with Sevvai Dosham is married to a horoscope without Sevvai Dosham, it is feared that the life of the spouse will be endangered.
Now it need not necessarily be a demise.
In modern days, it can be taken the other way around also. In the case of incompatible Sevvai Doshams, it may, instead of risking the life of the spouse, may result in a long term separation, legal separation (divorce) or frequently disrupted marital relationships, taking away the peace of mind.The conclusion need not necessarily be the demise of the spouse.
As we have seen earlier, a Sevvai Dosham is constituted if Sevvai is in the 2,4,7,8 or 12th house from the Lagna, Chandran or Sukran.
Sevvai Dosham is exempted under several conditions.
In some cases there are varying versions of exemptions.
But most of the exemptions are common in different versions.The following are the exemptions for Sevvai Dosham, even if Sevvai is in the 2nd, 4th, 7th, 8th or 12th houses from the Lagna, Chandran or Sukran.
In the case of exemption to Sevvai Dosham, it should be taken as if the horoscope is not suffering from Sevvai Dosham, since the same is offset by the exemption.
\section{The exemptions are:}
1. Whatever be the place of Sevvai in a horoscope, if Sevvai is in his exalted house (Uchcham) Makaram, or ruling houses (Aakshi houses) Mesham and Vrichigam, Sevvai Dosham is exempted.
2. Wherever is Sevvai in a horoscope, if the Lagna of the horoscope is Katagam or Simham, Sevvai Dosham is exempted.
3. Whatever is the place of Sevvai with reference to Lagna, Chandran or Sukran, if Sevvai is in Simham or Kumbam, Sevvai Dosham is exempted.
4. If Sevvai is in Simham, Katagam, Dhanur or Meenam Raasis, Sevvai Dosham is exempted.
5. If Sevvai is associated with Sani, Raahu or Kethu or if Sevvai is receiving the aspect (Paarvai) of Sani, Raahu or Kethu, Sevvai Dosham is exempted.
6. If the Lord of the house where Sevvai is positioned in the horoscope, from where Sevvai Dosham is constituted, is either in Kendra Sthanas or Thri-Kona Sthanas, (1,4,5,7,9,10 houses), Sevvai Dosham is exempted.
7. If Sevvai is associated with Guru or Chandran, Sevvai Dosham is exempted.
8. If Sevvai is in the 2nd house from the Lagna or Chandran or Sukran, and if such a 2nd house happens to be Midhunam or Kanni, Sevvai Dosham is exempted.
9. If Sevvai is in the 4th house from Lagna, Chandran or Sukran, and if such a house is Mesham or Vrichigam, Sevvai Dosham is exempted. (In Mesham and Vrichigam, Sevvai Dosham is also exempted as a general rule.
10. If Sevvai is in the 7th house and if the 7th house is Makaram or Katagam, Sevvai Dosham is exempted.
11. If Sevvai is in the 8th house, and if the 8th house is Dhanur or Meenam, Sevvai Dosham is exempted.
12. If Sevvai is in the 12th house, and if the 12th house is Thulam or Rishabham, Sevvai Dosham is exempted.
13. If Sevvai is associated with Sooriyan or Budhan or aspected by Sooriyan or Budhan, Sevvai Dosham is exempted.
If - and only if - Sevvai in the 2nd, 4th, 7th, 8th or 12 house from Lagna, Chandran or Sukran, does not fall under any of the above exemptions, it should be conceived that the horoscope suffers from Sevvai Dosham.
Normally it is believed that a horoscope with Sevvai Dosham should be married only to a person with Sevvai Dosham. Otherwise, it is feared to have an impact on the life of the spouse.
No one will dare risk the chances of life. As such, it has not been tried otherwise - atleast as far as my knowledge goes.
Hence the concept of Sevvai Dosham has necessarily to be applied in all horoscopes matching as a social necessity..
\end{document} |
{-# OPTIONS --cubical #-}
module Cubical.Codata.Stream where
open import Cubical.Codata.Stream.Base public
open import Cubical.Codata.Stream.Properties public
|
chapter \<open>Terms with explicit bound variable names\<close>
theory Nterm
imports Term_Class
begin
text \<open>
The \<open>nterm\<close> type is similar to @{typ term}, but removes the distinction between bound and free
variables. Instead, there are only named variables.
\<close>
datatype nterm =
Nconst name |
Nvar name |
Nabs name nterm ("\<Lambda>\<^sub>n _. _" [0, 50] 50) |
Napp nterm nterm (infixl "$\<^sub>n" 70)
derive linorder nterm
instantiation nterm :: pre_term begin
definition app_nterm where
"app_nterm t u = t $\<^sub>n u"
fun unapp_nterm where
"unapp_nterm (t $\<^sub>n u) = Some (t, u)" |
"unapp_nterm _ = None"
definition const_nterm where
"const_nterm = Nconst"
fun unconst_nterm where
"unconst_nterm (Nconst name) = Some name" |
"unconst_nterm _ = None"
definition free_nterm where
"free_nterm = Nvar"
fun unfree_nterm where
"unfree_nterm (Nvar name) = Some name" |
"unfree_nterm _ = None"
fun frees_nterm :: "nterm \<Rightarrow> name fset" where
"frees_nterm (Nvar x) = {| x |}" |
"frees_nterm (t\<^sub>1 $\<^sub>n t\<^sub>2) = frees_nterm t\<^sub>1 |\<union>| frees_nterm t\<^sub>2" |
"frees_nterm (\<Lambda>\<^sub>n x. t) = frees_nterm t - {| x |}" |
"frees_nterm (Nconst _) = {||}"
fun subst_nterm :: "nterm \<Rightarrow> (name, nterm) fmap \<Rightarrow> nterm" where
"subst_nterm (Nvar s) env = (case fmlookup env s of Some t \<Rightarrow> t | None \<Rightarrow> Nvar s)" |
"subst_nterm (t\<^sub>1 $\<^sub>n t\<^sub>2) env = subst_nterm t\<^sub>1 env $\<^sub>n subst_nterm t\<^sub>2 env" |
"subst_nterm (\<Lambda>\<^sub>n x. t) env = (\<Lambda>\<^sub>n x. subst_nterm t (fmdrop x env))" |
"subst_nterm t env = t"
fun consts_nterm :: "nterm \<Rightarrow> name fset" where
"consts_nterm (Nconst x) = {| x |}" |
"consts_nterm (t\<^sub>1 $\<^sub>n t\<^sub>2) = consts_nterm t\<^sub>1 |\<union>| consts_nterm t\<^sub>2" |
"consts_nterm (Nabs _ t) = consts_nterm t" |
"consts_nterm (Nvar _) = {||}"
instance
by standard
(auto
simp: app_nterm_def const_nterm_def free_nterm_def
elim: unapp_nterm.elims unconst_nterm.elims unfree_nterm.elims
split: option.splits)
end
instantiation nterm :: "term" begin
definition abs_pred_nterm :: "(nterm \<Rightarrow> bool) \<Rightarrow> nterm \<Rightarrow> bool" where
[code del]: "abs_pred P t \<longleftrightarrow> (\<forall>t' x. t = (\<Lambda>\<^sub>n x. t') \<longrightarrow> P t' \<longrightarrow> P t)"
instance proof (standard, goal_cases)
case (1 P t)
then show ?case
by (induction t) (auto simp: abs_pred_nterm_def const_nterm_def free_nterm_def app_nterm_def)
next
case 3
show ?case
unfolding abs_pred_nterm_def
apply auto
apply (subst fmdrop_comm)
by auto
next
case 4
show ?case
unfolding abs_pred_nterm_def
apply auto
apply (erule_tac x = "fmdrop x env\<^sub>1" in allE)
apply (erule_tac x = "fmdrop x env\<^sub>2" in allE)
by (auto simp: fdisjnt_alt_def)
next
case 5
show ?case
unfolding abs_pred_nterm_def
apply clarify
subgoal for t' x env
apply (erule allE[where x = "fmdrop x env"])
by auto
done
next
case 6
show ?case
unfolding abs_pred_nterm_def
apply clarify
subgoal premises prems[rule_format] for t x env
unfolding consts_nterm.simps subst_nterm.simps frees_nterm.simps
apply (subst prems)
unfolding fmimage_drop fmdom_drop
apply (rule arg_cong[where f = "(|\<union>|) (consts t)"])
apply (rule arg_cong[where f = ffUnion])
apply (rule arg_cong[where f = "\<lambda>x. consts |`| fmimage env x"])
by auto
done
qed (auto simp: abs_pred_nterm_def)
end
lemma no_abs_abs[simp]: "\<not> no_abs (\<Lambda>\<^sub>n x. t)"
by (subst no_abs.simps) (auto simp: term_cases_def)
end |
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.Foundations.Equiv.Base where
open import Cubical.Foundations.Function
open import Cubical.Foundations.Prelude
open import Cubical.Core.Glue public
using ( isEquiv ; equiv-proof ; _≃_ ; equivFun ; equivProof )
fiber : ∀ {ℓ ℓ'} {A : Type ℓ} {B : Type ℓ'} (f : A → B) (y : B) → Type (ℓ-max ℓ ℓ')
fiber {A = A} f y = Σ[ x ∈ A ] f x ≡ y
-- Helper function for constructing equivalences from pairs (f,g) that cancel each other up to definitional
-- equality. For such (f,g), the result type simplifies to isContr (fiber f b).
strictContrFibers : ∀ {ℓ ℓ'} {A : Type ℓ} {B : Type ℓ'} {f : A → B} (g : B → A) (b : B)
→ Σ[ t ∈ fiber f (f (g b)) ]
((t' : fiber f b) → Path (fiber f (f (g b))) t (g (f (t' .fst)) , cong (f ∘ g) (t' .snd)))
strictContrFibers {f = f} g b .fst = (g b , refl)
strictContrFibers {f = f} g b .snd (a , p) i = (g (p (~ i)) , λ j → f (g (p (~ i ∨ j))))
-- The identity equivalence
idIsEquiv : ∀ {ℓ} (A : Type ℓ) → isEquiv (idfun A)
idIsEquiv A .equiv-proof = strictContrFibers (idfun A)
idEquiv : ∀ {ℓ} (A : Type ℓ) → A ≃ A
idEquiv A .fst = idfun A
idEquiv A .snd = idIsEquiv A
|
State Before: α : Type u_1
β : Type ?u.36119
γ : Type ?u.36122
δ : Type ?u.36125
δ' : Type ?u.36128
ι : Sort u_2
s t u : Set α
m : ι → MeasurableSpace α
⊢ (⨆ (n : ι), m n) = generateFrom {s | ∃ n, MeasurableSet s} State After: case h
α : Type u_1
β : Type ?u.36119
γ : Type ?u.36122
δ : Type ?u.36125
δ' : Type ?u.36128
ι : Sort u_2
s✝ t u : Set α
m : ι → MeasurableSpace α
s : Set α
⊢ MeasurableSet s ↔ MeasurableSet s Tactic: ext s State Before: case h
α : Type u_1
β : Type ?u.36119
γ : Type ?u.36122
δ : Type ?u.36125
δ' : Type ?u.36128
ι : Sort u_2
s✝ t u : Set α
m : ι → MeasurableSpace α
s : Set α
⊢ MeasurableSet s ↔ MeasurableSet s State After: case h
α : Type u_1
β : Type ?u.36119
γ : Type ?u.36122
δ : Type ?u.36125
δ' : Type ?u.36128
ι : Sort u_2
s✝ t u : Set α
m : ι → MeasurableSpace α
s : Set α
⊢ GenerateMeasurable {s | ∃ i, MeasurableSet s} s ↔ MeasurableSet s Tactic: rw [measurableSet_iSup] State Before: case h
α : Type u_1
β : Type ?u.36119
γ : Type ?u.36122
δ : Type ?u.36125
δ' : Type ?u.36128
ι : Sort u_2
s✝ t u : Set α
m : ι → MeasurableSpace α
s : Set α
⊢ GenerateMeasurable {s | ∃ i, MeasurableSet s} s ↔ MeasurableSet s State After: no goals Tactic: rfl |
! integer, bind(c) :: somevar
bind(c, name="sharedcommon") :: /sharedcommon/
end
|
#' Weight of Evidence and Information Value in Credit Scoring
#'
#' Calculate Information Value and Weight of Evidence for variables in data frame. Information Value is used in credit scoring to compare predictive power among variables.
#' Weight of Evidence (WoE): \deqn{WoE = \ln(\frac{\%good_i}{\%bad_i})}
#' Information Value:
#' \deqn{IV = \Sigma_{i=1}^{n}(\ln(\frac{\%good_i}{\%bad_i})*(\%good_i - \%bad_i))}
#' @docType package
#' @name woe
#' @import ggplot2
#' @importFrom plyr rbind.fill
#' @importFrom RColorBrewer brewer.pal
#' @import rpart
#' @importFrom sqldf sqldf
NULL |
theory T8
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z)))
"
nitpick[card nat=4,timeout=86400]
oops
end |
[STATEMENT]
lemma map_of_SomeD: "map_of xs k = Some y \<Longrightarrow> (k, y) \<in> set xs"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. map_of xs k = Some y \<Longrightarrow> (k, y) \<in> set xs
[PROOF STEP]
by (induct xs) (auto split: if_splits) |
palindrome : Nat -> String -> Bool
palindrome n str = let longEnough = (length str) > n
in longEnough && (isPalindrome str)
where
isPalindrome : String -> Bool
isPalindrome s = (toLower s) == (toLower (reverse s))
showPalindrome : String -> String
showPalindrome str = "Word is palindrome: " ++ show (palindrome 0 str) ++ "\n"
main : IO ()
main = repl "> " showPalindrome |
lemma content_dvd_coeffs: "c \<in> set (coeffs p) \<Longrightarrow> content p dvd c" |
// Server settings and option parsing
#ifndef _SETTINGS_H
#define _SETTINGS_H
#include <gsl/gsl_rng.h>
#include <stdbool.h>
// Settings the server has
typedef struct _settings {
int verbose;
int threads;
int tcpport;
double dist_arg1; // normal distribution mean
double dist_arg2; // normal distribution stddev
bool use_dist;
gsl_rng *r;
} settings;
void usage(void);
settings settings_init(void);
bool settings_parse(int argc, char **argv, settings *s);
#endif
|
! { dg-do compile }
!
! PR 58470: [4.9 Regression] [OOP] ICE on invalid with FINAL procedure and type extension
!
! Contributed by Andrew Benson <[email protected]>
module cf
type :: cfml
contains
final :: mld
end type cfml
type, extends(cfml) :: cfmde
end type cfmde
contains
subroutine mld(s) ! { dg-error "must be of type" }
class(cfml), intent(inout) :: s
end subroutine mld
end module cf
! { dg-final { cleanup-modules "cf" } }
|
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/program_options.hpp>
#include "BloomFilter.hpp"
#include "utils/Helpers.hpp"
namespace po = boost::program_options;
int main(int argc, char **argv)
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
po::options_description desc;
po::variables_map vm;
desc.add_options()
("file-with-saved-data", po::value<std::string>()->required(), "Path to file with data to save in bloom filter")
("hash-size", po::value<uint32_t>()->required(), "Hash size for bloom filter")
("hash-count", po::value<uint32_t>()->required(), "Hash count for bloom filter")
("hash-start", po::value<uint32_t>()->default_value(0), "Start using hashes from bit");
try
{
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
}
catch (const po::error &e)
{
desc.print(std::cerr);
throw std::runtime_error(e.what());
}
auto hashSize = vm["hash-size"].as<uint32_t>();
auto hashCount = vm["hash-count"].as<uint32_t>();
auto hashStart = vm["hash-start"].as<uint32_t>();
auto fileName = vm["file-with-saved-data"].as<std::string>();
hobf::BloomFilter bf(hashSize, hashCount, hashStart);
std::ifstream dataStream(fileName, std::ios::in);
if (!dataStream)
{
throw std::runtime_error("Could not open file with saved data '" + fileName + "'");
}
auto toCompute = (hashStart + hobf::utils::getPower(hashSize) * hashCount + 127) / 128;
std::vector<uint32_t> seeds(toCompute);
for (uint32_t i = 0; i < seeds.size(); ++i)
{
seeds[i] = i + 1;
}
std::string elem;
std::vector<uint64_t> hashes;
hashes.reserve(seeds.size() * 2);
while(std::getline(dataStream, elem))
{
hashes.clear();
for (auto seed: seeds)
{
auto hash = hobf::utils::hash(elem, seed);
hashes.push_back(hash.first);
hashes.push_back(hash.second);
}
bf.add(hashes);
}
while(std::getline(std::cin, elem))
{
hashes.clear();
for (auto seed: seeds)
{
auto hash = hobf::utils::hash(elem, seed);
hashes.push_back(hash.first);
hashes.push_back(hash.second);
}
if (bf.lookup(hashes))
{
std::cout << elem << "\n";
}
}
} |
This design takes inspiration from a city station such as Newcastle or York. Bay platforms and a range of sidings to the top right mean that plenty of locomotives can be accommodated, each taking turns to run regional express services from this busy railway hub. The bay to the lower end of the station could be used for Motorail or parcels services, breaking up the staple diet of passenger trains. |
If $f$ is a function from $X$ to $Y$ and $M$ is a set of measures on $Y$, then the sets of the measure algebra of the supremum of $M$ under $f$ are the same as the sets of the supremum of the measure algebras of the measures in $M$ under $f$. |
-- --------------------------------------------------------------- [ State.idr ]
-- Module : State.idr
-- Copyright : (c) Jan de Muijnck-Hughes
-- License : see LICENSE
-- --------------------------------------------------------------------- [ EOH ]
||| State for Building Patterns from the AST.
module Sif.DSL.State
import Effects
import Effect.Default
import Sif.Types
import Sif.AbsSyntax
import Sif.Pattern
import Sif.Error
-- -------------------------------------------------------------- [ Directives ]
%access export
%default total
-- -------------------------------------------------------------------- [ Body ]
public export
record BuildState where
constructor MkSState
getProbID : Maybe String
getRQs : List (String, SifAST TyREQ)
pattTitle : String
pattDesc : Maybe String
getPFName : String
getSFName : String
defBuildSt : String -> String -> BuildState
defBuildSt p s = MkSState Nothing Nil "" Nothing p s
Default BuildState where
default = defBuildSt "" ""
-- --------------------------------------------------------------------- [ EOF ]
|
-- Copyright (c) 2013 Radek Micek
module Main
import D3
main : IO ()
main = do
-- Prints: 3, 5
arr <- mkArray [1, 2, 3, 6]
getNth arr 2 >>= print
setNth arr 2 5
getNth arr 2 >>= print
-- Prints: 0, 1, 17
arr2 <- emptyA ()
lengthA arr2 >>= print
pushA arr2 17
lengthA arr2 >>= print
getNth arr2 0 >>= print
-- Prints: True, False
anyA (pure . (== 5)) arr >>= print
anyA (pure . (== 3)) arr >>= print
-- Prints: [1, 2, 5, 6]
-- [1, 2]
arr3 <- filterA (pure . (< 4)) arr
arrayToList arr >>= print
arrayToList arr3 >>= print
return ()
|
theory MyNat
imports Main
begin
datatype nat = Zero | Suc nat
fun add :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"add Zero n = n" |
"add (Suc m) n = Suc(add m n)"
lemma add_02 [simp]: "add m Zero = m"
apply(induction m)
apply(auto)
done
lemma add_assoc [simp]: "add x (add y z) = add (add x y) z"
apply(induction x)
apply(auto)
done
lemma add_suc [simp]: "Suc (add x y) = add x (Suc y)"
apply(induction x)
apply(auto)
done
lemma add_comm [simp]: "add x y = add y x"
apply(induction x)
apply(auto)
done
fun double :: "nat \<Rightarrow> nat" where
"double Zero = Zero" |
"double (Suc m) = Suc (Suc (double m))"
value "double (Suc Zero)"
value "double (Suc (Suc Zero))"
lemma double_add [simp]: "double m = add m m"
apply(induction m)
apply(auto)
done
end |
data Tree elem = Empty
| Node (Tree elem) elem (Tree elem)
%name Tree left, val, right
Eq elem => Eq (Tree elem) where
(==) Empty Empty = ?Eq_rhs1_2
(==) (Node left e right) (Node left' e' right') = left == left' && e == e' && right == right'
(==) _ _ = False
insert : Ord elem => elem -> Tree elem -> Tree elem
insert x Empty = Node Empty x Empty
insert x orig@(Node left val right) = case compare x val of
LT => Node (insert x left) val right
EQ => orig
GT => Node left val (insert x right)
listToTree : Ord a => List a -> Tree a
listToTree [] = Empty
listToTree (x :: xs) = let tree = listToTree xs in insert x tree
treeToList : Tree a -> List a
treeToList Empty = []
treeToList (Node left val right) = treeToList left ++ [val] ++ treeToList right
|
Require Export ComputableCategory SigTCategory.
Set Implicit Arguments.
Generalizable All Variables.
Set Asymmetric Patterns.
Set Universe Polymorphism.
Section ComputableCategory.
Variable I : Type.
Context `(Index2Cat : forall i : I, @SpecializedCategory (@Index2Object i)).
Local Coercion Index2Cat : I >-> SpecializedCategory.
Let eq_dec_on_cat `(C : @SpecializedCategory objC) := forall x y : objC, {x = y} + {x <> y}.
Definition ComputableCategoryDec := @SpecializedCategory_sigT_obj _ (@ComputableCategory _ _ Index2Cat) (fun C => eq_dec_on_cat C).
End ComputableCategory.
|
, we all picks the top libraries together with greatest image resolution simply for you all, and this photographs is one among graphics libraries in this very best graphics gallery concerning Unique Living Room Chair Designs. I am hoping you can enjoy it.
posted simply by admin in 2019-03-16 12:32:45. To see almost all pictures throughout Unique Living Room Chair Designs images gallery please adhere to this kind of web page link. |
module AutomotiveDrivingModels
using Reexport
using Parameters
using Printf
using LinearAlgebra
using SparseArrays
@reexport using Records
@reexport using Distributions
@reexport using Vec
include("interface/main.jl") # core interface
include("1d/main.jl") # 1D interface
include("2d/main.jl") # 2D interface
end # module
|
[STATEMENT]
lemma (in semicategory) op_smc_is_monic_arr[smc_op_simps]:
"f : b \<mapsto>\<^sub>m\<^sub>o\<^sub>n\<^bsub>op_smc \<CC>\<^esub> a \<longleftrightarrow> f : a \<mapsto>\<^sub>e\<^sub>p\<^sub>i\<^bsub>\<CC>\<^esub> b"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. f : b \<mapsto>\<^sub>m\<^sub>o\<^sub>n\<^bsub>op_smc \<CC>\<^esub> a = f : a \<mapsto>\<^sub>e\<^sub>p\<^sub>i\<^bsub>\<CC>\<^esub> b
[PROOF STEP]
unfolding is_monic_arr_def is_epic_arr_def smc_op_simps
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (f : a \<mapsto>\<^bsub>\<CC>\<^esub> b \<and> (\<forall>fa g a. fa : b \<mapsto>\<^bsub>\<CC>\<^esub> a \<longrightarrow> g : b \<mapsto>\<^bsub>\<CC>\<^esub> a \<longrightarrow> f \<circ>\<^sub>A\<^bsub>op_smc \<CC>\<^esub> fa = f \<circ>\<^sub>A\<^bsub>op_smc \<CC>\<^esub> g \<longrightarrow> fa = g)) = (f : a \<mapsto>\<^bsub>\<CC>\<^esub> b \<and> (\<forall>fa g a. fa : b \<mapsto>\<^bsub>\<CC>\<^esub> a \<longrightarrow> g : b \<mapsto>\<^bsub>\<CC>\<^esub> a \<longrightarrow> f \<circ>\<^sub>A\<^bsub>op_smc \<CC>\<^esub> fa = f \<circ>\<^sub>A\<^bsub>op_smc \<CC>\<^esub> g \<longrightarrow> fa = g))
[PROOF STEP]
.. |
module Utils.Conjugate
import Data.Complex
%default total
%access public export
interface Conjugate space coSpace where
conjug : space -> coSpace
implementation Neg a => Conjugate (Complex a) (Complex a) where
conjug = conjugate
implementation Conjugate Double Double where
conjug = id
implementation Conjugate Integer Integer where
conjug = id
implementation Conjugate Nat Nat where
conjug = id
implementation Conjugate Int Int where
conjug = id
|
Require Export VST.floyd.proofauto.
Require Export VST.floyd.library.
Require Export CertiGraph.CertiGC.gc.
Instance CompSpecs : compspecs. make_compspecs prog. Defined.
Definition Vprog : varspecs. mk_varspecs prog. Defined.
Definition thread_info_type : type := Tstruct _thread_info noattr.
Definition space_type : type := Tstruct _space noattr.
Definition heap_type: type := Tstruct _heap noattr.
|
(* Property from Productive Use of Failure in Inductive Proof,
Andrew Ireland and Alan Bundy, JAR 1996.
This Isabelle theory is produced using the TIP tool offered at the following website:
https://github.com/tip-org/tools
This file was originally provided as part of TIP benchmark at the following website:
https://github.com/tip-org/benchmarks
Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
to make it compatible with Isabelle2017.
Some proofs were added by Yutaka Nagashima.*)
theory TIP_prop_42
imports "../../Test_Base"
begin
datatype 'a list = nil2 | cons2 "'a" "'a list"
datatype Nat = Z | S "Nat"
fun y :: "Nat => Nat => bool" where
"y (Z) (Z) = True"
| "y (Z) (S z2) = False"
| "y (S x2) (Z) = False"
| "y (S x2) (S y22) = y x2 y22"
fun x :: "bool => bool => bool" where
"x True y2 = True"
| "x False y2 = y2"
fun elem :: "Nat => Nat list => bool" where
"elem z (nil2) = False"
| "elem z (cons2 z2 xs) = x (y z z2) (elem z xs)"
fun union :: "Nat list => Nat list => Nat list" where
"union (nil2) y2 = y2"
| "union (cons2 z2 xs) y2 =
(if elem z2 y2 then union xs y2 else cons2 z2 (union xs y2))"
theorem property0 :
"((elem z y2) ==> (elem z (union y2 z2)))"
oops
end
|
function transpose(f) %#ok<*INUSD>
%TRANSPOSE CHEBTECH objects are not transposable, so this method will throw an
% error.
% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.
error('CHEBFUN:CHEBTECH:transpose:notPossible', ...
'CHEBTECH objects are not transposable.')
end
|
module Main
import Counts
showCounts : String -> String
showCounts str = show (counts str) ++ "\n"
main : IO ()
main = repl "Enter a string: " showCounts |
(* *********************************************************************)
(* *)
(* The Syntax of the Intermediate Language *)
(* *)
(* More specifically, this file includes the Notations and supporting *)
(* definitions to use the language described in lang.v *)
(* *)
(* *********************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Require Import Integers.
Require Import lang.
Declare Scope hdl_type_scope.
Notation "'tbit'" := (TBit) (at level 60) : hdl_type_scope.
Notation "'tvec32'" := (TVec32) (at level 60) : hdl_type_scope.
Notation "'tvec64'" := (TVec64) (at level 60) : hdl_type_scope.
Notation "'tarr' N <<< t >>>" := (TArr N t) (at level 60, right associativity) : hdl_type_scope.
Close Scope hdl_type_scope.
Declare Scope hdl_exp_scope.
Notation "'val' v" := (EVal v) (at level 59) : hdl_exp_scope.
Notation "'var' x" := (EVar x) (at level 59) : hdl_exp_scope.
Notation "e [[ i ]]" := (EDeref i e) (at level 60) : hdl_exp_scope.
Notation "e 'rightrotate' n" := (r_rotate32 e n) (at level 60) : hdl_exp_scope.
Notation "e 'rightshift' n" := (EBinop OShru e n) (at level 60) : hdl_exp_scope.
Notation "e1 'and' e2" := (EBinop OAnd e1 e2) (at level 61) : hdl_exp_scope.
Notation "e1 'xor' e2" := (EBinop OXor e1 e2) (at level 61) : hdl_exp_scope.
Notation "e1 'plus' e2" := (EBinop OAddu e1 e2) (at level 61) : hdl_exp_scope.
Notation "e1 'lt' e2" := (EBinop OLt e1 e2) (at level 61) : hdl_exp_scope.
Notation "'not' e" := (ENot e) (at level 60) : hdl_exp_scope.
Close Scope hdl_exp_scope.
Declare Scope hdl_stmt_scope.
Notation "x <= e" := (SAssign x e) (at level 70) : hdl_stmt_scope. (*TODO: change to ::= to avoid confusion with Verilog nonblocking assignments*)
Definition iter (lo hi:nat) (f:iN hi -> stmt) := @SIter lo hi f.
Arguments iter lo hi f : clear implicits.
Notation "x @ i <- e" := (SUpdate x i e) (at level 70).
Notation "'skip'" := (SSkip) (at level 70).
Infix ";;" := (SSeq) (at level 71).
Close Scope hdl_stmt_scope.
Coercion PSeq : prog >-> Funclass.
Coercion PStmt : stmt >-> prog.
Notation "i 'vec' x ::== v" := (VDecl i x v) (at level 79).
Notation "i 'vec' x <<< t >>> ::== v" := (@VDecl t _ i x v) (at level 79).
Notation "i 'arr' x <<< t , N >>>" := (@ADecl i N t x) (at level 79).
Notation "f ;;; p" := (f p) (at level 80, right associativity, only parsing).
Notation "'done'" := (PDone) (at level 79).
Definition nat2bool (n:nat) : bool :=
match n with
| O => false
| 1 => true
| _ => false (*bogus*)
end.
Notation "' i" := (@Fin.of_nat_lt (proj1_sig (Fin.to_nat i)) _ _) (at level 55) : hdl_exp_scope.
Notation "'' m" := (@Fin.of_nat_lt m _ _) (at level 55) : hdl_exp_scope.
Notation "'force' m" := (@nat_to_iN _ m) (at level 55) : hdl_exp_scope.
Require Export ZArith.
Coercion Int.repr : Z >-> Int.int.
Coercion nat_of_fin (N:nat) (x:iN N) : nat := proj1_sig (Fin.to_nat x).
Definition evar (t:ty) (x:id t) : exp t := @EVar t x. Arguments evar {t} x.
|
State Before: α : Type u_1
β : Type ?u.411803
γ : Type ?u.411806
δ : Type ?u.411809
ι : Type ?u.411812
R : Type ?u.411815
R' : Type ?u.411818
m0 : MeasurableSpace α
inst✝¹ : MeasurableSpace β
inst✝ : MeasurableSpace γ
μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : Measure α
s✝ s' t : Set α
μa μa' : Measure α
μb μb' : Measure β
μc : Measure γ
f✝ : α → β
s : Set α
f : α → α
hf : QuasiMeasurePreserving f
k : ℕ
hs : f ⁻¹' s =ᵐ[μ] s
⊢ f^[k] ⁻¹' s =ᵐ[μ] s State After: case zero
α : Type u_1
β : Type ?u.411803
γ : Type ?u.411806
δ : Type ?u.411809
ι : Type ?u.411812
R : Type ?u.411815
R' : Type ?u.411818
m0 : MeasurableSpace α
inst✝¹ : MeasurableSpace β
inst✝ : MeasurableSpace γ
μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : Measure α
s✝ s' t : Set α
μa μa' : Measure α
μb μb' : Measure β
μc : Measure γ
f✝ : α → β
s : Set α
f : α → α
hf : QuasiMeasurePreserving f
hs : f ⁻¹' s =ᵐ[μ] s
⊢ f^[Nat.zero] ⁻¹' s =ᵐ[μ] s
case succ
α : Type u_1
β : Type ?u.411803
γ : Type ?u.411806
δ : Type ?u.411809
ι : Type ?u.411812
R : Type ?u.411815
R' : Type ?u.411818
m0 : MeasurableSpace α
inst✝¹ : MeasurableSpace β
inst✝ : MeasurableSpace γ
μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : Measure α
s✝ s' t : Set α
μa μa' : Measure α
μb μb' : Measure β
μc : Measure γ
f✝ : α → β
s : Set α
f : α → α
hf : QuasiMeasurePreserving f
hs : f ⁻¹' s =ᵐ[μ] s
k : ℕ
ih : f^[k] ⁻¹' s =ᵐ[μ] s
⊢ f^[Nat.succ k] ⁻¹' s =ᵐ[μ] s Tactic: induction' k with k ih State Before: case succ
α : Type u_1
β : Type ?u.411803
γ : Type ?u.411806
δ : Type ?u.411809
ι : Type ?u.411812
R : Type ?u.411815
R' : Type ?u.411818
m0 : MeasurableSpace α
inst✝¹ : MeasurableSpace β
inst✝ : MeasurableSpace γ
μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : Measure α
s✝ s' t : Set α
μa μa' : Measure α
μb μb' : Measure β
μc : Measure γ
f✝ : α → β
s : Set α
f : α → α
hf : QuasiMeasurePreserving f
hs : f ⁻¹' s =ᵐ[μ] s
k : ℕ
ih : f^[k] ⁻¹' s =ᵐ[μ] s
⊢ f^[Nat.succ k] ⁻¹' s =ᵐ[μ] s State After: case succ
α : Type u_1
β : Type ?u.411803
γ : Type ?u.411806
δ : Type ?u.411809
ι : Type ?u.411812
R : Type ?u.411815
R' : Type ?u.411818
m0 : MeasurableSpace α
inst✝¹ : MeasurableSpace β
inst✝ : MeasurableSpace γ
μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : Measure α
s✝ s' t : Set α
μa μa' : Measure α
μb μb' : Measure β
μc : Measure γ
f✝ : α → β
s : Set α
f : α → α
hf : QuasiMeasurePreserving f
hs : f ⁻¹' s =ᵐ[μ] s
k : ℕ
ih : f^[k] ⁻¹' s =ᵐ[μ] s
⊢ f ⁻¹' (f^[k] ⁻¹' s) =ᵐ[μ] s Tactic: rw [iterate_succ, preimage_comp] State Before: case succ
α : Type u_1
β : Type ?u.411803
γ : Type ?u.411806
δ : Type ?u.411809
ι : Type ?u.411812
R : Type ?u.411815
R' : Type ?u.411818
m0 : MeasurableSpace α
inst✝¹ : MeasurableSpace β
inst✝ : MeasurableSpace γ
μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : Measure α
s✝ s' t : Set α
μa μa' : Measure α
μb μb' : Measure β
μc : Measure γ
f✝ : α → β
s : Set α
f : α → α
hf : QuasiMeasurePreserving f
hs : f ⁻¹' s =ᵐ[μ] s
k : ℕ
ih : f^[k] ⁻¹' s =ᵐ[μ] s
⊢ f ⁻¹' (f^[k] ⁻¹' s) =ᵐ[μ] s State After: no goals Tactic: exact EventuallyEq.trans (hf.preimage_ae_eq ih) hs State Before: case zero
α : Type u_1
β : Type ?u.411803
γ : Type ?u.411806
δ : Type ?u.411809
ι : Type ?u.411812
R : Type ?u.411815
R' : Type ?u.411818
m0 : MeasurableSpace α
inst✝¹ : MeasurableSpace β
inst✝ : MeasurableSpace γ
μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : Measure α
s✝ s' t : Set α
μa μa' : Measure α
μb μb' : Measure β
μc : Measure γ
f✝ : α → β
s : Set α
f : α → α
hf : QuasiMeasurePreserving f
hs : f ⁻¹' s =ᵐ[μ] s
⊢ f^[Nat.zero] ⁻¹' s =ᵐ[μ] s State After: no goals Tactic: rfl |
State Before: α : Type u_1
inst✝ : DecidableEq α
s✝ t✝ : Finset α
a b : α
n✝ : ℕ
m : Sym α n✝
s t : Finset α
n : ℕ
⊢ Finset.sym (s ∩ t) n = Finset.sym s n ∩ Finset.sym t n State After: case a
α : Type u_1
inst✝ : DecidableEq α
s✝ t✝ : Finset α
a b : α
n✝ : ℕ
m✝ : Sym α n✝
s t : Finset α
n : ℕ
m : Sym α n
⊢ m ∈ Finset.sym (s ∩ t) n ↔ m ∈ Finset.sym s n ∩ Finset.sym t n Tactic: ext m State Before: case a
α : Type u_1
inst✝ : DecidableEq α
s✝ t✝ : Finset α
a b : α
n✝ : ℕ
m✝ : Sym α n✝
s t : Finset α
n : ℕ
m : Sym α n
⊢ m ∈ Finset.sym (s ∩ t) n ↔ m ∈ Finset.sym s n ∩ Finset.sym t n State After: no goals Tactic: simp only [mem_inter, mem_sym_iff, imp_and, forall_and] |
lemma nonzero_inverse_scaleR_distrib: "a \<noteq> 0 \<Longrightarrow> x \<noteq> 0 \<Longrightarrow> inverse (scaleR a x) = scaleR (inverse a) (inverse x)" for x :: "'a::real_div_algebra" |
[STATEMENT]
lemma eqButUID12_not_UID:
"\<lbrakk>eqButUID12 freq freq1; \<not> (uid,uid') \<in> {(UID1,UID2), (UID2,UID1)}\<rbrakk> \<Longrightarrow> freq uid uid' = freq1 uid uid'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>eqButUID12 freq freq1; (uid, uid') \<notin> {(UID1, UID2), (UID2, UID1)}\<rbrakk> \<Longrightarrow> freq uid uid' = freq1 uid uid'
[PROOF STEP]
unfolding eqButUID12_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>\<forall>uid uid'. if (uid, uid') \<in> {(UID1, UID2), (UID2, UID1)} then True else freq uid uid' = freq1 uid uid'; (uid, uid') \<notin> {(UID1, UID2), (UID2, UID1)}\<rbrakk> \<Longrightarrow> freq uid uid' = freq1 uid uid'
[PROOF STEP]
by (auto split: if_splits) |
module Gadgil.Ass1
import Evens
-- name your module as above
data IsOdd : Nat -> Type where
OneOdd : IsOdd 1
SSOdd : (n: Nat) -> IsOdd n -> IsOdd (S (S n))
notOddZ : IsOdd Z -> Void
notOddZ OneOdd impossible
notOddZ (SSOdd _ _) impossible
notOdd2: IsOdd 2 -> Void
notOdd2 (SSOdd Z OneOdd) impossible
notOdd2 (SSOdd Z (SSOdd _ _)) impossible
evenS : (n: Nat) -> IsEven n -> IsOdd (S n)
evenS Z ZEven = OneOdd
evenS (S (S k)) (SSEven k x) = SSOdd (S k) (evenS k x)
|
State Before: F : Type ?u.24201
α : Type u_2
β : Type u_1
γ : Type ?u.24210
inst✝³ : LinearOrderedField α
inst✝² : ConditionallyCompleteLinearOrderedField β
inst✝¹ : ConditionallyCompleteLinearOrderedField γ
inst✝ : Archimedean α
a : α
b : β
q : ℚ
x y : α
⊢ inducedMap α β (x + y) = inducedMap α β x + inducedMap α β y State After: F : Type ?u.24201
α : Type u_2
β : Type u_1
γ : Type ?u.24210
inst✝³ : LinearOrderedField α
inst✝² : ConditionallyCompleteLinearOrderedField β
inst✝¹ : ConditionallyCompleteLinearOrderedField γ
inst✝ : Archimedean α
a : α
b : β
q : ℚ
x y : α
⊢ sSup (cutMap β x + cutMap β y) = inducedMap α β x + inducedMap α β y Tactic: rw [inducedMap, cutMap_add] State Before: F : Type ?u.24201
α : Type u_2
β : Type u_1
γ : Type ?u.24210
inst✝³ : LinearOrderedField α
inst✝² : ConditionallyCompleteLinearOrderedField β
inst✝¹ : ConditionallyCompleteLinearOrderedField γ
inst✝ : Archimedean α
a : α
b : β
q : ℚ
x y : α
⊢ sSup (cutMap β x + cutMap β y) = inducedMap α β x + inducedMap α β y State After: no goals Tactic: exact csSup_add (cutMap_nonempty β x) (cutMap_bddAbove β x) (cutMap_nonempty β y)
(cutMap_bddAbove β y) |
= Architecture of the Song dynasty =
|
is_left_unit := (A::set) -> proc(m,e) local a;
`and`(seq(evalb(m(e,a)=a),a in A)); end:
is_right_unit := (A::set) -> proc(m,e) local a;
`and`(seq(evalb(m(a,e)=a),a in A)); end:
is_left_absorbing := (A::set) -> proc(m,z) local a;
`and`(seq(evalb(m(z,a)=z),a in A)); end:
is_right_absorbing := (A::set) -> proc(m,z) local a;
`and`(seq(evalb(m(a,z)=z),a in A)); end:
is_idempotent := (A::set) -> proc(m) local a;
`and`(seq(evalb(m(a,a)=a),a in A)); end:
is_commutative := (A::set) -> proc(m) local a,b;
`and`(seq(seq(evalb(m(a,b) = m(b,a)),b in A),a in A)); end:
is_associative := (A::set) -> proc(m) local a,b,c;
`and`(seq(seq(seq(evalb(m(a,m(b,c))=m(m(a,b),c)),c in A),b in A),a in A)); end:
is_left_distributive := (A::set) -> proc(m,p) local a,b,c;
`and`(seq(seq(seq(evalb(m(a,p(b,c))=p(m(a,b),m(a,c))),c in A),b in A),a in A)); end:
is_right_distributive := (A::set) -> proc(m,p) local a,b,c;
`and`(seq(seq(seq(evalb(m(p(a,b),c)=p(m(a,c),m(b,c))),c in A),b in A),a in A)); end:
is_monoid := (A::set) -> proc(m,e)
is_left_unit(A)(m,e) and is_right_unit(A)(m,e) and is_associative(A)(m); end:
is_semiring := (A::set) -> (m,p,e,z) ->
is_monoid(A)(m,e) and
is_monoid(A)(p,z) and
is_left_absorbing(A)(m,z) and
is_right_absorbing(A)(m,z) and
is_left_distributive(A)(m,p) and
is_right_distributive(A)(m,p);
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.