Section CofiniteQuantification.
Local Notation "{ k ~> u } t" := (open_rec k u t) (at level 67).
(* With this new definition, we can almost use the same proof for [open_rec_lc], we only need one change. We need to add the line [pick fresh x for L.]  immediately before the use of [apply open_rec_lc_core].  This tactic, defined in [Metatheory], introduces a new atom [x] that is known not to be in the set [L]. *)
(* Take-home Exercise: The next two lemmas have exactly the same proofs as before. *)
(*************************************************************************)
(*                                                                       *)
(*  Coffee break                                                         *)
(*                                                                       *)
(*************************************************************************)
(*************************************************************************)
(** * Typing environments *)
(*************************************************************************)
(** We represent environments as association lists (lists of pairs of keys and values) whose keys are [atom]s. *)
Notation env := (list (atom * typ)).
(** For STLC, environments bind [atom]s to [typ]s.  We define an abbreviation [env] for the type of these environments.  Coq will print [list (atom * typ)] as [env], and we can use [env] as a shorthand for writing [list (atom * typ)].  Lists are defined in Coq's standard library, with the constructors [nil] and [cons].  The list library includes the [::] notation for cons as well as standard list operations such as append, map, and fold. The infix operation "++" is list append.  The Metatheory library extends this reasoning by instantiating the AssocList library to provide support for association lists whose keys are [atom]s.  Everything in this library is polymorphic over the type of objects bound in the environment.  Look in AssocList for additional details about the functions and predicates that we mention below. *)
(** Environment equality *)
(** When reasoning about environments, we often need to talk about bindings in the "middle" of an environment. Therefore, it is common for lemmas and definitions to use list append in their statements. Unfortunately, list append is associative, so two Coq expressions may denote the same environment even though they are not equal.  The tactic [simpl_env] reassociates all concatenations of environments to the right. *)
(** To make environments easy to read, instead of building them from [nil] and [cons], we prefer to build them from the following components: - [nil]: The empty list. - [one]: Lists consisting of exactly one item. - [++]:  List append.  Furthermore, we introduce compact notation for one (singleton lists): [(x ~ T)] is the same as [one (x, T)]. *)
(** The simpl_env tactic actually puts lists built from only nil, one and [++] into a "normal form". This process reassociates all appends to the right, removes extraneous nils converts cons to singleton lists with an append. *)
(** Note that the [simpl] tactic doesn't produce the "normal form" for environments. It should always be followed up with [simpl_env].  Furthermore, to convert an environment to any equivalent form other than the normal form (perhaps to apply a lemma) use the tactic [rewrite_env]. *)
(** Environment operations. *)
(** The ternary predicate [binds] holds when a given binding is present somewhere in an environment. *)
(** The function [dom] computes the domain of an environment, returning a finite set of [atom]s. Note that we cannot use Coq's equality for finite sets, we must instead use a defined relation [=] for atom set equality. *)
(** The unary predicate [uniq] holds when each atom is bound at most once in an environment. *)
(*************************************************************************)
(** * Typing relation *)
(*************************************************************************)
(** The definition of the typing relation is straightforward.  In order to ensure that the relation holds for only well-formed environments, we check in the [typing_var] case that the environment is [uniq].  The structure of typing derivations implicitly ensures that the relation holds only for locally closed expressions.  Finally, note the use of cofinite quantification in the [typing_abs] case. *)
Inductive typing_c : env -> exp -> typ -> Prop :=
| typing_var_c : forall E (x : atom) T,
uniq E ->
binds x T E ->
typing_c E (fvar x) T
| typing_abs_c : forall (L : atoms) E e T1 T2,
(forall (x:atom), x `notin` L ->
typing_c ((x ~ T1) ++ E) (open e x) T2) ->
typing_c E (abs T1 e) (typ_arrow T1 T2)
| typing_app_c : forall E e1 e2 T1 T2,
typing_c E e1 (typ_arrow T1 T2) ->
typing_c E e2 T1 ->
typing_c E (app e1 e2) T2.
(** We add the constructors of the typing relation as hints to be used by the [auto] and [eauto] tactics. *)
Hint Constructors typing_c : core.
(*************************************************************************)
(** * Weakening *)
(*************************************************************************)
(** Weakening states that if an expression is typeable in some environment, then it is typeable in any well-formed extension of that environment.  This property is needed to prove the substitution lemma.  As stated below, this lemma is not directly proveable.  The natural way to try proving this lemma proceeds by induction on the typing derivation for [e]. *)
(** We are stuck in the [typing_abs_c] case because the induction hypothesis [H0] applies only when we weaken the environment at its head.  In this case, however, we need to weaken the environment in the middle; compare the conclusion at the point where we're stuck to the hypothesis [H], which comes from the given typing derivation.  We can obtain a more useful induction hypothesis by changing the statement to insert new bindings into the middle of the environment, instead of at the head.  However, the proof still gets stuck, as can be seen by examining each of the cases in the proof below.  Note: To view subgoal n in a proof, use the command "n : { ... }".  *)
(** The hypotheses in the [typing_var_c] case include an environment [E0] that that has no relation to what we need to prove.  The missing fact we need is that [E0 = (G ++ E)].  The problem here arises from the fact that Coq's [induction] tactic let's us only prove something about all typing derivations. While it's clear to us that weakening applies to all typing derivations, it's not clear to Coq, because the environment is written using concatenation.  The [induction] tactic expects that all arguments to a judgement are variables.  So we see [E0] in the proof instead of [(G ++ E)].  The solution is to restate the lemma.  For example, we can prove  << forall E F E' e T, typing_c E' e T -> forall G, E' = G ++ E -> uniq (G ++ F ++ E) -> typing_c (G ++ F ++ E) e T. >>  The equality gets around the problem with Coq's [induction] tactic.  The placement of the [(forall G)] quantifier gives us a sufficiently strong induction hypothesis in the [typing_abs_c] case.  However, we prefer not to state the lemma in the way shown above, since it is not as readable as the original statement.  Instead, we use a tactic to introduce the equality within the proof itself. The tactic [(remember t as t')] replaces an object [t] with the identifier [t'] everywhere in the goal and introduces an equality [t' = t] into the context.  It is often combined with [generalize dependent], as illustrated below. *)
(** *** Exercise  See how we use [remember as] in the proof below for weakening. Then, complete the proof below.  HINTS:  - The [typing_var_c] case follows from [binds_weaken], the weakening lemma for the [binds] relation.  - The [typing_abs_c] case follows from the induction hypothesis, but the [apply] tactic may be unable to unify things as you might expect.  -- Recall the [pick fresh and apply] tactic.  -- In order to apply the induction hypothesis, use [rewrite_env] to reassociate the list operations.  -- After applying the induction hypothesis, use [simpl_env] to use [uniq_push].  -- Here, use [auto] to solve facts about finite sets of atoms, since it will simplify the [dom] function behind the scenes.  [fsetdec] does not work with the [dom] function.  - The [typing_app_c] case follows directly from the induction hypotheses. *)
(*************************************************************************)
(** * Substitution *)
(*************************************************************************)
(** Having proved weakening, we can now prove the usual substitution lemma, which we state both in the form we need and in the strengthened form needed to make the proof go through.  << typing_c_subst_simple : forall E e u S T z, typing_c ((z ~ S) ++ E) e T -> typing_c E u S -> typing_c E ([z ~> u] e) T  typing_c_subst : forall E F e u S T z, typing_c (F ++ (z ~ S) ++ E) e T -> typing_c E u S -> typing_c (F ++ E) ([z ~> u] e) T >>  The proof of the strengthened statement proceeds by induction on the given typing derivation for [e].  The most involved case is the one for variables; the others follow from the induction hypotheses. *)
(** *** Exercise  Below, we state what needs to be proved in the [typing_var_c] case of the substitution lemma.  Fill in the proof.  Proof sketch: The proof proceeds by a case analysis on [(x == z)], i.e., whether the two variables are the same or not.  - If [(x = z)], then we need to show [(typing (F ++ E) u T)]. This follows from the given typing derivation for [u] by weakening and the fact that [T] must equal [S].  - If [(x <> z)], then we need to show [(typing (F ++ E) x T)]. This follows by the typing rule for variables.  HINTS: Lemmas [binds_mid_eq], [uniq_remove_mid], and [binds_remove_mid] are useful.  *)
(** *** Exercise  Complete the proof of the substitution lemma. The proof proceeds by induction on the typing derivation for [e].  The initial steps should use [remember as] and [generalize dependent] in a manner similar to the proof of weakening.  HINTS: - Use the lemma proved above for the [typing_var_c] case.  - The [typing_abs_c] case follows from the induction hypothesis. -- Use [simpl] to simplify the substitution.  -- Recall the tactic [pick fresh and apply].  -- In order to use the induction hypothesis, use [subst_open_var_c] to push the substitution under the opening operation.  -- Recall the lemma [typing_c_to_lc_c] and the [rewrite_env] and [simpl_env] tactics.  - The [typing_app_c] case follows from the induction hypotheses. Use [simpl] to simplify the substitution. *)
(*************************************************************************)
(** * Exists-Fresh Definitions *)
(*************************************************************************)
(* The use of cofinite quantification may make some people worry that we are not formalizing the "right" language. Below, we show that the "exists-fresh" version of the rules is the same as the cofinite version. *)
(* First, we redefine the language with the exist-fresh version of the rules everywhere. *)
Inductive typing : env -> exp -> typ -> Prop :=
| typing_var : forall E (x : atom) T,
uniq E ->
binds x T E ->
typing E (fvar x) T
| typing_abs : forall E e T1 T2 (x : atom),
x `notin` fv e ->
typing ((x ~ T1) ++ E) (open e x) T2 ->
typing E (abs T1 e) (typ_arrow T1 T2)
| typing_app : forall E e1 e2 T1 T2,
typing E e1 (typ_arrow T1 T2) ->
typing E e2 T1 ->
typing E (app e1 e2) T2.
Inductive value : exp -> Prop :=
| value_abs : forall e T1,
lc (abs T1 e) ->
value (abs T1 e).
Inductive eval : exp -> exp -> Prop :=
| eval_beta : forall e1 e2 T1,
lc (abs T1 e1) ->
value e2 ->
eval (app (abs T1 e1) e2) (open e1 e2)
| eval_app_1 : forall e1 e1' e2,
lc e2 ->
eval e1 e1' ->
eval (app e1 e2) (app e1' e2)
| eval_app_2 : forall e1 e2 e2',
value e1 ->
eval e2 e2' ->
eval (app e1 e2) (app e1 e2').
Hint Constructors typing value eval : core.
(*************************************************************************)
(** * Equivalence of Exists-Fresh and Cofinite Definitions *)
(*************************************************************************)
(* Next, we prove that these two definitions type the same terms. *)

(* Take-home exercise. *)
Lemma eval_c_to_eval : forall e e',
eval_c e e' -> eval e e'.