/-
Copyright (c) 2019 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis, Floris van Doorn
-/
import data.option.defs
import data.string.defs
import tactic.derive_inhabited
/-!
# Additional operations on expr and related types

This file defines basic operations on the types expr, name, declaration, level, environment.

This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.

## Tags

expr, name, declaration, level, environment, meta, metaprogramming, tactic
-/

open tactic

attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind

namespace binder_info

/-! ### Declarations about `binder_info` -/

instance : inhabited binder_info := ⟨ binder_info.default ⟩

/-- The brackets corresponding to a given binder_info. -/
def brackets : binder_info → string × string
| binder_info.implicit        := ("{", "}")
| binder_info.strict_implicit := ("{{", "}}")
| binder_info.inst_implicit   := ("[", "]")
| _                           := ("(", ")")

end binder_info

namespace name

/-! ### Declarations about `name` -/

/-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix
with the value of `f n`. -/
def map_prefix (f : name → option name) : name → name
| anonymous := anonymous
| (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n')
| (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n')

/-- If `nm` is a simple name (having only one string component) starting with `_`, then
`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/
meta def deinternalize_field : name → name
| (mk_string s name.anonymous) :=
  let i := s.mk_iterator in
  if i.curr = '_' then i.next.next_to_string else s
| n := n

/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/
meta def get_nth_prefix : name → ℕ → name
| nm 0 := nm
| nm (n + 1) := get_nth_prefix nm.get_prefix n

/-- Auxiliary definition for `pop_nth_prefix` -/
private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ
| anonymous n := (anonymous, 1)
| nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in
          if height ≤ n then (anonymous, height + 1)
          else (nm.update_prefix pfx, height + 1)

/-- Pops the top `n` prefixes from the given name. -/
meta def pop_nth_prefix (nm : name) (n : ℕ) : name :=
prod.fst $ pop_nth_prefix_aux nm n

/-- Pop the prefix of a name -/
meta def pop_prefix (n : name) : name :=
pop_nth_prefix n 1

/-- Auxiliary definition for `from_components` -/
private def from_components_aux : name → list string → name
| n [] := n
| n (s :: rest) := from_components_aux (name.mk_string s n) rest

/-- Build a name from components. For example `from_components ["foo","bar"]` becomes
  ``` `foo.bar``` -/
def from_components : list string → name :=
from_components_aux name.anonymous

/-- `name`s can contain numeral pieces, which are not legal names
  when typed/passed directly to the parser. We turn an arbitrary
  name into a legal identifier name by turning the numbers to strings. -/
meta def sanitize_name : name → name
| name.anonymous := name.anonymous
| (name.mk_string s p) := name.mk_string s $ sanitize_name p
| (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p

/-- Append a string to the last component of a name. -/
def append_suffix : name → string → name
| (mk_string s n) s' := mk_string (s ++ s') n
| n _ := n

/-- Update the last component of a name. -/
def update_last (f : string → string) : name → name
| (mk_string s n) := mk_string (f s) n
| n := n

/-- `append_to_last nm s is_prefix` adds `s` to the last component of `nm`,
  either as prefix or as suffix (specified by `is_prefix`), separated by `_`.
  Used by `simps_add_projections`. -/
def append_to_last (nm : name) (s : string) (is_prefix : bool) : name :=
nm.update_last $ λ s', if is_prefix then s ++ "_" ++ s' else s' ++ "_" ++ s

/-- The first component of a name, turning a number to a string -/
meta def head : name → string
| (mk_string s anonymous) := s
| (mk_string s p)         := head p
| (mk_numeral n p)        := head p
| anonymous               := "[anonymous]"

/-- Tests whether the first component of a name is `"_private"` -/
meta def is_private (n : name) : bool :=
n.head = "_private"

/-- Returns the number of characters used to print all the string components of a name,
  including periods between name segments. Ignores numerical parts of a name. -/
meta def length : name → ℕ
| (mk_string s anonymous) := s.length
| (mk_string s p)         := s.length + 1 + p.length
| (mk_numeral n p)        := p.length
| anonymous               := "[anonymous]".length

/-- Checks whether `nm` has a prefix (including itself) such that P is true -/
def has_prefix (P : name → bool) : name → bool
| anonymous := ff
| (mk_string s nm)  := P (mk_string s nm) ∨ has_prefix nm
| (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm

/-- Appends `'` to the end of a name. -/
meta def add_prime : name → name
| (name.mk_string s p) := name.mk_string (s ++ "'") p
| n := (name.mk_string "x'" n)

/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.
For example, ``last_string `a.b.c.33`` will return `` `c ``. -/
def last_string : name → string
| anonymous        := "[anonymous]"
| (mk_string s _)  := s
| (mk_numeral _ n) := last_string n

/-- Like `++`, except that if the right argument starts with `_root_` the namespace will be
ignored.
```
append_namespace `a.b `c.d = `a.b.c.d
append_namespace `a.b `_root_.c.d = `c.d
```
-/
meta def append_namespace (ns : name) : name → name
| (mk_string s anonymous) := if s = "_root_" then anonymous else mk_string s ns
| (mk_string s p)         := mk_string s (append_namespace p)
| (mk_numeral n p)        := mk_numeral n (append_namespace p)
| anonymous               := ns

/--
Constructs a (non-simple) name from a string.

Example: ``name.from_string "foo.bar" = `foo.bar``
-/
meta def from_string (s : string) : name :=
from_components $ s.split (= '.')

/--
In surface Lean, we can write anonymous Π binders (i.e. binders where the
argument is not named) using the function arrow notation:

```lean
inductive test : Type
| intro : unit → test
```

After elaboration, however, every binder must have a name, so Lean generates
one. In the example, the binder in the type of `intro` is anonymous, so Lean
gives it the name `ᾰ`:

```lean
test.intro : ∀ (ᾰ : unit), test
```

When there are multiple anonymous binders, they are named `ᾰ_1`, `ᾰ_2` etc.

Thus, when we want to know whether the user named a binder, we can check whether
the name follows this scheme. Note, however, that this is not reliable. When the
user writes (for whatever reason)

```lean
inductive test : Type
| intro : ∀ (ᾰ : unit), test
```

we cannot tell that the binder was, in fact, named.

The function `name.is_likely_generated_binder_name` checks if
a name is of the form `ᾰ`, `ᾰ_1`, etc.
-/
library_note "likely generated binder names"

/--
Check whether a simple name was likely generated by Lean to name an anonymous
binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See
note [likely generated binder names].
-/
meta def is_likely_generated_binder_simple_name : string → bool
| "ᾰ" := tt
| n :=
  match n.get_rest "ᾰ_" with
  | none := ff
  | some suffix := suffix.is_nat
  end

/--
Check whether a name was likely generated by Lean to name an anonymous binder.
Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See
note [likely generated binder names].
-/
meta def is_likely_generated_binder_name (n : name) : bool :=
match n with
| mk_string s anonymous := is_likely_generated_binder_simple_name s
| _ := ff
end

end name

namespace level

/-! ### Declarations about `level` -/

/-- Tests whether a universe level is non-zero for all assignments of its variables -/
meta def nonzero : level → bool
| (succ _) := tt
| (max l₁ l₂) := l₁.nonzero || l₂.nonzero
| (imax _ l₂) := l₂.nonzero
| _ := ff

/--
`l.fold_mvar f` folds a function `f : name → α → α`
over each `n : name` appearing in a `level.mvar n` in `l`.
-/
meta def fold_mvar {α} : level → (name → α → α) → α → α
| zero f := id
| (succ a) f := fold_mvar a f
| (param a) f := id
| (mvar a) f := f a
| (max a b) f := fold_mvar a f ∘ fold_mvar b f
| (imax a b) f := fold_mvar a f ∘ fold_mvar b f

/--
`l.params` is the set of parameters occuring in `l`.
For example if `l = max 1 (max (u+1) (max v w))` then `l.params = {u, v, w}`.
-/
protected meta def params (u : level) : name_set :=
u.fold mk_name_set $ λ v l,
  match v with
  | (param nm) := l.insert nm
  | _ := l
  end

end level

/-! ### Declarations about `binder` -/

/-- The type of binders containing a name, the binding info and the binding type -/
@[derive decidable_eq, derive inhabited]
meta structure binder :=
  (name : name)
  (info : binder_info)
  (type : expr)

namespace binder
/-- Turn a binder into a string. Uses expr.to_string for the type. -/
protected meta def to_string (b : binder) : string :=
let (l, r) := b.info.brackets in
l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r

meta instance : has_to_string binder := ⟨ binder.to_string ⟩
meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩
meta instance : has_to_tactic_format binder :=
⟨ λ b, let (l, r) := b.info.brackets in
  (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩

end binder

/-!
### Converting between expressions and numerals

There are a number of ways to convert between expressions and numerals, depending on the input and
output types and whether you want to infer the necessary type classes.

See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.
-/

/--
`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.
`type`: an expression representing the target type. This must live in Type 0.
`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.
 -/
meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr :=
let z : expr := `(@has_zero.zero.{0} %%type %%has_zero),
    o : expr := `(@has_one.one.{0} %%type %%has_one) in
nat.binary_rec z
  (λ b n e, if n = 0 then o else
    if b then `(@bit1.{0} %%type %%has_one %%has_add %%e)
    else `(@bit0.{0} %%type %%has_add %%e))

/--
`int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.
`type`: an expression representing the target type. This must live in Type 0.
`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.
 -/
meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr
| (int.of_nat n) := n.mk_numeral type has_zero has_one has_add
| -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in
            `(@has_neg.neg.{0} %%type %%has_neg %%ne)

/--
`nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.
The `pexpr` does not hold any typing information:
`to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`.
-/
meta def nat.to_pexpr : ℕ → pexpr
| 0 := ``(0)
| 1 := ``(1)
| n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2)))

/--
`int.to_pexpr n` creates a `pexpr` that will evaluate to `n`.
The `pexpr` does not hold any typing information:
`to_expr ``((%%(int.to_pexpr (-5)) : ℚ))` will create a native `ℚ` numeral `(-5 : ℚ)`.
-/
meta def int.to_pexpr : ℤ → pexpr
| (int.of_nat k) := k.to_pexpr
| (int.neg_succ_of_nat k) := ``(-%%((k+1).to_pexpr))

namespace expr

/--
Turns an expression into a natural number, assuming it is only built up from
`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.
-/
protected meta def to_nat : expr → option ℕ
| `(has_zero.zero) := some 0
| `(has_one.one) := some 1
| `(bit0 %%e) := bit0 <$> e.to_nat
| `(bit1 %%e) := bit1 <$> e.to_nat
| `(nat.succ %%e) := (+1) <$> e.to_nat
| `(nat.zero) := some 0
| _ := none

/--
Turns an expression into a integer, assuming it is only built up from
`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.
-/
protected meta def to_int : expr → option ℤ
| `(has_neg.neg %%e) := do n ← e.to_nat, some (-n)
| e                  := coe <$> e.to_nat

/--
Turns an expression into a list, assuming it is only built up from `list.nil` and `list.cons`.
-/
protected meta def to_list {α} (f : expr → option α) : expr → option (list α)
| `(list.nil)          := some []
| `(list.cons %%x %%l) := list.cons <$> f x <*> l.to_list
| _                    := none

/--
`is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,
ignoring differences in type and type class arguments.
-/
meta def is_num_eq : expr → expr → bool
| `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt
| `(@has_one.one _ _) `(@has_one.one _ _) := tt
| `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b
| `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b
| `(-%%a) `(-%%b) := a.is_num_eq b
| `(%%a/%%a') `(%%b/%%b') :=  a.is_num_eq b
| _ _ := ff

end expr

/-! ### Declarations about `pexpr` -/

namespace pexpr

/--
If `e` is an annotation of `frozen_name` to `expr.const n`,
`e.get_frozen_name` returns `n`.
Otherwise, returns `name.anonymous`.
-/
meta def get_frozen_name (e : pexpr) : name :=
match e.is_annotation with
| some (`frozen_name, expr.const n _) := n
| _ := name.anonymous
end

/--
If `e : pexpr` is a sequence of applications `f e₁ e₂ ... eₙ`,
`e.get_app_fn_args` returns `(f, [e₁, ... eₙ])`.
See also `expr.get_app_fn_args`.
-/
meta def get_app_fn_args : pexpr → opt_param (list pexpr) [] → pexpr × list pexpr
| (expr.app e1 e2) r := get_app_fn_args e1 (e2::r)
| e1 r := (e1, r)

/--
If `e : pexpr` is a sequence of applications `f e₁ e₂ ... eₙ`,
`e.get_app_fn` returns `f`.
See also `expr.get_app_fn`.
-/
meta def get_app_fn : pexpr → list pexpr :=
prod.snd ∘ get_app_fn_args

/--
If `e : pexpr` is a sequence of applications `f e₁ e₂ ... eₙ`,
`e.get_app_args` returns `[e₁, ... eₙ]`.
See also `expr.get_app_args`.
-/
meta def get_app_args : pexpr → list pexpr :=
prod.snd ∘ get_app_fn_args

end pexpr

/-! ### Declarations about `expr` -/

namespace expr

/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/
meta def clean_ids : list name :=
[``id, ``id_rhs, ``id_delta, ``hidden]

/-- Clean an expression by removing `id`s listed in `clean_ids`. -/
meta def clean (e : expr) : expr :=
e.replace (λ e n,
     match e with
     | (app (app (const n _) _) e') :=
       if n ∈ clean_ids then some e' else none
     | (app (lam _ _ _ (var 0)) e') := some e'
     | _ := none
     end)

/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/
meta def replace_with (e : expr) (s : expr) (s' : expr) : expr :=
e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none

/-- Implementation of `expr.mreplace`. -/
meta def mreplace_aux {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) :
  expr → ℕ → m expr
| (app f x) n := option.mget_or_else (R (app f x) n)
  (do Rf ← mreplace_aux f n, Rx ← mreplace_aux x n, return $ app Rf Rx)
| (lam nm bi ty bd) n := option.mget_or_else (R (lam nm bi ty bd) n)
  (do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ lam nm bi Rty Rbd)
| (pi nm bi ty bd) n := option.mget_or_else (R (pi nm bi ty bd) n)
  (do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ pi nm bi Rty Rbd)
| (elet nm ty a b) n := option.mget_or_else (R (elet nm ty a b) n)
  (do Rty ← mreplace_aux ty n,
    Ra ← mreplace_aux a n,
    Rb ← mreplace_aux b n,
    return $ elet nm Rty Ra Rb)
| (macro c es) n := option.mget_or_else (R (macro c es) n) $
    macro c <$> es.mmap (λ e, mreplace_aux e n)
| e n := option.mget_or_else (R e n) (return e)

/--
Monadic analogue of `expr.replace`.

The `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where
`n` is the number of binders above `e`.
If `R s n` fails, the whole replacement fails.
If `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit
its subexpressions).
If `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`.

WARNING: This function performs exponentially worse on large terms than `expr.replace`,
if a subexpression occurs more than once in an expression, `expr.replace` visits them only once,
but this function will visit every occurence of it. Do not use this on large expressions.
-/
meta def mreplace {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) (e : expr) :
  m expr :=
mreplace_aux R e 0

/-- Match a variable. -/
meta def match_var {elab} : expr elab → option ℕ
| (var n) := some n
| _ := none

/-- Match a sort. -/
meta def match_sort {elab} : expr elab → option level
| (sort u) := some u
| _ := none

/-- Match a constant. -/
meta def match_const {elab} : expr elab → option (name × list level)
| (const n lvls) := some (n, lvls)
| _ := none

/-- Match a metavariable. -/
meta def match_mvar {elab} : expr elab →
  option (name × name × expr elab)
| (mvar unique pretty type) := some (unique, pretty, type)
| _ := none

/-- Match a local constant. -/
meta def match_local_const {elab} : expr elab →
  option (name × name × binder_info × expr elab)
| (local_const unique pretty bi type) := some (unique, pretty, bi, type)
| _ := none

/-- Match an application. -/
meta def match_app {elab} : expr elab → option (expr elab × expr elab)
| (app t u) := some (t, u)
| _ := none

/-- Match an application of `coe_fn`. -/
meta def match_app_coe_fn : expr → option (expr × expr × expr × expr × expr)
| (app `(@coe_fn %%α %%β %%inst %%fexpr) x) := some (α, β, inst, fexpr, x)
| _ := none

/-- Match an abstraction. -/
meta def match_lam {elab} : expr elab →
  option (name × binder_info × expr elab × expr elab)
| (lam var_name bi type body) := some (var_name, bi, type, body)
| _ := none

/-- Match a Π type. -/
meta def match_pi {elab} : expr elab →
  option (name × binder_info × expr elab × expr elab)
| (pi var_name bi type body) := some (var_name, bi, type, body)
| _ := none

/-- Match a let. -/
meta def match_elet {elab} : expr elab →
  option (name × expr elab × expr elab × expr elab)
| (elet var_name type assignment body) := some (var_name, type, assignment, body)
| _ := none

/-- Match a macro. -/
meta def match_macro {elab} : expr elab →
  option (macro_def × list (expr elab))
| (macro df args) := some (df, args)
| _ := none

/-- Tests whether an expression is a meta-variable. -/
meta def is_mvar : expr → bool
| (mvar _ _ _) := tt
| _            := ff

/-- Tests whether an expression is a sort. -/
meta def is_sort : expr → bool
| (sort _) := tt
| e         := ff

/-- Get the universe levels of a `const` expression -/
meta def univ_levels : expr → list level
| (const n ls) := ls
| _            := []

/--
Replace any metavariables in the expression with underscores, in preparation for printing
`refine ...` statements.
-/
meta def replace_mvars (e : expr) : expr :=
e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none)

/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to
 `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/
meta def to_implicit_local_const : expr → expr
| (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t
| e := e

/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder
info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants.
-/
meta def to_implicit_binder : expr → expr
| (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d
| (lam n _ d b) := lam n binder_info.implicit d b
| (pi n _ d b) := pi n binder_info.implicit d b
| e  := e

/-- Returns a list of all local constants in an expression (without duplicates). -/
meta def list_local_consts (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es)

/-- Returns the set of all local constants in an expression. -/
meta def list_local_consts' (e : expr) : expr_set :=
e.fold mk_expr_set (λ e' _ es, if e'.is_local_constant then es.insert e' else es)

/-- Returns the unique names of all local constants in an expression. -/
meta def list_local_const_unique_names (e : expr) : name_set :=
e.fold mk_name_set
  (λ e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name else es)

/-- Returns a `name_set` of all constants in an expression. -/
meta def list_constant (e : expr) : name_set :=
e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es)

/-- Returns a `list name` containing the constant names of an `expr` in the same order
  that `expr.fold` traverses it. -/
meta def list_constant' (e : expr) : list name :=
(e.fold [] (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es)).reverse

/-- Returns a list of all meta-variables in an expression (without duplicates). -/
meta def list_meta_vars (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es)

/-- Returns the set of all meta-variables in an expression. -/
meta def list_meta_vars' (e : expr) : expr_set :=
e.fold mk_expr_set (λ e' _ es, if e'.is_mvar then es.insert e' else es)

/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/
meta def list_univ_meta_vars (e : expr) : list name :=
native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s,
match e' with
| (sort u) := u.fold_mvar (flip native.rb_set.insert) s
| (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s
| _ := s
end

/--
Test `t` contains the specified subexpression `e`, or a metavariable.
This represents the notion that `e` "may occur" in `t`,
possibly after subsequent unification.
-/
meta def contains_expr_or_mvar (t : expr) (e : expr) : bool :=
-- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.
¬ t.list_meta_vars.empty ∨ e.occurs t

/-- Returns a `name_set` of all constants in an expression starting with a certain prefix. -/
meta def list_names_with_prefix (pre : name) (e : expr) : name_set :=
e.fold mk_name_set $ λ e' _ l,
  match e' with
  | expr.const n _ := if n.get_prefix = pre then l.insert n else l
  | _ := l
  end

/-- Returns true if `e` contains a name `n` where `p n` is true.
  Returns `true` if `p name.anonymous` is true. -/
meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool :=
e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b)

/--
Returns true if `e` contains a `sorry`.
See also `name.contains_sorry`.
-/
meta def contains_sorry (e : expr) : bool :=
e.fold ff (λ e' _ b, if (is_sorry e').is_some then tt else b)

/--
`app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.
-/
meta def app_symbol_in (e : expr) (l : list name) : bool :=
match e.get_app_fn with
| (expr.const n _) := n ∈ l
| _ := ff
end

/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/
meta def get_simp_args (e : expr) : tactic (list expr) :=
-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app
if ¬ e.is_app then pure [] else do
cgr ← mk_specialized_congr_lemma_simp e,
pure $ do
  (arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args,
  guard $ arg_kind = congr_arg_kind.eq,
  pure arg

/-- Simplifies the expression `t` with the specified options.
  The result is `(new_e, pr)` with the new expression `new_e` and a proof
  `pr : e = new_e`. -/
meta def simp (t : expr)
  (cfg : simp_config := {}) (discharger : tactic unit := failed)
  (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :
  tactic (expr × expr × name_set) :=
do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs,
   simplify s to_unfold t cfg `eq discharger

/-- Definitionally simplifies the expression `t` with the specified options.
  The result is the simplified expression. -/
meta def dsimp (t : expr)
  (cfg : dsimp_config := {})
  (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :
  tactic expr :=
do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs,
   s.dsimplify to_unfold t cfg

/-- Get the names of the bound variables by a sequence of pis or lambdas. -/
meta def binding_names : expr → list name
| (pi n _ _ e)  := n :: e.binding_names
| (lam n _ _ e) := n :: e.binding_names
| e             := []

/-- head-reduce a single let expression -/
meta def reduce_let : expr → expr
| (elet _ _ v b) := b.instantiate_var v
| e              := e

/-- head-reduce all let expressions -/
meta def reduce_lets : expr → expr
| (elet _ _ v b) := reduce_lets $ b.instantiate_var v
| e              := e

/-- Instantiate lambdas in the second argument by expressions from the first. -/
meta def instantiate_lambdas : list expr → expr → expr
| (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e')
| _        e              := e

/-- Repeatedly apply `expr.subst`. -/
meta def substs : expr → list expr → expr | e es := es.foldl expr.subst e

/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.
If the length of `es` is larger than the number of lambdas in `e`,
then the term is applied to the remaining terms.
Also reduces head let-expressions in `e`, including those after instantiating all lambdas.

This is very similar to `expr.substs`, but this also reduces head let-expressions. -/
meta def instantiate_lambdas_or_apps : list expr → expr → expr
| (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v
| es      (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v
| es      e              := mk_app e es

/--
Some declarations work with open expressions, i.e. an expr that has free variables.
Terms will free variables are not well-typed, and one should not use them in tactics like
`infer_type` or `unify`. You can still do syntactic analysis/manipulation on them.
The reason for working with open types is for performance: instantiating variables requires
iterating through the expression. In one performance test `pi_binders` was more than 6x
quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x).
-/
library_note "open expressions"

/-- Get the codomain/target of a pi-type.
  This definition doesn't instantiate bound variables, and therefore produces a term that is open.
  See note [open expressions]. -/
meta def pi_codomain : expr → expr
| (pi n bi d b) := pi_codomain b
| e             := e

/-- Get the body/value of a lambda-expression.
  This definition doesn't instantiate bound variables, and therefore produces a term that is open.
  See note [open expressions]. -/
meta def lambda_body : expr → expr
| (lam n bi d b) := lambda_body b
| e             := e

/-- Auxiliary defintion for `pi_binders`.
  See note [open expressions]. -/
meta def pi_binders_aux : list binder → expr → list binder × expr
| es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b
| es e             := (es, e)

/-- Get the binders and codomain of a pi-type.
  This definition doesn't instantiate bound variables, and therefore produces a term that is open.
  The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the
  free variables.
  See note [open expressions]. -/
meta def pi_binders (e : expr) : list binder × expr :=
let (es, e) := pi_binders_aux [] e in (es.reverse, e)

/-- Auxiliary defintion for `get_app_fn_args`. -/
meta def get_app_fn_args_aux : list expr → expr → expr × list expr
| r (app f a) := get_app_fn_args_aux (a::r) f
| r e         := (e, r)

/-- A combination of `get_app_fn` and `get_app_args`: lists both the
  function and its arguments of an application -/
meta def get_app_fn_args : expr → expr × list expr :=
get_app_fn_args_aux []

/-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/
meta def drop_pis : list expr → expr → tactic expr
| (v :: vs) (pi n bi d b) := do
  t ← infer_type v,
  guard (t =ₐ d),
  drop_pis vs (b.instantiate_var v)
| [] e := return e
| _  _ := failed

/-- `instantiate_pis es e` instantiates the pis in `e` with the expressions from `es`.
  Does not check whether the result remains type-correct. -/
meta def instantiate_pis : list expr → expr → expr
| (v :: vs) (pi n bi d b) := instantiate_pis vs (b.instantiate_var v)
| _ e := e

/-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`.
  Returns `empty` if the list is empty. -/
meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr
| []        := empty
| [e]       := e
| (e :: es) := op e $ mk_op_lst es

/-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/
meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true)

/-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/
meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false)

/-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant.
Otherwise returns `binder_info.default`. -/
meta def local_binding_info : expr → binder_info
| (expr.local_const _ _ bi _) := bi
| _ := binder_info.default

/-- `is_default_local e` tests whether `e` is a local constant with binder info
`binder_info.default` -/
meta def is_default_local : expr → bool
| (expr.local_const _ _ binder_info.default _) := tt
| _ := ff

/-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/
meta def has_local_constant (e l : expr) : bool :=
e.has_local_in $ mk_name_set.insert l.local_uniq_name

/-- Turns a local constant into a binder -/
meta def to_binder : expr → binder
| (local_const _ nm bi t) := ⟨nm, bi, t⟩
| _                       := default

/-- Strip-away the context-dependent unique id for the given local const and return: its friendly
`name`, its `binder_info`, and its `type : expr`. -/
meta def get_local_const_kind : expr → name × binder_info × expr
| (expr.local_const _ n bi e) := (n, bi, e)
| _ := (name.anonymous, binder_info.default, expr.const name.anonymous [])

/-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/
meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab
| (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t
| e                           new_t := e

/-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to
access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to
`expr tt` at the site of definition unnecessarily.

DANGER: Unless you know exactly what you are doing, this is probably not the function you are
looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/
meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast

/-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as
a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever
`f` is encountered in `e` verbatim, replace it with `t`". -/
meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) :
  expr elab :=
unsafe_cast $ e.unsafe_cast.replace $ λ e n,
  (mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd

/-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of
    other `expr.local_const`s. It determines whether `e` should be considered "available in context"
    as a variable by virtue of the fact that the variables `vs` have been deemed such.

    For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that
    the typeclass instance `prime n` should be included, but `ih : even n` should not.

    DANGER: It is possible that for `f : expr` another `expr.local_const`, we have
    `is_implicitly_included_variable f vs = ff` but
    `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to
    iteratively add a list of local constants (usually, the `variables` declared in the local scope)
    which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables
    were added in a particular iteration. The function `all_implicitly_included_variables` below
    implements this behaviour.

    Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/
meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool :=
if ¬(e.local_pp_name.to_string.starts_with "_") then
  e ∈ vs
else e.local_type.fold tt $ λ se _ b,
  if ¬b then ff
  else if ¬se.is_local_constant then tt
  else se ∈ vs

/-- Private work function for `all_implicitly_included_variables`, performing the actual series of
    iterations, tracking with a boolean whether any updates occured this iteration. -/
private meta def all_implicitly_included_variables_aux
  : list expr → list expr → list expr → bool → list expr
| []          vs rs tt := all_implicitly_included_variables_aux rs vs [] ff
| []          vs rs ff := vs
| (e :: rest) vs rs b :=
  let (vs, rs, b) :=
    if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in
  all_implicitly_included_variables_aux rest vs rs b

/-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`,
    another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion
    of the variables in `vs` into the local context implies that `e` should also be included. See
    `is_implicitly_included_variable e vs` for the details.

    In particular, those elements of `vs` are included automatically. -/
meta def all_implicitly_included_variables (es vs : list expr) : list expr :=
all_implicitly_included_variables_aux es vs [] ff

/-- Get the list of explicit arguments of a function. -/
meta def list_explicit_args (f : expr) : tactic (list expr) :=
tactic.fold_explicit_args f [] (λ ll e, return $ ll ++ [e])

/--  `replace_explicit_args f parg` assumes that `f` is an expression corresponding to a function
application.  It replaces the explicit arguments of `f`, in succession, by the elements of `parg`.
The implicit arguments of `f` remain unchanged. -/
meta def replace_explicit_args (f : expr) (parg : list expr) : tactic expr :=
do finf ← (get_fun_info f.get_app_fn),
  let is_ex_arg : list bool := finf.params.map (λ e, ¬ e.is_implicit ∧ ¬ e.is_inst_implicit),
  let nargs := list.replace_if f.get_app_args is_ex_arg parg,
  return $ expr.mk_app f.get_app_fn nargs

/-- Infer the type of an application of the form `f x1 x2 ... xn`, where `f` is an identifier.
This also works if `x1, ... xn` contain free variables. -/
protected meta def simple_infer_type (env : environment) (e : expr) : exceptional expr := do
(@const tt n ls, es) ← return e.get_app_fn_args |
  exceptional.fail "expression is not a constant applied to arguments",
d ← env.get n,
return $ (d.type.instantiate_pis es).instantiate_univ_params $ d.univ_params.zip ls

/-- Auxilliary function for `head_eta_expand`. -/
meta def head_eta_expand_aux : ℕ → expr → expr → expr
| (n+1) e (pi x bi d b) :=
  lam x bi d $ head_eta_expand_aux n e b
| _ e _ := e

/-- `head_eta_expand n e t` eta-expands `e` `n` times, with the binders info and domains obtained
  by its type `t`. -/
meta def head_eta_expand (n : ℕ) (e t : expr) : expr :=
((e.lift_vars 0 n).mk_app $ (list.range n).reverse.map var).head_eta_expand_aux n t

/-- `e.eta_expand env dict` eta-expands all expressions that have as head a constant `n` in
`dict`. They are expanded until they are applied to one more argument than the maximum in
`dict.find n`. -/
protected meta def eta_expand (env : environment) (dict : name_map $ list ℕ) : expr → expr
| e := e.replace $ λ e _, do
  let (e0, es) := e.get_app_fn_args,
  let ns := (dict.find e0.const_name).iget,
  guard (bnot ns.empty),
  let e' := e0.mk_app $ es.map eta_expand,
  let needed_n := ns.foldr max 0 + 1,
  if needed_n ≤ es.length then some e'
  else do
    e'_type ← (e'.simple_infer_type env).to_option,
    some $ head_eta_expand (needed_n - es.length) e' e'_type

/--
`e.apply_replacement_fun f test` applies `f` to each identifier
(inductive type, defined function etc) in an expression, unless
* The identifier occurs in an application with first argument `arg`; and
* `test arg` is false.
However, if `f` is in the dictionary `relevant`, then the argument `relevant.find f`
is tested, instead of the first argument.

Reorder contains the information about what arguments to reorder:
e.g. `g x₁ x₂ x₃ ... xₙ` becomes `g x₂ x₁ x₃ ... xₙ` if `reorder.find g = some [1]`.
We assume that all functions where we want to reorder arguments are fully applied.
This can be done by applying `expr.eta_expand` first.
-/
protected meta def apply_replacement_fun (f : name → name) (test : expr → bool)
  (relevant : name_map ℕ) (reorder : name_map $ list ℕ) : expr → expr
| e := e.replace $ λ e _,
  match e with
  | const n ls := some $ const (f n) $
      -- if the first two arguments are reordered, we also reorder the first two universe parameters
      if 1 ∈ (reorder.find n).iget then ls.inth 1::ls.head::ls.drop 2 else ls
  | app g x :=
    let f := g.get_app_fn,
        nm := f.const_name,
        n_args := g.get_app_num_args in -- this might be inefficient
    if n_args ∈ (reorder.find nm).iget ∧ test g.get_app_args.head then
    -- interchange `x` and the last argument of `g`
    some $ apply_replacement_fun g.app_fn (apply_replacement_fun x) $
      apply_replacement_fun g.app_arg else
    if n_args = (relevant.find nm).lhoare 0 ∧ f.is_constant ∧ ¬ test x then
      some $ (f.mk_app $ g.get_app_args.map apply_replacement_fun) (apply_replacement_fun x) else
      none
  | _ := none
  end

end expr

/-! ### Declarations about `environment` -/

namespace environment

/-- Tests whether `n` is a structure. -/
meta def is_structure (env : environment) (n : name) : bool :=
(env.structure_fields n).is_some

/-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a
  structure. -/
meta def structure_fields_full (env : environment) (n : name) : option (list name) :=
(env.structure_fields n).map (list.map $ λ n', n ++ n')

/-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type.
  Note that `is_ginductive` returns `tt` even on regular inductive types.
  This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive
  type. -/
meta def is_ginductive' (e : environment) (nm : name) : bool :=
e.is_ginductive nm ∧ ¬ e.is_inductive nm

/-- For all declarations `d` where `f d = some x` this adds `x` to the returned list.  -/
meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α :=
  e.fold [] $ λ d l, match f d with
                     | some r := r :: l
                     | none := l
                     end

/-- Maps `f` to all declarations in the environment. -/
meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α :=
  e.decl_filter_map $ λ d, some (f d)

/-- Lists all declarations in the environment -/
meta def get_decls (e : environment) : list declaration :=
  e.decl_map id

/-- Lists all trusted (non-meta) declarations in the environment -/
meta def get_trusted_decls (e : environment) : list declaration :=
  e.decl_filter_map (λ d, if d.is_trusted then some d else none)

/-- Lists the name of all declarations in the environment -/
meta def get_decl_names (e : environment) : list name :=
  e.decl_map declaration.to_name

/-- Fold a monad over all declarations in the environment. -/
meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α)
  (fn : declaration → α → m α) : m α :=
e.fold (return x) (λ d t, t >>= fn d)

/-- Filters all declarations in the environment. -/
meta def filter (e : environment) (test : declaration → bool) : list declaration :=
e.fold [] $ λ d ds, if test d then d::ds else ds

/-- Filters all declarations in the environment. -/
meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) :=
e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds

/-- Checks whether `s` is a prefix of the file where `n` is declared.
  This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/
meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool :=
s.is_prefix_of $ (e.decl_olean n).get_or_else ""

end environment

/-!
### `is_eta_expansion`

 In this section we define the tactic `is_eta_expansion` which checks whether an expression
  is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`).

-/

namespace expr

/-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have
  `pr = nm.{univs} args`.
  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we
  want to eta-reduce. -/
meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) :
  bool :=
l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args

/-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all
  elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`.
  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we
  want to eta-reduce. -/
meta def is_eta_expansion_test : list (name × expr) → option expr
| []              := none
| (⟨proj, val⟩::l) :=
  match val.get_app_fn with
  | (const nm univs : expr) :=
    if nm = proj then
      let args := val.get_app_args in
      let e := args.ilast in
      if is_eta_expansion_of args univs l then some e else none
    else
      none
  | _                       := none
  end

/-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`.
  Here `l` is intended to consists of the projections and the fields of `val`.
  This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and
  afterward checks whether the resulting expression `e` unifies with `val`.
  This last check is necessary, because `val` and `e` might have different types. -/
meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) :=
do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val),
  match is_eta_expansion_test l' with
  | some e := option.map (λ _, e) <$> try_core (unify e val)
  | none   := return none
  end

/-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the
  eta-expansion of `e`.
  With eta-expansion we here mean the eta-expansion of a structure, not of a function.
  For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`.
  This assumes that `val` is a fully-applied application of the constructor of a structure.

  This is useful to reduce expressions generated by the notation
    `{ field_1 := _, ..other_structure }`
  If `other_structure` is itself a field of the structure, then the elaborator will insert an
  eta-expanded version of `other_structure`. -/
meta def is_eta_expansion (val : expr) : tactic (option expr) := do
  e ← get_env,
  type ← infer_type val,
  projs ← e.structure_fields_full type.get_app_fn.const_name,
  let args := (val.get_app_args).drop type.get_app_args.length,
  is_eta_expansion_aux val (projs.zip args)

end expr

/-! ### Declarations about `declaration` -/

namespace declaration

/--
`declaration.update_with_fun f test tgt decl`
sets the name of the given `decl : declaration` to `tgt`, and applies both `expr.eta_expand` and
`expr.apply_replacement_fun` to the value and type of `decl`.
-/
protected meta def update_with_fun (env : environment) (f : name → name) (test : expr → bool)
  (relevant : name_map ℕ) (reorder : name_map $ list ℕ) (tgt : name) (decl : declaration) :
  declaration :=
let decl := decl.update_name $ tgt in
let decl := decl.update_type $
  (decl.type.eta_expand env reorder).apply_replacement_fun f test relevant reorder in
decl.update_value $
  (decl.value.eta_expand env reorder).apply_replacement_fun f test relevant reorder

/-- Checks whether the declaration is declared in the current file.
  This is a simple wrapper around `environment.in_current_file`
  Use `environment.in_current_file` instead if performance matters. -/
meta def in_current_file (d : declaration) : tactic bool :=
do e ← get_env, return $ e.in_current_file d.to_name

/-- Checks whether a declaration is a theorem -/
meta def is_theorem : declaration → bool
| (thm _ _ _ _) := tt
| _             := ff

/-- Checks whether a declaration is a constant -/
meta def is_constant : declaration → bool
| (cnst _ _ _ _) := tt
| _              := ff

/-- Checks whether a declaration is a axiom -/
meta def is_axiom : declaration → bool
| (ax _ _ _) := tt
| _          := ff

/-- Checks whether a declaration is automatically generated in the environment.
  There is no cheap way to check whether a declaration in the namespace of a generalized
  inductive type is automatically generated, so for now we say that all of them are automatically
  generated. -/
meta def is_auto_generated (e : environment) (d : declaration) : bool :=
e.is_constructor d.to_name ∨
(e.is_projection d.to_name).is_some ∨
(e.is_constructor d.to_name.get_prefix ∧
  d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨
(e.is_inductive d.to_name.get_prefix ∧
  d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec",
  "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨
d.to_name.has_prefix (λ nm, e.is_ginductive' nm)

/--
Returns true iff `d` is an automatically-generated or internal declaration.
-/
meta def is_auto_or_internal (env : environment) (d : declaration) : bool :=
d.to_name.is_internal || d.is_auto_generated env

/-- Returns the list of universe levels of a declaration. -/
meta def univ_levels (d : declaration) : list level :=
d.univ_params.map level.param

/-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/
protected meta def reducibility_hints : declaration → reducibility_hints
| (declaration.defn _ _ _ _ red _) := red
| _ := _root_.reducibility_hints.opaque

/-- formats the arguments of a `declaration.thm` -/
private meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format :=
do tp ← pp tp, body ← pp body.get,
   return $ "<theorem " ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">"

/-- formats the arguments of a `declaration.defn` -/
private meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) :
  tactic format :=
do tp ← pp tp, body ← pp body,
   return $ "<" ++ (if is_trusted then "def " else "meta def ") ++ to_fmt nm ++ " : " ++ tp ++
     " := " ++ body ++ ">"

/-- formats the arguments of a `declaration.cnst` -/
private meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format :=
do tp ← pp tp,
   return $ "<" ++ (if is_trusted then "constant " else "meta constant ") ++ to_fmt nm ++ " : "
     ++ tp ++ ">"

/-- formats the arguments of a `declaration.ax` -/
private meta def print_ax (nm : name) (tp : expr) : tactic format :=
do tp ← pp tp,
   return $ "<axiom " ++ to_fmt nm ++ " : " ++ tp ++ ">"

/-- pretty-prints a `declaration` object. -/
meta def to_tactic_format : declaration → tactic format
| (declaration.thm nm _ tp bd) := print_thm nm tp bd
| (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted
| (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted
| (declaration.ax nm _ tp) := print_ax nm tp

meta instance : has_to_tactic_format declaration :=
⟨to_tactic_format⟩

end declaration

meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) :=
unchecked_cast
expr.has_decidable_eq

section
local attribute [semireducible] reflected
meta instance {α} [has_reflect α] : has_reflect (thunk α) | a :=
expr.lam `x binder_info.default (reflect unit) (reflect $ a ())
end


import for_mathlib.category_theory.triangulated.pretriangulated_misc
import algebra.homology.short_complex.exact
import for_mathlib.category_theory.localization.triangulated_subcategory
import for_mathlib.category_theory.shift_misc
import for_mathlib.category_theory.preadditive.misc
import category_theory.limits.preserves.shapes.zero
import for_mathlib.category_theory.shift_compatibility_minus

noncomputable theory

namespace category_theory

open limits category pretriangulated
open_locale zero_object

lemma limits.exists_discrete_walking_pair_exists_iso_pair
  {C : Type*} [category C] (F : discrete walking_pair ⥤ C) :
  ∃ (X₁ X₂ : C), nonempty (F ≅ pair X₁ X₂) :=
⟨F.obj (discrete.mk walking_pair.left), F.obj (discrete.mk walking_pair.right),
  ⟨discrete.nat_iso_functor ≪≫ eq_to_iso (by { congr' 1, ext j, cases j, tidy, })⟩⟩

section

variables {C D : Type*} [category C] [category D] [has_zero_morphisms C] [has_zero_morphisms D]

instance preserves_limit_functor_empty (F : C ⥤ D) [F.preserves_zero_morphisms]
  [has_zero_object C] : preserves_limit (functor.empty.{0} C) F :=
begin
  let c : cone (functor.empty.{0} C) := cone.mk 0 { app := λ X, 0, },
  have hc : is_limit c :=
  { lift := λ s, 0,
    fac' := by rintro s ⟨⟨⟩⟩,
    uniq' := λ s m hm, subsingleton.elim _ _, },
  refine preserves_limit_of_preserves_limit_cone hc
  { lift := λ s, 0,
    fac' := by rintro s ⟨⟨⟩⟩,
    uniq' := λ s m hm, begin
      refine is_zero.eq_of_tgt _ _ _,
      dsimp [functor.map_cone],
      rw [limits.is_zero.iff_id_eq_zero, ← F.map_id,
        subsingleton.elim (𝟙 (0 : C)) 0, F.map_zero],
    end, },
end

end

section
/-- should be moved to short_complex.exact -/

variables {C : Type*} [category C]

lemma short_complex.exact.is_zero_of_both_zeros [has_zero_morphisms C]
  {S : short_complex C} (ex : S.exact)
  (h₁ : S.f = 0) (h₂ : S.g = 0) : is_zero S.X₂ :=
(short_complex.homology_data.of_zeros S h₁ h₂).exact_iff.1 ex

lemma short_complex.exact.epi_f_iff_g_eq_zero [preadditive C] {S : short_complex C}
  (ex : S.exact) : epi S.f ↔ S.g = 0 :=
begin
  split,
  { introI,
    simp only [← cancel_epi S.f, S.zero, comp_zero], },
  { intro hg,
    haveI := ex.has_homology,
    haveI := S.is_iso_cycles_i_of hg,
    rw preadditive.epi_iff_cancel_zero,
    intros Z h eq,
    rw [← S.p_desc_cycles_co _ eq, ← cancel_epi (S.cycles_i),
      reassoc_of (S.exact_iff_cycles_i_p_cycles_co_zero.1 ex), comp_zero, zero_comp], },
end

lemma short_complex.exact.mono_g_iff_f_eq_zero [preadditive C] {S : short_complex C}
  (ex : S.exact) : mono S.g ↔ S.f = 0 :=
begin
  split,
  { introI,
    simp only [← cancel_mono S.g, S.zero, zero_comp], },
  { intro hf,
    haveI := ex.has_homology,
    haveI := S.is_iso_p_cycles_co_of hf,
    rw preadditive.mono_iff_cancel_zero,
    intros Z h eq,
    rw [← S.lift_cycles_i _ eq, ← cancel_mono (S.p_cycles_co), assoc,
      S.exact_iff_cycles_i_p_cycles_co_zero.1 ex, comp_zero, zero_comp], },
end

end

variables {C D A : Type*} [category C] [has_zero_object C] [has_shift C ℤ]
  [preadditive C] [∀ (n : ℤ), (shift_functor C n).additive] [pretriangulated C]
  [category D] [has_zero_object D] [has_shift D ℤ]
  [preadditive D] [∀ (n : ℤ), (shift_functor D n).additive] [pretriangulated D]
  [category A] [abelian A] (F : C ⥤ A) [functor.preserves_zero_morphisms F]

@[simps]
def pretriangulated.triangle.short_complex (T : pretriangulated.triangle C)
  (hT : T ∈ dist_triang C) : short_complex C :=
  (candidate_triangle.of_distinguished T hT).short_complex

namespace functor

@[protected]
class is_homological : Prop :=
(map_distinguished [] : ∀ (T : pretriangulated.triangle C) (hT : T ∈ dist_triang C),
  ((T.short_complex hT).map F).exact)

namespace is_homological

lemma mk' (hF : ∀ (T : pretriangulated.triangle C) (hT : T ∈ dist_triang C),
  ∃ (T' : pretriangulated.triangle C) (hT' : T' ∈ dist_triang C) (e : T ≅ T'),
    ((T'.short_complex hT').map F).exact) :
  F.is_homological :=
⟨λ T hT, begin
  obtain ⟨T', hT', e, ex'⟩ := hF T hT,
  refine (short_complex.exact_iff_of_iso (F.map_short_complex.map_iso
    ((candidate_triangle.to_short_complex_functor C).map_iso _))).2 ex',
  exact preimage_iso (full_subcategory_inclusion _ : candidate_triangle C ⥤ _) e,
end⟩

variable {F}

lemma of_iso {G : C ⥤ A} [G.preserves_zero_morphisms] (e : G ≅ F) [F.is_homological] :
  G.is_homological :=
is_homological.mk (λ T hT, (short_complex.exact_iff_of_iso
  (short_complex.map_nat_iso _ e)).2 (is_homological.map_distinguished F T hT))

end is_homological

section

open triangulated

variable [F.is_homological]

def kernel_of_is_homological : set C :=
λ K, ∀ (n : ℤ), limits.is_zero (F.obj (K⟦n⟧))

instance : is_triangulated_subcategory F.kernel_of_is_homological :=
{ zero := λ n, limits.is_zero.of_iso (is_zero_zero A)
    (F.map_iso (shift_functor C n).map_zero_object ≪≫ F.map_zero_object),
  shift := λ K m hK n, limits.is_zero.of_iso (hK (m+n))
    (F.map_iso ((shift_functor_add C m n).app K).symm),
  ext₂ := λ T hT h₁ h₃ n, (is_homological.map_distinguished F _
    (triangle.shift_distinguished _ T hT n)).is_zero_of_both_zeros
    (is_zero.eq_of_src (h₁ _) _ _) (is_zero.eq_of_tgt (h₃ _) _ _), }

instance kernel_of_is_homological_saturated :
  saturated F.kernel_of_is_homological :=
⟨λ L K i, begin
  introI,
  intros hL n,
  replace hL := hL n,
  rw limits.is_zero.iff_id_eq_zero at ⊢ hL,
  have eq : 𝟙 _ = i ≫ 𝟙 _ ≫ retraction i := by simp only [id_comp, is_split_mono.id],
  replace eq := (shift_functor C n ⋙ F).congr_map eq,
  dsimp only [functor.comp_map] at eq,
  simpa only [functor.map_comp, functor.map_id, hL, zero_comp, comp_zero] using eq,
end⟩

def W_of_is_homological : morphism_property C :=
λ X Y f, ∀ (n : ℤ), is_iso (F.map (f⟦n⟧'))

instance : preserves_limits_of_shape (discrete walking_pair) F :=
begin
  suffices : ∀ (X₁ X₂ : C), preserves_limit (pair X₁ X₂) F,
  { haveI := this,
    exact ⟨λ X, preserves_limit_of_iso_diagram F
      (category_theory.limits.exists_discrete_walking_pair_exists_iso_pair X)
      .some_spec.some_spec.some.symm⟩, },
  intros X₁ X₂,
  haveI : mono (F.biprod_comparison X₁ X₂),
  { rw preadditive.mono_iff_cancel_zero,
    intros Z f hf,
    have h₂ : f ≫ F.map biprod.snd = 0,
    { simpa only [assoc, biprod_comparison_snd, zero_comp] using hf =≫ biprod.snd, },
    have ex := is_homological.map_distinguished F _
      (binary_biproduct_triangle_distinguished X₁ X₂),
    let S := short_complex.mk (F.map (biprod.inl : X₁ ⟶ _)) (F.map (biprod.snd : _ ⟶ X₂))
      (by { rw ← F.map_comp, simp only [biprod.inl_snd, functor.map_zero]}),
    have ex : S.short_exact := short_complex.short_exact.mk
      (is_homological.map_distinguished F _ (binary_biproduct_triangle_distinguished X₁ X₂)),
    have hf' : ∃ (f₁ : Z ⟶ F.obj X₁), f₁ ≫ F.map biprod.inl = f := ⟨_, ex.lift_f f h₂⟩,
    obtain ⟨f₁, rfl⟩ := hf',
    replace hf := hf =≫ biprod.fst,
    simp only [assoc, biprod_comparison_fst, zero_comp, ← F.map_comp,
      biprod.inl_fst, F.map_id, comp_id] at hf,
    rw [hf, zero_comp], },
  haveI : preserves_binary_biproduct X₁ X₂ F :=
    limits.preserves_binary_biproduct_of_mono_biprod_comparison F,
  apply limits.preserves_binary_product_of_preserves_binary_biproduct,
end

@[priority 100]
instance is_homological.additive : F.additive :=
functor.additive_of_preserves_binary_products _

lemma kernel_of_is_homological_W :
  triangulated.subcategory.W F.kernel_of_is_homological = F.W_of_is_homological :=
begin
  ext X Y f,
  split,
  { intros hf n,
    let f' := f⟦n⟧',
    change is_iso (F.map f'),
    have hf' : triangulated.subcategory.W F.kernel_of_is_homological f' :=
      (morphism_property.compatible_with_shift.iff _ f n).2 hf,
    obtain ⟨Z, g', h', dist, mem⟩ := hf',
    rw is_iso_iff_mono_and_epi,
    split,
    { exact (functor.is_homological.map_distinguished F _
        (inv_rot_of_dist_triangle _ _ dist)).mono_g_iff_f_eq_zero.2
        (limits.is_zero.eq_of_src (mem (-1)) _ _), },
    { exact (functor.is_homological.map_distinguished F _ dist).epi_f_iff_g_eq_zero.2
        (limits.is_zero.eq_of_tgt
          (limits.is_zero.of_iso (mem 0) (F.map_iso ((shift_functor_zero C ℤ).symm.app _))) _ _), }, },
  { intro hf,
    obtain ⟨Z, g, h, mem⟩ := pretriangulated.distinguished_cocone_triangle _ _ f,
    have w : f ≫ g = 0 := pretriangulated.triangle.comp_zero₁₂ _ mem,
    refine ⟨Z, g, h, mem, λ n, _⟩,
    refine short_complex.exact.is_zero_of_both_zeros
      (functor.is_homological.map_distinguished F _
        (rot_of_dist_triangle _ _ (triangle.shift_distinguished _ _ mem n))) _ _,
    { dsimp [pretriangulated.triangle.short_complex],
      haveI := hf n,
      rw ← cancel_epi (F.map (f⟦n⟧')),
      simp only [F.map_zsmul, comp_zero, preadditive.comp_zsmul, ← functor.map_comp, w,
        functor.map_zero, zsmul_zero], },
    { haveI : is_iso (F.map (f⟦n⟧'⟦(1 : ℤ)⟧')) :=
        (nat_iso.is_iso_map_iff (iso_whisker_right (shift_functor_add _ n 1) F) f).1 (hf (n+1)),
      rw ← cancel_mono (F.map (f⟦n⟧'⟦(1 : ℤ)⟧')),
      have w' := F.congr_map (pretriangulated.triangle.comp_zero₂₃ _
        (rot_of_dist_triangle _ _ (triangle.shift_distinguished _ _ mem n))),
      dsimp [pretriangulated.triangle.short_complex] at ⊢ w',
      simp only [preadditive.comp_neg, functor.map_zsmul, assoc, preadditive.comp_zsmul,
        preadditive.zsmul_comp, functor.map_neg, F.map_zero, smul_neg, neg_eq_zero,
        smul_smul, ← units.coe_mul, ← mul_zpow, mul_neg, neg_mul, neg_neg, one_mul, one_smul,
        one_zpow, units.coe_one] at w',
      simp only [← F.map_comp, zero_comp, assoc, preadditive.zsmul_comp, F.map_zsmul, w',
        smul_zero], }, },
end

instance shift_is_homological (n : ℤ) :
  (shift_functor C n ⋙ F).is_homological :=
⟨λ T hT, begin
  refine (short_complex.exact_iff_of_iso _).1
    (functor.is_homological.map_distinguished F _ (triangle.shift_distinguished _ _ hT n)),
  refine short_complex.mk_iso (preadditive.mul_iso ((-1 : units ℤ)^n) (iso.refl _))
    (iso.refl _) (preadditive.mul_iso ((-1 : units ℤ)^n) (iso.refl _)) _ _,
  { dsimp, simp only [preadditive.zsmul_comp, id_comp, comp_id, F.map_zsmul], },
  { dsimp, simp only [preadditive.comp_zsmul, id_comp, comp_id, F.map_zsmul, smul_smul,
      ← units.coe_mul, ← mul_zpow, mul_neg, neg_mul, neg_neg, one_mul, one_smul, one_zpow,
      units.coe_one], },
end⟩

end

@[priority 100]
instance triangulated_functor_preserves_zero_morphisms
  (F : C ⥤ D) [F.has_comm_shift ℤ] [F.is_triangulated] :
  F.preserves_zero_morphisms :=
⟨λ X₁ X₂, begin
  have h := triangle.comp_zero₁₂ _ (F.map_distinguished _
    (binary_product_triangle_distinguished X₁ X₂)),
  dsimp at h,
  simpa only [← F.map_comp, prod.lift_snd] using h,
end⟩

instance triangulated_functor_preserves_binary_products
  (F : C ⥤ D) [F.has_comm_shift ℤ] [F.is_triangulated] :
  preserves_limits_of_shape (discrete walking_pair) F :=
begin
  suffices : ∀ (X₁ X₂ : C), preserves_limit (pair X₁ X₂) F,
  { haveI := this,
    exact ⟨λ X, preserves_limit_of_iso_diagram F
      (category_theory.limits.exists_discrete_walking_pair_exists_iso_pair X)
      .some_spec.some_spec.some.symm⟩, },
  intros X₁ X₂,
  haveI : mono (F.biprod_comparison X₁ X₂),
  { rw preadditive.mono_iff_cancel_zero,
    intros Z f hf,
    have h₂ : f ≫ F.map biprod.snd = 0,
    { simpa only [assoc, biprod_comparison_snd, zero_comp] using hf =≫ biprod.snd, },
    obtain ⟨f₁, rfl⟩ := covariant_yoneda_exact₂ _
      (F.map_distinguished _ (binary_biproduct_triangle_distinguished X₁ X₂)) f h₂,
    replace hf := hf =≫ biprod.fst,
    dsimp [triangulated_functor.map_triangle] at hf,
    simp only [assoc, biprod_comparison_fst, zero_comp, ← F.map_comp, biprod.inl_fst,
      F.map_id, comp_id] at hf,
    rw [hf, zero_comp], },
  haveI : preserves_binary_biproduct X₁ X₂ F :=
    limits.preserves_binary_biproduct_of_mono_biprod_comparison _,
  apply limits.preserves_binary_product_of_preserves_binary_biproduct,
end

@[priority 100]
instance triangulated_functor_additive (F : C ⥤ D) [F.has_comm_shift ℤ] [F.is_triangulated ] :
  F.additive :=
functor.additive_of_preserves_binary_products _

@[priority 100]
instance is_homological.of_comp (F : C ⥤ D) (G : D ⥤ A) [F.has_comm_shift ℤ]
  [F.is_triangulated] [G.preserves_zero_morphisms]
  [G.is_homological] : (F ⋙ G).is_homological :=
⟨λ T hT, begin
  have h := is_homological.map_distinguished G _ (F.map_distinguished _ hT),
  exact h,
end⟩

namespace is_homological

variables (F) (T : pretriangulated.triangle C) (hT : T ∈ dist_triang C)
  (n₀ n₁ : ℤ) (h : n₁ = n₀+1)

include h

def δ : F.obj (T.obj₃⟦n₀⟧) ⟶ F.obj (T.obj₁⟦n₁⟧) :=
F.map (T.mor₃⟦n₀⟧' ≫ (shift_functor_add' C (1 : ℤ) n₀ n₁ (by rw [h, add_comm])).inv.app T.obj₁)

omit h

include hT

lemma δ_comp : δ F T n₀ n₁ h ≫ F.map (T.mor₁⟦n₁⟧') = 0 :=
begin
  dsimp only [δ],
  rw [← F.map_comp, assoc, ← nat_trans.naturality],
  erw [← functor.map_comp_assoc, pretriangulated.triangle.comp_zero₃₁ _ hT],
  simp only [functor.map_zero, zero_comp],
end

lemma comp_δ : F.map (T.mor₂⟦n₀⟧') ≫ δ F T n₀ n₁ h  = 0 :=
begin
  dsimp only [δ],
  rw [← F.map_comp, ← functor.map_comp_assoc, pretriangulated.triangle.comp_zero₂₃ _ hT],
  simp only [functor.map_zero, zero_comp],
end

variable [hF : F.is_homological]

include hF

lemma ex₂ (n : ℤ) :
  (short_complex.mk (F.map (T.mor₁⟦n⟧')) (F.map (T.mor₂⟦n⟧'))
    (by rw [← F.map_comp, ← functor.map_comp, pretriangulated.triangle.comp_zero₁₂ _ hT,
      functor.map_zero, F.map_zero])).exact :=
begin
  refine (short_complex.exact_iff_of_iso _).1
    (is_homological.map_distinguished F _ (pretriangulated.triangle.shift_distinguished C T hT n)),
  refine short_complex.mk_iso (iso.refl _) (preadditive.mul_iso ((-1 : units ℤ)^n) (iso.refl _))
    (iso.refl _) _ _,
  { dsimp,
    simp only [id_comp, linear.comp_smul, comp_id, F.map_zsmul, smul_smul,
      int.units_coe_mul_self, one_zsmul], },
  { dsimp,
    simp only [linear.smul_comp, id_comp, comp_id, F.map_zsmul], },
end

lemma ex₃ :
  (short_complex.mk (F.map (T.mor₂⟦n₀⟧')) (δ F T n₀ n₁ h) (comp_δ F T hT n₀ n₁ h)).exact :=
begin
  refine (short_complex.exact_iff_of_iso _).1
    (is_homological.map_distinguished F _ ((rotate_distinguished_triangle _).1
      (pretriangulated.triangle.shift_distinguished C T hT n₀))),
  refine short_complex.mk_iso (iso.refl _) (preadditive.mul_iso ((-1 : units ℤ)^n₀) (iso.refl _))
    (F.map_iso ((shift_functor_add' C n₀ (1 : ℤ) n₁ h).symm.app T.obj₁)) _ _,
  { dsimp,
    simp only [id_comp, comp_id, F.map_zsmul, preadditive.comp_zsmul, smul_smul,
      int.units_coe_mul_self, one_zsmul], },
  { dsimp [δ],
    simp only [preadditive.zsmul_comp, id_comp, F.map_zsmul, ← F.map_comp, assoc],
    congr' 3,
    simp only [shift_functor_add_comm_hom_app],
    dsimp only [shift_functor_add', eq_to_iso, iso.trans],
    simp only [nat_trans.comp_app, eq_to_hom_app, assoc,
      iso.hom_inv_id_app_assoc, eq_to_hom_trans], },
end

lemma ex₁ :
  (short_complex.mk (δ F T n₀ n₁ h) (F.map (T.mor₁⟦n₁⟧')) (δ_comp F T hT n₀ n₁ h)).exact :=
begin
  refine (short_complex.exact_iff_of_iso _).1
    (is_homological.map_distinguished F _ ((inv_rotate_distinguished_triangle _).2
      (pretriangulated.triangle.shift_distinguished C T hT n₁))),
  refine short_complex.mk_iso
    (F.map_iso ((shift_functor_add' C n₁ (-1) n₀
      (by rw [h, int.add_neg_one, add_tsub_cancel_right])).symm.app T.obj₃))
    (preadditive.mul_iso ((-1 : units ℤ)^n₀) (iso.refl _))
    (preadditive.mul_iso ((-1 : units ℤ)) (iso.refl _)) _ _,
  { change F.map ((shift_functor_add' C n₁ (-1 : ℤ) n₀ _).inv.app T.obj₃) ≫
      F.map (T.mor₃⟦n₀⟧' ≫ (shift_functor_add' C 1 n₀ n₁ _).inv.app T.obj₁) =
      F.map (-(shift_functor C (-1 : ℤ)).map (((-1 : units ℤ)^n₁ • T.mor₃⟦n₁⟧') ≫ (shift_functor_add_comm C 1 n₁).hom.app _) ≫
      (shift_shift_neg (T.obj₁⟦n₁⟧) (1 : ℤ)).hom) ≫ ((-1 : units ℤ)^n₀ • 𝟙 _),
    rw functor.map_neg,
    erw preadditive.zsmul_comp,
    erw preadditive.comp_zsmul,
    rw functor.map_zsmul,
    rw preadditive.zsmul_comp,
    rw functor.map_zsmul,
    rw comp_id,
    rw smul_neg,
    rw smul_smul,
    simp only [h, zpow_add, zpow_one, mul_neg, units.coe_neg, neg_smul, neg_neg, mul_one,
      int.units_coe_mul_self, one_smul, ← F.map_comp],
    erw ← nat_trans.naturality_assoc,
    rw [(shift_functor C (-1 : ℤ)).map_comp, assoc],
    dsimp only [functor.comp_map],
    congr' 2,
    apply shift_compatibility_add_comm, },
  { dsimp,
    simp only [id_comp, comp_id, F.map_zsmul, preadditive.comp_zsmul, smul_smul, id_comp,
      preadditive.zsmul_comp, h, zpow_add, zpow_one, mul_neg, mul_one, units.coe_neg, neg_neg], },
end

end is_homological

end functor

end category_theory


deriving instance TypeName for Nat
deriving instance TypeName for String

example : (Dynamic.mk 42).get? String = none := by native_decide
example : (Dynamic.mk 42).get? Nat = some 42 := by native_decide
example : (Dynamic.mk 42).typeName = ``Nat := by native_decide


/-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.data.ordering.basic init.coe init.data.to_string

/-- Reflect a C++ name object. The VM replaces it with the C++ implementation. -/
inductive name
| anonymous  : name
| mk_string  : string → name → name
| mk_numeral : unsigned → name → name

/-- Gadget for automatic parameter support. This is similar to the opt_param gadget, but it uses
    the tactic declaration names tac_name to synthesize the argument.
    Like opt_param, this gadget only affects elaboration.
    For example, the tactic will *not* be invoked during type class resolution. -/
@[reducible] def {u} auto_param (α : Sort u) (tac_name : name) : Sort u :=
α

@[simp] lemma {u} auto_param_eq (α : Sort u) (n : name) : auto_param α n = α :=
rfl

instance : inhabited name :=
⟨name.anonymous⟩

def mk_str_name (n : name) (s : string) : name :=
name.mk_string s n

def mk_num_name (n : name) (v : nat) : name :=
name.mk_numeral (unsigned.of_nat' v) n

def mk_simple_name (s : string) : name :=
mk_str_name name.anonymous s

instance string_to_name : has_coe string name :=
⟨mk_simple_name⟩

infix ` <.> `:65 := mk_str_name

open name

def name.get_prefix : name → name
| anonymous        := anonymous
| (mk_string s p)  := p
| (mk_numeral s p) := p

def name.update_prefix : name → name → name
| anonymous        new_p := anonymous
| (mk_string s p)  new_p := mk_string s new_p
| (mk_numeral s p) new_p := mk_numeral s new_p

-- Without this option, we get errors when defining the following definitions.
set_option eqn_compiler.ite false

def name.to_string_with_sep (sep : string) : name → string
| anonymous                := "[anonymous]"
| (mk_string s anonymous)  := s
| (mk_numeral v anonymous) := repr v
| (mk_string s n)          := name.to_string_with_sep n ++ sep ++ s
| (mk_numeral v n)         := name.to_string_with_sep n ++ sep ++ repr v

private def name.components' : name -> list name
| anonymous                := []
| (mk_string s n)          := mk_string s anonymous :: name.components' n
| (mk_numeral v n)         := mk_numeral v anonymous :: name.components' n

def name.components (n : name) : list name :=
(name.components' n).reverse

protected def name.to_string : name → string :=
name.to_string_with_sep "."

protected def name.repr (n : name) : string :=
"`" ++ n.to_string

instance : has_to_string name :=
⟨name.to_string⟩

instance : has_repr name :=
⟨name.repr⟩

/- TODO(Leo): provide a definition in Lean. -/
meta constant name.has_decidable_eq : decidable_eq name
/- Both cmp and lex_cmp are total orders, but lex_cmp implements a lexicographical order. -/
meta constant name.cmp : name → name → ordering
meta constant name.lex_cmp : name → name → ordering
meta constant name.append : name → name → name
meta constant name.is_internal : name → bool

protected meta def name.lt (a b : name) : Prop :=
name.cmp a b = ordering.lt

meta instance : decidable_rel name.lt :=
λ a b, ordering.decidable_eq _ _

meta instance : has_lt name :=
⟨name.lt⟩

attribute [instance] name.has_decidable_eq

meta instance : has_append name :=
⟨name.append⟩

/-- `name.append_after n i` return a name of the form n_i -/
meta constant name.append_after : name → nat → name

meta def name.is_prefix_of : name → name → bool
| p name.anonymous := ff
| p n              :=
  if p = n then tt else name.is_prefix_of p n.get_prefix

meta def name.is_suffix_of : name → name → bool
| anonymous _ := tt
| (mk_string s n) (mk_string s' n') := (s = s') && name.is_suffix_of n n'
| (mk_numeral v n) (mk_numeral v' n') := (v = v') && name.is_suffix_of n n'
| _ _ := ff

meta def name.replace_prefix : name → name → name → name
| anonymous        p p' := anonymous
| (mk_string s c)  p p' := if c = p then mk_string s p' else mk_string s (name.replace_prefix c p p')
| (mk_numeral v c) p p' := if c = p then mk_numeral v p' else mk_numeral v (name.replace_prefix c p p')


/-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.ScopedEnvExtension
import Lean.Util.Recognizers
import Lean.Meta.Basic

namespace Lean.Meta

structure CongrLemma where
  theoremName   : Name
  funName       : Name
  hypothesesPos : Array Nat
  priority      : Nat
deriving Inhabited, Repr

structure CongrLemmas where
  lemmas : SMap Name (List CongrLemma) := {}
  deriving Inhabited, Repr

def CongrLemmas.get (d : CongrLemmas) (declName : Name) : List CongrLemma :=
  match d.lemmas.find? declName with
  | none    => []
  | some cs => cs

def addCongrLemmaEntry (d : CongrLemmas) (e : CongrLemma) : CongrLemmas :=
  { d with lemmas :=
      match d.lemmas.find? e.funName with
      | none    => d.lemmas.insert e.funName [e]
      | some es => d.lemmas.insert e.funName <| insert es }
where
  insert : List CongrLemma → List CongrLemma
    | []     => [e]
    | e'::es => if e.priority ≥ e'.priority then e::e'::es else e' :: insert es

builtin_initialize congrExtension : SimpleScopedEnvExtension CongrLemma CongrLemmas ←
  registerSimpleScopedEnvExtension {
    name           := `congrExt
    initial        := {}
    addEntry       := addCongrLemmaEntry
    finalizeImport := fun s => { s with lemmas := s.lemmas.switch }
  }

def mkCongrLemma (declName : Name) (prio : Nat) : MetaM CongrLemma := withReducible do
  let c ← mkConstWithLevelParams declName
  let (xs, bis, type) ← forallMetaTelescopeReducing (← inferType c)
  match type.eq? with
  | none => throwError "invalid 'congr' theorem, equality expected{indentExpr type}"
  | some (_, lhs, rhs) =>
    lhs.withApp fun lhsFn lhsArgs => rhs.withApp fun rhsFn rhsArgs => do
      unless lhsFn.isConst && rhsFn.isConst && lhsFn.constName! == rhsFn.constName! && lhsArgs.size == rhsArgs.size do
        throwError "invalid 'congr' theorem, equality left/right-hand sides must be applications of the same function{indentExpr type}"
      let mut foundMVars : NameSet := {}
      for lhsArg in lhsArgs do
        unless lhsArg.isSort do
          unless lhsArg.isMVar do
            throwError "invalid 'congr' theorem, arguments in the left-hand-side must be variables or sorts{indentExpr lhs}"
          foundMVars := foundMVars.insert lhsArg.mvarId!
      let mut i := 0
      let mut hypothesesPos := #[]
      for x in xs, bi in bis do
        if bi.isExplicit && !foundMVars.contains x.mvarId! then
          let rhsFn? ← forallTelescopeReducing (← inferType x) fun ys xType => do
            match xType.eq? with
            | none => pure none -- skip
            | some (_, xLhs, xRhs) =>
              let mut j := 0
              for y in ys do
                let yType ← inferType y
                unless onlyMVarsAt yType foundMVars do
                  throwError "invalid 'congr' theorem, argument #{j+1} of parameter #{i+1} contains unresolved parameter{indentExpr yType}"
                j := j + 1
              unless onlyMVarsAt xLhs foundMVars do
                throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the left-hand-side contains unresolved parameters{indentExpr xLhs}"
              let xRhsFn := xRhs.getAppFn
              unless xRhsFn.isMVar do
                throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head is not a metavariable{indentExpr xRhs}"
              unless !foundMVars.contains xRhsFn.mvarId! do
                throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head was already resolved{indentExpr xRhs}"
              for arg in xRhs.getAppArgs do
                unless arg.isFVar do
                  throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side argument is not local variable{indentExpr xRhs}"
              pure (some xRhsFn)
          match rhsFn? with
          | none       => pure ()
          | some rhsFn =>
            foundMVars    := foundMVars.insert x.mvarId! |>.insert rhsFn.mvarId!
            hypothesesPos := hypothesesPos.push i
        i := i + 1
      trace[Meta.debug] "c: {c} : {type}"
      return {
        theoremName   := declName
        funName       := lhsFn.constName!
        hypothesesPos := hypothesesPos
        priority      := prio
      }
where
  /-- Return `true` if `t` contains a metavariable that is not in `mvarSet` -/
  onlyMVarsAt (t : Expr) (mvarSet : NameSet) : Bool :=
    Option.isNone <| t.find? fun e => e.isMVar && !mvarSet.contains e.mvarId!

def addCongrLemma (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do
  let lemma ← mkCongrLemma declName prio
  congrExtension.add lemma attrKind

builtin_initialize
  registerBuiltinAttribute {
    name  := `congr
    descr := "congruence theorem"
    add   := fun declName stx attrKind => do
      let prio ← getAttrParamOptPrio stx[1]
      discard <| addCongrLemma declName attrKind prio |>.run {} {}
  }

def getCongrLemmas : MetaM CongrLemmas :=
  return congrExtension.getState (← getEnv)

end Lean.Meta


import Machine.Parser
import Machine.Options
import Lean.Elab

open Lean Machine.Types

namespace List
  def forAll {α : Type u} (P : α → Prop) : List α → Prop
  | []      => True
  | x :: xs => P x ∧ forAll P xs

  def successively {α : Type u} (R : α → α → Prop) : List α → Prop
  | []           => True
  | [x]          => True
  | x :: y :: ys => R x y ∧ successively R (y :: ys)

  def forLast {α : Type u} (P : α → Prop) : List α → Prop
  | []      => True
  | [x]     => P x
  | x :: xs => forLast P xs

  def forFirst {α : Type u} (P : α → Prop) : List α → Prop
  | []      => True
  | x :: xs => P x

  def nonempty {α : Type u} : List α → Prop
  | []      => False
  | x :: xs => True
end List

namespace Machine.Types
  def machine.next : machine → machine
  | ⟨stack, regs, flag, progc⟩ => ⟨stack, regs, flag, progc + 1⟩

  def machine.get (m : machine) (r : reg) : Int :=
  (m.regs.find? r).get!
end Machine.Types

namespace Machine.Simulator
  def condjmp (M : machine) (cond : Ordering) (ptr : Nat) : machine :=
  ⟨M.stack, M.regs, M.flag, if M.flag == cond then ptr else M.progc + 1⟩

  def instr.eval (M : machine) : instr → machine
  | instr.push z => ⟨M.stack.push z, M.regs, M.flag, M.progc + 1⟩
  | instr.pushr r => ⟨M.stack.push (M.get r), M.regs, M.flag, M.progc + 1⟩
  | instr.popr r => ⟨M.stack.pop, M.regs.replace r M.stack.back, M.flag, M.progc + 1⟩
  | instr.dup => ⟨M.stack.push M.stack.back, M.regs, M.flag, M.progc + 1⟩
  | instr.add r₁ r₂ r₃ => ⟨M.stack, M.regs.replace r₃ (M.get r₁ + M.get r₂), M.flag, M.progc + 1⟩
  | instr.neg r₁ r₂ => ⟨M.stack, M.regs.replace r₂ (-M.get r₁), M.flag, M.progc + 1⟩
  | instr.mul r₁ r₂ r₃ => ⟨M.stack, M.regs.replace r₃ (M.get r₁ * M.get r₂), M.flag, M.progc + 1⟩
  | instr.cmp r₁ r₂ => ⟨M.stack, M.regs, compare (M.get r₁) (M.get r₂), M.progc + 1⟩
  | instr.jmp ptr => ⟨M.stack, M.regs, M.flag, ptr⟩
  | instr.je ptr => condjmp M Ordering.eq ptr
  | instr.jg ptr => condjmp M Ordering.gt ptr
  | instr.jl ptr => condjmp M Ordering.lt ptr
  | instr.dump => M.next

  def instr.effect (M : machine) : instr → IO Unit
  | instr.dump => do println! "r1 = {M.get reg.r1}, r2 = {M.get reg.r2}, r3 = {M.get reg.r3}, r4 = {M.get reg.r4}"
  | _          => return ()

  def tick (M : machine) (ρ : tape) : Option machine :=
  match ρ.get? M.progc with
  | none   => none
  | some ε => some (instr.eval M ε)

  def effect (M : machine) (ρ : tape) : IO Unit :=
  match ρ.get? M.progc with
  | none   => return ()
  | some ε => instr.effect M ε

  private def await (M₀ : machine) (ρ : tape) : Nat → IO Unit
  |   0   => throw (IO.userError "execution depth was reached")
  | n + 1 => do effect M₀ ρ; match tick M₀ ρ with
    | none   => return ()
    | some M => await M ρ n

  private partial def unsafeAwait (M₀ : machine) (ρ : tape) : IO Unit :=
  do effect M₀ ρ; match tick M₀ ρ with
  | none   => return ()
  | some M => unsafeAwait M ρ

  def simulate :=
  unsafeAwait machine.init

  elab "asm " label:ident xs:mnemonic* " end" : command => do
    let (ρ, M) ← Machine.Parser.expand xs
    let xs ← Array.mapM instr.restore ρ
    Elab.Command.elabDeclaration (← `(def $label : Array instr := #[$xs,*]))

    let opts ← getOptions

    if Machine.Options.debugAsm.get opts then
      do await M ρ (Machine.Options.executionDepth.get opts)
    else return ()

  def computes (ρ : tape) (M₁ M₂ : machine) :=
  tick M₁ ρ = some M₂

  def completed (ρ : tape) (M : machine) :=
  tick M ρ = none

  def clean (M : machine) :=
  M = machine.init

  def allowed (ρ : tape) (L : List machine) :=
  L.successively (computes ρ) ∧ L.forLast (completed ρ)

  def terminator (ρ : tape) (L : List machine) :=
  L.nonempty ∧ L.forFirst clean ∧ allowed ρ L

  def terminating (ρ : tape) :=
  ∃ L, terminator ρ L

  asm loop
    M: jmp M
  end

  theorem some_inj {α : Type u} {a b : α} (p : some a = some b) : a = b :=
  by { apply Option.noConfusion p; apply id }

  theorem loop.conservative : ∀ (M₁ M₂ : machine), tick M₁ loop = M₂ → M₁ = M₂ :=
  λ ⟨stack₁, regs₁, flags₁, progc₁⟩ ⟨stack₂, regs₂, flags₂, progc₂⟩ H => by {
    induction progc₁; apply some_inj H; cases H
  }

  theorem loopTerminator : ∀ (L : List machine), terminator loop L → False
  | [], ⟨p, _⟩ => p
  | [x], ⟨_, ⟨q, ⟨_, h⟩⟩⟩ => by { rw [q] at h; cases h }
  | x :: y :: ys, ⟨p, ⟨q, ⟨r, h⟩⟩⟩ => by {
    apply loopTerminator (y :: ys); apply And.intro;
    apply True.intro; apply And.intro; rw [←loop.conservative x y r.left];
    apply q; apply And.intro; apply r.right; apply h
  }

  theorem nonterminating : ¬terminating loop :=
  λ | Exists.intro L η => loopTerminator L η
end Machine.Simulator


/-
Copyright (c) 2022 Devon Tuma. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Devon Tuma
-/
import computational_monads.simulation_semantics.simulate.support
import computational_monads.simulation_semantics.simulate.eval_dist
import computational_monads.simulation_semantics.simulate.subsingleton
import computational_monads.support.prod

/-!
# Tracking Simulation Oracle

This file defines a constructor for simulation oracles that use the internal state
for the purpose of tracking some value, in a way that doesn't affect the actual query result.
For example a logging oracle just tracks the queries, without actually affecting the return value.

The definition is in terms of a query function that responds to queries,
and an indepdent update_state function that controls the internal state.
For simplicity the update state function rather than having oracle access.

In many cases this definition will be composed with an oracle with result depending on the state,
but this construction allows seperation of the components that affect state independently.
-/

variables {α β γ : Type} {spec spec' spec'': oracle_spec}

structure tracking_sim_oracle (spec spec' : oracle_spec) (S : Type)
  extends sim_oracle spec spec' S :=
(default_state := default_state)
(answer_query : Π (i : spec.ι), spec.domain i → oracle_comp spec' (spec.range i))
(update_state : Π (s : S) (i : spec.ι), spec.domain i → spec.range i → S)
(o := λ i x, (λ u, (u, update_state x.2 i x.1 u)) <$> (answer_query i x.1))

structure stateless_sim_oracle (spec spec' : oracle_spec)
  extends tracking_sim_oracle spec spec' unit :=
(default_state := ())
(answer_query := answer_query)
(update_state := λ _ _ _ _, ())
(o := λ i x, (λ u, (u, ())) <$> (answer_query i x.1))

def identi_o (spec : oracle_spec) : stateless_sim_oracle spec spec :=
{ answer_query := λ i t, oracle_comp.query i t }

/-- Oracle where the query result is indepenent of the current oracle state,
although the new state may depend upon the previous state.
For example a logging oracle that just tracks the input and output of queries.
`o` is the way the oracle responds to queries, which doesn't have access to the state.
`update_state` takes a query and internal state and returns the new internal state.
Note that `update_state` is not a probabalistic function, and has no oracle access -/
def tracking_oracle {spec : oracle_spec} {S : Type}
  (o : Π (i : spec.ι), spec.domain i → oracle_comp spec' (spec.range i))
  (update_state : Π (s : S) (i : spec.ι), spec.domain i → spec.range i → S)
  (default_state : S) : sim_oracle spec spec' S :=
{ default_state := default_state,
  o := λ i ⟨t, s⟩, (λ u, (u, update_state s i t u)) <$> (o i t) }

notation `⟪` o `|` update_state `,` default_state `⟫` :=
  tracking_oracle o update_state default_state

namespace tracking_oracle

open_locale big_operators ennreal
open oracle_comp oracle_spec

variables {S S' : Type} (o : Π (i : spec.ι), spec.domain i → oracle_comp spec' (spec.range i))
  (o' : Π (i : spec.ι), spec.domain i → oracle_comp spec'' (spec.range i))
  (update_state : Π (s : S) (i : spec.ι), spec.domain i → spec.range i → S)
  (update_state' : Π (s : S') (i : spec.ι), spec.domain i → spec.range i → S')
  (default_state : S) (default_state' : S') (a : α) (i : spec.ι) (t : spec.domain i)
  (oa : oracle_comp spec α) (ob : α → oracle_comp spec β) (s : S) (s' : S')
  (x : spec.domain i × S) (y : spec.range i × S)

@[simp] lemma apply_eq : ⟪o | update_state, default_state⟫ i x =
  (λ u, (u, update_state x.2 i x.1 u)) <$> (o i x.1) := by {cases x, refl}

instance decidable [decidable_eq S] [∀ i x, (o i x).decidable] :
  (⟪o | update_state, default_state⟫ i x).decidable :=
by { rw [apply_eq], exact oracle_comp.decidable_map _ _ }

section support

@[simp] lemma support_apply : (⟪o | update_state, default_state⟫ i x).support =
  (λ u, (u, update_state x.2 i x.1 u)) '' (o i x.1).support :=
set.ext (λ y, by rw [apply_eq, support_map])

lemma fin_support_apply [∀ i t, (o i t).decidable] [decidable_eq S] :
  (⟪o | update_state, default_state⟫ i x).fin_support =
    (o i x.1).fin_support.image (λ u, (u, update_state x.2 i x.1 u)) :=
by simp only [fin_support_eq_iff_support_eq_coe, apply_eq, support_map,
  finset.coe_image, coe_fin_support_eq_support]

lemma mem_support_apply_iff {y : spec.range i × S} :
  y ∈ (⟪o | update_state, default_state⟫ i x).support ↔
    y.1 ∈ (o i x.1).support ∧ update_state x.2 i x.1 y.1 = y.2 :=
by simp only [support_apply, prod.eq_iff_fst_eq_snd_eq, set.mem_image,
  and_comm (_ = y.fst), exists_eq_right_right]

/-- If the oracle can take on any value then the first element of the support is unchanged -/
theorem support_simulate'_eq_support (h : ∀ i t, (o i t).support = ⊤) :
  (simulate' ⟪o | update_state, default_state⟫ oa s).support = oa.support :=
support_simulate'_eq_support _ oa s (λ i t s, set.ext (λ x, by simp only
  [h, set.top_eq_univ, set.mem_univ, true_and, apply_eq, support_map, set.mem_image,
    prod.exists, prod.mk.inj_iff, exists_eq_left, exists_eq_left', exists_apply_eq_apply]))

/-- Particular case of `support_simulate'_eq_support` for `query`.
In particular a tracking oracle that *only* does tracking doesn't affect the main output. -/
@[simp] lemma support_simulate'_query_eq_support :
  (simulate' ⟪query | update_state, default_state⟫ oa s).support = oa.support :=
support_simulate'_eq_support query update_state default_state oa s (λ _ _, rfl)

theorem support_simulate'_eq_support_simulate' (h : ∀ i t, (o i t).support = (o' i t).support) :
  (simulate' ⟪o | update_state, default_state⟫ oa s).support =
    (simulate' ⟪o' | update_state', default_state'⟫ oa s').support :=
support_simulate'_eq_support_simulate' (λ i t s s', set.ext $ λ x,
  by simp only [mem_support_apply_iff, h, simulate'_query, support_map, support_apply,
    set.mem_image, set.mem_set_of_eq, prod.exists, exists_and_distrib_right, exists_eq_right,
    exists_eq_right', exists_eq_right_right, prod.eq_iff_fst_eq_snd_eq, and_comm (_ = x)]) oa s s'

/-- The support of `simulate'` is independt of the tracking functions -/
theorem support_simulate'_eq_support_simulate'_of_oracle_eq :
  (simulate' ⟪o | update_state, default_state⟫ oa s).support =
    (simulate' ⟪o | update_state', default_state'⟫ oa s').support :=
support_simulate'_eq_support_simulate' o o _ _ _ _ oa s s' (λ _ _, rfl)

section subsingleton

variables [subsingleton S]

@[simp] lemma support_apply_of_subsingleton :
  (⟪o | update_state, default_state⟫ i x).support = prod.fst ⁻¹' (o i x.1).support :=
set.ext (λ y, by erw [apply_eq, map_eq_bind_return_comp,
  support_bind_prod_mk_of_snd_subsingleton, set.image_id])

lemma support_simulate_eq_preimage_support_of_subsingleton (h : ∀ i t, (o i t).support = ⊤) :
  (simulate ⟪o | update_state, default_state⟫ oa s).support = prod.fst ⁻¹' oa.support :=
by rw [set.preimage, support_simulate_eq_support_simulate'_of_subsingleton,
  support_simulate'_eq_support o _ _ oa s h]

@[simp] lemma support_simulate_query_eq_support_of_subsingleton :
  (simulate ⟪query | update_state, default_state⟫ oa s).support = prod.fst ⁻¹' oa.support :=
support_simulate_eq_preimage_support_of_subsingleton query _ _ oa s (λ _ _, rfl)

end subsingleton

end support

section eval_dist

@[simp] lemma eval_dist_apply :
  ⁅⟪o | update_state, default_state⟫ i (t, s)⁆ = ⁅o i t⁆.map (λ u, (u, update_state s i t u)) :=
by rw [apply_eq, eval_dist_map]

/-- If the oracle has uniform distribution, then the distribution under `simulate'` is unchanged -/
theorem eval_dist_simulate'_eq_eval_dist
  (h : ∀ i t, ⁅o i t⁆ = pmf.uniform_of_fintype (spec.range i)) :
  ⁅simulate' ⟪o | update_state, default_state⟫ oa s⁆ = ⁅oa⁆ :=
eval_dist_simulate'_eq_eval_dist _ oa s (λ i t s, trans
  (by simpa [eval_dist_apply, pmf.map_comp] using pmf.map_id ⁅o i t⁆) (h i t))

/-- Specific case of `eval_dist_simulate'_eq_eval_dist` for query.
In particular if a tracking oracle *only* does tracking gives the same main output distribution. -/
@[simp] lemma eval_dist_simulate'_query_eq_eval_dist :
  ⁅simulate' ⟪query | update_state, default_state⟫ oa s⁆ = ⁅oa⁆ :=
eval_dist_simulate'_eq_eval_dist query update_state default_state oa s (λ _ _, rfl)

lemma eval_dist_simulate'_eq_eval_dist_simulate'
  (h : ∀ i t, o i t ≃ₚ o' i t) : ⁅simulate' ⟪o | update_state, default_state⟫ oa s⁆ =
    ⁅simulate' ⟪o' | update_state', default_state'⟫ oa s'⁆ :=
eval_dist_simulate'_eq_eval_dist_simulate' (λ i t s s',
  sorry) _ _ _ --by simp [pmf.map_comp, tracking_oracle.apply_eq, eval_dist_map, h]) oa s s'

/-- The first output of simulation under different `tracking_oracle` with the same oracle
is the same regardless of if the tracking functions are different. -/
theorem eval_dist_simulate'_eq_eval_dist_simulate'_of_oracle_eq :
  ⁅simulate' ⟪o | update_state, default_state⟫ oa s⁆ =
    ⁅simulate' ⟪o | update_state', default_state'⟫ oa s'⁆ :=
eval_dist_simulate'_eq_eval_dist_simulate' o o _ _ _ _ oa s s' (λ _ _, rfl)

end eval_dist

section prob_event

variable (e : set α)

@[simp] lemma prob_event_apply (e : set (spec.range i × S)) :
  ⁅e | ⟪o | update_state, default_state⟫ i (t, s)⁆ =
    ⁅λ u, (u, update_state s i t u) ∈ e | o i t⁆ :=
by simpa only [apply_eq, prob_event_map]

lemma prob_event_simulate'_eq_prob_event
  (h : ∀ i t, ⁅o i t⁆ = pmf.uniform_of_fintype (spec.range i)) :
  ⁅e | simulate' ⟪o | update_state, default_state⟫ oa s⁆ = ⁅e | oa⁆ :=
prob_event_eq_of_eval_dist_eq (eval_dist_simulate'_eq_eval_dist _ _ _ _ _ h) e

/-- Specific case of `eval_dist_simulate'_eq_eval_dist` for query.
In particular if a tracking oracle *only* does tracking gives the same main output distribution. -/
lemma prob_event_simulate'_query_eq_prob_event :
  ⁅e | simulate' ⟪query | update_state, default_state⟫ oa s⁆ = ⁅e | oa⁆ :=
prob_event_simulate'_eq_prob_event _ _ _ oa s e (λ _ _, rfl)

lemma prob_event_simulate'_eq_prob_event_simulate'
  (h : ∀ i t, o i t ≃ₚ o' i t) : ⁅e | simulate' ⟪o | update_state, default_state⟫ oa s⁆ =
    ⁅e | simulate' ⟪o' | update_state', default_state'⟫ oa s'⁆ :=
prob_event_eq_of_eval_dist_eq (eval_dist_simulate'_eq_eval_dist_simulate' _ _ _ _ _ _ _ _ _ h) e

/-- The first output of simulation under different `tracking_oracle` with the same oracle
is the same regardless of if the tracking functions are different. -/
theorem prob_event_simulate'_eq_eval_dist_simulate'_of_oracle_eq :
  ⁅e | simulate' ⟪o | update_state, default_state⟫ oa s⁆ =
    ⁅e | simulate' ⟪o | update_state', default_state'⟫ oa s'⁆ :=
prob_event_simulate'_eq_prob_event_simulate' o o _ _ _ _ oa s s' e (λ _ _, rfl)

end prob_event

end tracking_oracle


import data.quot
import .homotopy_classes

universes v u

open category_theory
local notation f ` ∘ `:80 g:80 := g ≫ f

namespace homotopy_theory.cofibrations
-- Homotopy equivalences as the weak equivalences of an I-category.
open homotopy_theory.weak_equivalences

variables {C : Type u} [category.{v} C]
  [has_initial_object.{v} C] [has_coproducts.{v} C] [I_category.{v} C]

instance homotopy_category.category_with_weak_equivalences :
  category_with_weak_equivalences (category_mod_congruence C homotopy_congruence) :=
isomorphisms_as_weak_equivalences

instance I_category.category_with_weak_equivalences : category_with_weak_equivalences C :=
preimage_with_weak_equivalences (quotient_functor C homotopy_congruence)

def homotopy_equivalence {x y : C} (f : x ⟶ y) : Prop := is_weq f

lemma homotopic_iff_equal_in_ho {x y : C} {f g : x ⟶ y} : f ≃ g ↔ ⟦f⟧ = ⟦g⟧ :=
by symmetry; apply quotient.eq

lemma homotopy_equivalence_iff {x y : C} {f : x ⟶ y} :
  homotopy_equivalence f ↔ ∃ g, g ∘ f ≃ 𝟙 _ ∧ f ∘ g ≃ 𝟙 _ :=
begin
  split,
  { intro h, cases h with i hi,
    cases quotient.exists_rep i.inv with g hg,
    existsi g, split; rw homotopic_iff_equal_in_ho,
    { have := i.hom_inv_id',
      rw [hi, ←hg] at this, exact this },
    { have := i.inv_hom_id',
      rw [hi, ←hg] at this, exact this } },
  { intro h, rcases h with ⟨g, h₁, h₂⟩,
    refine ⟨iso.mk ⟦f⟧ ⟦g⟧ _ _, rfl⟩;
    { dsimp [auto_param], change ⟦_⟧ = ⟦_⟧, rw ←homotopic_iff_equal_in_ho,
      exact h₁ <|> exact h₂ } }
end

end homotopy_theory.cofibrations


import Lean
open Lean Elab Command Term Meta

/- ## Elaboration: Solutions -/

/- ### 1. -/

elab n:term "♥" a:"♥"? b:"♥"? : term => do
  let nExpr : Expr ← elabTermEnsuringType n (mkConst `Nat)
  if let some a := a then
    if let some b := b then
      return Expr.app (Expr.app (Expr.const `Nat.add []) nExpr) (mkNatLit 3)
    else
      return Expr.app (Expr.app (Expr.const `Nat.add []) nExpr) (mkNatLit 2)
  else
    return Expr.app (Expr.app (Expr.const `Nat.add []) nExpr) (mkNatLit 1)

#eval 7 ♥ -- 8
#eval 7 ♥♥ -- 9
#eval 7 ♥♥♥ -- 10

/- ### 2. -/

-- a) using `syntax` + `@[command_elab alias] def elabOurAlias : CommandElab`
syntax (name := aliasA) (docComment)? "aliasA " ident " ← " ident* : command

@[command_elab «aliasA»]
def elabOurAlias : CommandElab := λ stx =>
  match stx with
  | `(aliasA $x:ident ← $ys:ident*) =>
    for y in ys do
      Lean.logInfo y
  | _ =>
    throwUnsupportedSyntax

aliasA hi.hello ← d.d w.w nnn

-- b) using `syntax` + `elab_rules`.
syntax (name := aliasB) (docComment)? "aliasB " ident " ← " ident* : command

elab_rules : command
  | `(command | aliasB $m:ident ← $ys:ident*) =>
    for y in ys do
      Lean.logInfo y

aliasB hi.hello ← d.d w.w nnn

-- c) using `elab`
elab "aliasC " x:ident " ← " ys:ident* : command =>
  for y in ys do
    Lean.logInfo y

aliasC hi.hello ← d.d w.w nnn

/- ### 3. -/

open Parser.Tactic

-- a) using `syntax` + `@[tactic nthRewrite] def elabNthRewrite : Lean.Elab.Tactic.Tactic`.
syntax (name := nthRewriteA) "nth_rewriteA " (config)? num rwRuleSeq (ppSpace location)? : tactic

@[tactic nthRewriteA] def elabNthRewrite : Lean.Elab.Tactic.Tactic := fun stx => do
  match stx with
  | `(tactic| nth_rewriteA $[$cfg]? $n $rules $_loc) =>
    Lean.logInfo "rewrite location!"
  | `(tactic| nth_rewriteA $[$cfg]? $n $rules) =>
    Lean.logInfo "rewrite target!"
  | _ =>
    throwUnsupportedSyntax

-- b) using `syntax` + `elab_rules`.
syntax (name := nthRewriteB) "nth_rewriteB " (config)? num rwRuleSeq (ppSpace location)? : tactic

elab_rules (kind := nthRewriteB) : tactic
  | `(tactic| nth_rewriteB $[$cfg]? $n $rules $_loc) =>
    Lean.logInfo "rewrite location!"
  | `(tactic| nth_rewriteB $[$cfg]? $n $rules) =>
    Lean.logInfo "rewrite target!"

-- c) using `elab`.
elab "nth_rewriteC " (config)? num rwRuleSeq loc:(ppSpace location)? : tactic =>
  if let some loc := loc then
    Lean.logInfo "rewrite location!"
  else
    Lean.logInfo "rewrite target!"

example : 2 + 2 = 4 := by
  nth_rewriteC 2 [← add_zero] at h
  nth_rewriteC 2 [← add_zero]
  sorry