Require Import prosa.classic.util.all.
Require Import prosa.classic.model.arrival.basic.task prosa.classic.model.priority prosa.classic.model.arrival.basic.task_arrival.
Require Import prosa.classic.model.schedule.global.workload prosa.classic.model.schedule.global.schedulability
               prosa.classic.model.schedule.global.response_time.
Require Import prosa.classic.model.schedule.global.jitter.job prosa.classic.model.schedule.global.jitter.schedule
               prosa.classic.model.schedule.global.jitter.platform prosa.classic.model.schedule.global.jitter.interference
               prosa.classic.model.schedule.global.jitter.constrained_deadlines.
Require Import prosa.classic.analysis.global.jitter.workload_bound
               prosa.classic.analysis.global.jitter.interference_bound_edf.
From mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop div path.

Module ResponseTimeAnalysisEDFJitter.

  Export JobWithJitter SporadicTaskset ScheduleOfSporadicTaskWithJitter Workload
         Schedulability ResponseTime Priority TaskArrival WorkloadBoundJitter
         InterferenceBoundEDFJitter Platform Interference ConstrainedDeadlines.

  (* In this section, we prove that any fixed point in Bertogna and
     Cirinei's RTA for EDF scheduling modified to account for jitter
     yields a safe response-time bound. This is an extension of the
     analysis found in Chapter 17.1.2 of Baruah et al.'s book
     Multiprocessor Scheduling for Real-time Systems. *)
  Section ResponseTimeBound.

    Context {sporadic_task: eqType}.
    Variable task_cost: sporadic_task -> time.
    Variable task_period: sporadic_task -> time.
    Variable task_deadline: sporadic_task -> time.
    Variable task_jitter: sporadic_task -> time.

    Context {Job: eqType}.
    Variable job_arrival: Job -> time.
    Variable job_cost: Job -> time.
    Variable job_deadline: Job -> time.
    Variable job_task: Job -> sporadic_task.
    Variable job_jitter: Job -> time.

    (* Assume any job arrival sequence... *)
    Context {arr_seq: arrival_sequence Job}.

    (* ... in which jobs arrive sporadically and have valid parameters.
       Note: the jitter of a valid job is bounded by the jitter of its task. *)
    Hypothesis H_sporadic_tasks:
      sporadic_task_model task_period job_arrival job_task arr_seq.
    Hypothesis H_valid_job_parameters:
      forall j,
        arrives_in arr_seq j ->
        valid_sporadic_job_with_jitter task_cost task_deadline task_jitter job_cost
                                                 job_deadline job_task job_jitter j.

    (* Assume that we have a task set where all tasks have valid
       parameters and constrained deadlines, ... *)
    Variable ts: taskset_of sporadic_task.
    Hypothesis H_valid_task_parameters:
      valid_sporadic_taskset task_cost task_period task_deadline ts.
    Hypothesis H_constrained_deadlines:
      forall tsk, tsk \in ts -> task_deadline tsk <= task_period tsk.

    (* ... and that all jobs in the arrival sequence come from the task set. *)
    Hypothesis H_all_jobs_from_taskset:
      forall j,
        arrives_in arr_seq j ->
        job_task j \in ts.

    (* Next, consider any schedule such that...*)
    Variable num_cpus: nat.
    Variable sched: schedule Job num_cpus.
    Hypothesis H_jobs_come_from_arrival_sequence:
      jobs_come_from_arrival_sequence sched arr_seq.

    (* ...jobs are sequential, do not execute before the
       jitter has passed and nor longer than their execution costs. *)
    Hypothesis H_sequential_jobs: sequential_jobs sched.
    Hypothesis H_execute_after_jitter:
      jobs_execute_after_jitter job_arrival job_jitter sched.
    Hypothesis H_completed_jobs_dont_execute:
      completed_jobs_dont_execute job_cost sched.

    (* Assume that there exists at least one processor. *)
    Hypothesis H_at_least_one_cpu: num_cpus > 0.

    (* Assume that the schedule is a work-conserving EDF schedule. *)
    Hypothesis H_work_conserving: work_conserving job_arrival job_cost job_jitter arr_seq sched.
    Hypothesis H_edf_policy: respects_JLFP_policy job_arrival job_cost job_jitter arr_seq sched
                                                  (EDF job_arrival job_deadline).

    (* Let's define some local names to avoid passing many parameters. *)
    Let no_deadline_is_missed_by_tsk (tsk: sporadic_task) :=
      task_misses_no_deadline job_arrival job_cost job_deadline job_task arr_seq sched tsk.
    Let response_time_bounded_by (tsk: sporadic_task) :=
      is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched tsk.

    (* Next we consider the response-time recurrence.
       Assume that a response-time bound R is known...  *)
    Let task_with_response_time := (sporadic_task * time)%type.
    Variable rt_bounds: seq task_with_response_time.

    (* ...for any task in the task set, ... *)
    Hypothesis H_rt_bounds_contains_all_tasks: unzip1 rt_bounds = ts.

    (* Also, assume that R is a fixed-point of the response-time recurrence, ... *)
    Let I (tsk: sporadic_task) (delta: time) :=
      total_interference_bound_edf task_cost task_period task_deadline task_jitter tsk rt_bounds delta.
    Hypothesis H_response_time_is_fixed_point :
      forall tsk R,
        (tsk, R) \in rt_bounds ->
        R = task_cost tsk + div_floor (I tsk R) num_cpus.

    (* ..., and R is no larger than the deadline. *)
    Hypothesis H_tasks_miss_no_deadlines:
      forall tsk R,
        (tsk, R) \in rt_bounds ->
        task_jitter tsk + R <= task_deadline tsk.

    (* In order to prove that R is a response-time bound, we first provide some lemmas. *)
    Section Lemmas.

      (* Let (tsk, R) be any task to be analyzed, with its response-time bound R. *)
      Variable tsk: sporadic_task.
      Variable R: time.
      Hypothesis H_tsk_R_in_rt_bounds: (tsk, R) \in rt_bounds.

      (* Consider any job j of tsk. *)
      Variable j: Job.
      Hypothesis H_j_arrives: arrives_in arr_seq j.
      Hypothesis H_job_of_tsk: job_task j = tsk.

      (* Let t1 be the first point in time where j can actually be scheduled. *)
      Let t1 := job_arrival j + job_jitter j.

      (* Assume that job j did not complete on time, ... *)
      Hypothesis H_j_not_completed: ~~ completed job_cost sched j (t1 + R).

      (* ...and that it is the first job not to satisfy its response-time bound. *)
      Hypothesis H_all_previous_jobs_completed_on_time :
        forall j_other tsk_other R_other,
          arrives_in arr_seq j_other ->
          job_task j_other = tsk_other ->
          (tsk_other, R_other) \in rt_bounds ->
          job_arrival j_other + task_jitter tsk_other + R_other < job_arrival j + task_jitter tsk + R ->
          completed job_cost sched j_other (job_arrival j_other + task_jitter tsk_other + R_other).

      (* Let's call x the interference incurred by job j due to tsk_other, ...*)
      Let x (tsk_other: sporadic_task) :=
        task_interference job_arrival job_cost job_task job_jitter sched j tsk_other t1 (t1 + R).

      (* and X the total interference incurred by job j due to any task. *)
      Let X := total_interference job_arrival job_cost job_jitter sched j t1 (t1 + R).

      (* Recall Bertogna and Cirinei's workload bound ... *)
      Let workload_bound (tsk_other: sporadic_task) (R_other: time) :=
        W_jitter task_cost task_period task_jitter tsk_other R_other R.

      (*... and the EDF-specific bound, ... *)
      Let edf_specific_bound (tsk_other: sporadic_task) (R_other: time) :=
        edf_specific_interference_bound task_cost task_period task_deadline task_jitter tsk tsk_other R_other.

      (* ... which combined form the interference bound. *)
      Let interference_bound (tsk_other: sporadic_task) (R_other: time) :=
        interference_bound_edf task_cost task_period task_deadline task_jitter tsk R (tsk_other, R_other).

      (* Based on the definition of a different task, ... *)
      Let other_task := different_task tsk.

      (* ...let other_tasks denote the set of tasks that are different from tsk. *)
      Let other_tasks :=
        [seq tsk_other <- ts | other_task tsk_other].

      (* Now we establish results the interfering tasks. *)
      Section LemmasAboutInterferingTasks.

        (* Let (tsk_other, R_other) be any pair of higher-priority task and
           response-time bound computed in previous iterations. *)
        Variable tsk_other: sporadic_task.
        Variable R_other: time.
        Hypothesis H_response_time_of_tsk_other: (tsk_other, R_other) \in rt_bounds.

        (* Note that tsk_other is in task set ts ...*)
        Lemma bertogna_edf_tsk_other_in_ts: tsk_other \in ts.
        Proof.
          by rewrite set_mem -H_rt_bounds_contains_all_tasks; apply/mapP; exists (tsk_other, R_other).
        Qed.

        (* Also, R_other is larger than the cost of tsk_other. *)
        Lemma bertogna_edf_R_other_ge_cost :
          R_other >= task_cost tsk_other.
        Proof.
          by rewrite [R_other](H_response_time_is_fixed_point tsk_other);
            first by apply leq_addr.
        Qed.

        (* Since tsk_other cannot interfere more than it executes, we show that
           the interference caused by tsk_other is no larger than workload bound W. *)
        Lemma bertogna_edf_workload_bounds_interference :
          x tsk_other <= workload_bound tsk_other R_other.
        Proof.
          unfold valid_sporadic_job in *.
          rename H_all_previous_jobs_completed_on_time into BEFOREok,
                 H_valid_job_parameters into PARAMS,
                 H_valid_task_parameters into TASK_PARAMS,
                 H_constrained_deadlines into RESTR,
                 H_tasks_miss_no_deadlines into NOMISS.
          unfold x, task_interference, valid_sporadic_job_with_jitter, valid_sporadic_job in *.
          have INts := bertogna_edf_tsk_other_in_ts.
          apply leq_trans with (n := workload job_task sched tsk_other t1 (t1 + R));
            first by apply task_interference_le_workload.
          have BOUND := workload_bounded_by_W task_cost task_period task_deadline task_jitter
            job_arrival job_cost job_task job_deadline job_jitter arr_seq _ sched.
          apply BOUND; try (by done); last 2 first;
            [ by apply NOMISS |
            | by ins; apply TASK_PARAMS
            | by apply RESTR
            | by apply bertogna_edf_R_other_ge_cost].
          {
            intros j0 ARR0 JOB0 LT0; apply BEFOREok; try (by done).
            unfold t1 in *.
            apply leq_trans with (n := job_arrival j + job_jitter j + R); first by done.
            rewrite leq_add2r leq_add2l.
            specialize (PARAMS j H_j_arrives); des.
            rewrite -H_job_of_tsk; apply PARAMS0.
          }
        Qed.

        (* Recall that the edf-specific interference bound also holds. *)
        Lemma bertogna_edf_specific_bound_holds :
          x tsk_other <= edf_specific_bound tsk_other R_other.
        Proof.
          by apply interference_bound_edf_bounds_interference with (job_deadline0 := job_deadline)
                   (arr_seq0 := arr_seq) (ts0 := ts); try (by done);
          [  by apply bertogna_edf_tsk_other_in_ts
          |  by apply H_tasks_miss_no_deadlines
          |  by ins; apply H_all_previous_jobs_completed_on_time with (tsk_other := tsk_other)].
        Qed.

      End LemmasAboutInterferingTasks.

      (* Next we prove some lemmas that help to derive a contradiction.*)
      Section DerivingContradiction.

        (* 0) Since job j did not complete by its response time bound, it follows that
              the total interference X >= R - e_k + 1. *)
        Lemma bertogna_edf_too_much_interference : X >= R - task_cost tsk + 1.
        Proof.
          rename H_completed_jobs_dont_execute into COMP,
                 H_valid_job_parameters into PARAMS, H_response_time_is_fixed_point into REC,
                 H_job_of_tsk into JOBtsk, H_j_not_completed into NOTCOMP.
          unfold completed, valid_sporadic_job_with_jitter, valid_sporadic_job in *.
          unfold X, total_interference; rewrite addn1.
          rewrite -(ltn_add2r (task_cost tsk)).
          rewrite subh1; last by rewrite [R](REC tsk) // leq_addr.
          rewrite -addnBA // subnn addn0.
          move: (NOTCOMP) => /negP NOTCOMP'.
          rewrite -ltnNge in NOTCOMP.
          apply leq_ltn_trans with (n := (\sum_(t1 <= t < t1 + R)
                                       backlogged job_arrival job_cost job_jitter sched j t) +
                                     service sched j (t1 + R)); last first.
          {
            rewrite -addn1 -addnA leq_add2l addn1.
            apply leq_trans with (n := job_cost j); first by done.
            by specialize (PARAMS j H_j_arrives); des; rewrite -JOBtsk.
          }
          unfold service.
          rewrite -> big_cat_nat with (n := t1) (m := 0); rewrite ?leq_addr // /=.
          rewrite (cumulative_service_before_jitter_zero job_arrival job_jitter) // add0n.
          rewrite -big_split /=.
          apply leq_trans with (n := \sum_(t1 <= i < t1 + R) 1);
            first by simpl_sum_const; rewrite addKn.
          apply leq_sum_nat; move => i /andP [GEi LTi] _.
          destruct (backlogged job_arrival job_cost job_jitter sched j i) eqn:BACK;
            first by rewrite -addn1 addnC; apply leq_add.
          apply negbT in BACK.
          rewrite add0n lt0n -not_scheduled_no_service negbK.
          rewrite /backlogged negb_and negbK in BACK.
          move: BACK => /orP [/negP NOTPENDING | SCHED]; last by done.
          exfalso; apply NOTPENDING; unfold pending; apply/andP; split; first by done.
          apply/negP; red; intro BUG; apply NOTCOMP'.
          by apply completion_monotonic with (t := i); try (by done); apply ltnW.
        Qed.

      (* 1) Next, we prove that during the scheduling window of j, any job that is
            scheduled while j is backlogged comes from a different task.
            This follows from the fact that j is the first job not to complete
            by its response-time bound, so previous jobs of j's task must have
            completed by their periods and cannot be pending. *)
        Lemma bertogna_edf_interference_by_different_tasks :
          forall t j_other,
            t1 <= t < t1 + R ->
            backlogged job_arrival job_cost job_jitter sched j t ->
            scheduled sched j_other t ->
            job_task j_other != tsk.
        Proof.
          rename H_all_jobs_from_taskset into FROMTS,
                 H_valid_task_parameters into PARAMS,
                 H_valid_job_parameters into JOBPARAMS,
                 H_job_of_tsk into JOBtsk, H_sporadic_tasks into SPO,
                 H_work_conserving into WORK,
                 H_tsk_R_in_rt_bounds into INbounds,
                 H_all_previous_jobs_completed_on_time into BEFOREok,
                 H_tasks_miss_no_deadlines into NOMISS,
                 H_constrained_deadlines into CONSTR.
          unfold valid_sporadic_job_with_jitter, valid_sporadic_job in *.
          move => t j_other /andP [LEt GEt] BACK SCHED.
          apply/eqP; red; intro SAMEtsk.
          move: SCHED => /existsP [cpu SCHED].
          have SCHED': scheduled sched j_other t by apply/existsP; exists cpu.
          clear SCHED; rename SCHED' into SCHED.
          have ARRother: arrives_in arr_seq j_other.
            by apply (H_jobs_come_from_arrival_sequence j_other t).
          move: (SCHED) => PENDING.
          apply scheduled_implies_pending with (job_cost0 := job_cost) (job_jitter0 := job_jitter)
            (job_arrival0 := job_arrival) in PENDING; try (by done).
          destruct (ltnP (job_arrival j_other) (job_arrival j)) as [BEFOREother | BEFOREj].
          {
            move: (BEFOREother) => LT; rewrite -(ltn_add2r R) in LT.
            exploit (BEFOREok j_other tsk R ARRother SAMEtsk INbounds).
            {
              rewrite -addnA [_ + R]addnC addnA -[(_ + _) + R]addnA [_ tsk + R]addnC addnA.
              by rewrite ltn_add2r.
            }
            intros COMP.
            move: PENDING => /andP [_ /negP NOTCOMP]; apply NOTCOMP.
            apply completion_monotonic with (t0 := job_arrival j_other + task_jitter tsk + R);
              try by done.
            apply leq_trans with (n := job_arrival j);
              last by apply leq_trans with (n := t1); [by apply leq_addr | by done].
            apply leq_trans with (n := job_arrival j_other + task_period tsk).
            {
              rewrite -addnA leq_add2l.
              by apply leq_trans with (n := task_deadline tsk);
                [by apply NOMISS | by apply CONSTR; rewrite -JOBtsk FROMTS].
            }
            rewrite -SAMEtsk; apply SPO; [ | by done | by done| by rewrite JOBtsk | by apply ltnW].
            by red; intro EQ; subst; rewrite ltnn in BEFOREother.
          }
          {
            move: PENDING => /andP [ARRIVED _].
            exploit (SPO j j_other); try (by done); [ | by rewrite SAMEtsk | ]; last first.
            {
              apply/negP; rewrite -ltnNge JOBtsk.
              apply leq_trans with (n := job_arrival j + task_deadline tsk);
                last by rewrite leq_add2l; apply CONSTR; rewrite -JOBtsk FROMTS.
              apply leq_trans with (n := job_arrival j + task_jitter tsk + R);
                last by rewrite -addnA leq_add2l; apply NOMISS.
              apply leq_trans with (n := t1 + R); last first.
              {
                rewrite leq_add2r leq_add2l -JOBtsk.
                by specialize (JOBPARAMS j H_j_arrives); des.
              }
              apply leq_ltn_trans with (n := job_arrival j_other + job_jitter j_other);
                first by apply leq_addr.
              by apply leq_ltn_trans with (n := t).
            }
            by intros EQtsk; subst j_other; rewrite /backlogged SCHED andbF in BACK.
          }
        Qed.

      (* 2) In order to use the lemmas in constrained_deadlines.v, we show that
            all jobs released before the end of the interval complete by their
            periods. This follows trivially from the hypothesis that all jobs
            before (t1 + R) complete by their response-time bounds.
            With this lemma, we can conclude that during job j's scheduling
            window there cannot be multiple pending jobs of each task.*)
        Lemma bertogna_edf_all_previous_jobs_complete_by_their_period:
          forall t j0,
            t < t1 + R ->
            arrives_in arr_seq j0 ->
            job_arrival j0 + task_period (job_task j0) <= t ->
            completed job_cost sched j0
               (job_arrival j0 + task_period (job_task j0)).
        Proof.
          rename H_valid_job_parameters into JOBPARAMS,
                 H_rt_bounds_contains_all_tasks into UNZIP,
                 H_job_of_tsk into JOBtsk,
                 H_constrained_deadlines into CONSTR,
                 H_tasks_miss_no_deadlines into NOMISS,
                 H_all_jobs_from_taskset into FROMTS,
                 H_all_previous_jobs_completed_on_time into BEFOREok.
          unfold valid_sporadic_job_with_jitter, valid_sporadic_job in *.
          intros t j0 LEt ARR0 LE.
          cut ((job_task j0) \in unzip1 rt_bounds = true); last by rewrite UNZIP FROMTS.
          move => /mapP [p IN EQ]; destruct p as [tsk' R0]; simpl in *; subst tsk'.
          apply completion_monotonic with (t0 := job_arrival j0 + task_jitter (job_task j0) + R0).
          {
            rewrite -addnA leq_add2l.
            apply leq_trans with (n := task_deadline (job_task j0));
              [by apply NOMISS | by apply CONSTR; rewrite FROMTS].
          }
          apply BEFOREok with (tsk_other := (job_task j0)); try by done.
          apply leq_ltn_trans with (n := t); last first.
          {
            apply leq_trans with (n := t1 + R); first by done.
            rewrite leq_add2r leq_add2l -JOBtsk.
            by specialize (JOBPARAMS j H_j_arrives); des.
          }
          apply leq_trans with (n := job_arrival j0 + task_period (job_task j0)); last by done.
          by rewrite -addnA leq_add2l; apply leq_trans with (n := task_deadline (job_task j0));
            [by apply NOMISS | apply CONSTR; rewrite FROMTS].
        Qed.

        (* Let's define a predicate to identify the other tasks that are scheduled. *)
        Let other_scheduled_task (t: time) (tsk_other: sporadic_task) :=
          task_is_scheduled job_task sched tsk_other t &&
          other_task tsk_other.

        (* 3) Now we prove that, at all times that j is backlogged, the number
              of tasks other than tsk that are scheduled is exactly the number
              of processors in the system. This is required to prove lemma (4). *)
        Lemma bertogna_edf_all_cpus_are_busy:
          forall t,
            t1 <= t < t1 + R ->
            backlogged job_arrival job_cost job_jitter sched j t ->
            count (other_scheduled_task t) ts = num_cpus.
        Proof.
          rename H_all_jobs_from_taskset into FROMTS,
                 H_valid_task_parameters into PARAMS,
                 H_valid_job_parameters into JOBPARAMS,
                 H_job_of_tsk into JOBtsk, H_jobs_come_from_arrival_sequence into FROMSEQ,
                 H_sporadic_tasks into SPO,
                 H_tsk_R_in_rt_bounds into INbounds,
                 H_all_previous_jobs_completed_on_time into BEFOREok,
                 H_tasks_miss_no_deadlines into NOMISS,
                 H_rt_bounds_contains_all_tasks into UNZIP,
                 H_constrained_deadlines into RESTR,
                 H_work_conserving into WORK.
          unfold x, X, total_interference, task_interference,
                 valid_sporadic_job_with_jitter, valid_sporadic_job in *.
          move => t /andP [LEt LTt] BACK.
          have PLAT := platform_cpus_busy_with_interfering_tasks task_cost task_period task_deadline
            job_arrival job_cost job_task job_jitter arr_seq sched FROMSEQ WORK.
          apply PLAT with (j := j); try (by done);
            [by apply PARAMS; rewrite -JOBtsk; apply FROMTS | clear PLAT].
          intros j0 tsk0 ARR0 TSK0 LE.
          cut (tsk0 \in unzip1 rt_bounds = true); last by rewrite UNZIP -TSK0 FROMTS //.
          move => /mapP [p IN EQ]; destruct p as [tsk' R0]; simpl in *; subst tsk'.
          apply completion_monotonic with (t0 := job_arrival j0 + task_jitter tsk0 + R0); try (by done).
          {
            rewrite -addnA leq_add2l TSK0.
            apply leq_trans with (n := task_deadline tsk0); first by apply NOMISS.
            by apply RESTR; rewrite -TSK0 FROMTS.
          }
          {
            apply BEFOREok with (tsk_other := tsk0); try (by done).
            apply leq_trans with (n := t1 + R);
              last by rewrite leq_add2r leq_add2l -JOBtsk; specialize (JOBPARAMS j H_j_arrives); des.
            apply leq_ltn_trans with (n := t); last by done.
            apply leq_trans with (n := job_arrival j0 + task_period tsk0); last by done.
            rewrite -addnA leq_add2l.
            apply leq_trans with (n := task_deadline tsk0); first by apply NOMISS.
            by apply RESTR; rewrite -TSK0; apply FROMTS.
          }
        Qed.

      (* 4) Next, we prove that the sum of the interference of each task is equal
          to the total interference multiplied by the number of processors. This
          holds because interference only occurs when all processors are busy.
          With this lemma we can relate per-task interference with the total
          interference incurred by j (backlogged time). *)
        Lemma bertogna_edf_interference_on_all_cpus :
          \sum_(tsk_k <- other_tasks) x tsk_k = X * num_cpus.
        Proof.
          have DIFFTASK := bertogna_edf_interference_by_different_tasks.
          rename H_all_jobs_from_taskset into FROMTS, H_valid_task_parameters into PARAMS,
                 H_job_of_tsk into JOBtsk, H_sporadic_tasks into SPO,
                 H_work_conserving into WORK, H_jobs_come_from_arrival_sequence into FROMSEQ,
                 H_tsk_R_in_rt_bounds into INbounds,
                 H_all_previous_jobs_completed_on_time into BEFOREok,
                 H_tasks_miss_no_deadlines into NOMISS, H_rt_bounds_contains_all_tasks into UNZIP,
                 H_constrained_deadlines into CONSTR.
          unfold sporadic_task_model in *.
          unfold x, X, total_interference, task_interference.
          rewrite -big_mkcond -exchange_big big_distrl /= mul1n.
          rewrite [\sum_(_ <= _ < _ | backlogged _ _ _ _ _ _) _]big_mkcond.
          apply eq_big_nat; move => t /andP [GEt LTt].
          destruct (backlogged job_arrival job_cost job_jitter sched j t) eqn:BACK;
            last by rewrite big1 //; ins; rewrite big1.
          rewrite big_mkcond /=.
          rewrite exchange_big /=.
          apply eq_trans with (y := \sum_(cpu < num_cpus) 1); last by simpl_sum_const.
          apply eq_bigr; intros cpu _.
          move: (WORK j t H_j_arrives BACK cpu) => [j_other /eqP SCHED]; unfold scheduled_on in *.
          have ARRother: arrives_in arr_seq j_other.
            by apply (FROMSEQ j_other t); apply/existsP; exists cpu; apply/eqP.
          rewrite (bigD1_seq (job_task j_other)) /=; last by rewrite filter_uniq; destruct ts.
          {
            rewrite (eq_bigr (fun i => 0));
              last by intros i DIFF; rewrite /task_scheduled_on SCHED;apply/eqP;rewrite eqb0 eq_sym.
            simpl_sum_const; apply/eqP; rewrite eqb1.
            by unfold task_scheduled_on; rewrite SCHED.
          }
          rewrite mem_filter; apply/andP; split; last by apply FROMTS.
          apply DIFFTASK with (t := t); [by auto | by done |].
          by apply/existsP; exists cpu; apply/eqP.
        Qed.

        (* Before stating the next lemma, let (num_tasks_exceeding delta) be the
           number of interfering tasks whose interference x is larger than delta. *)
        Let num_tasks_exceeding delta := count (fun i => x i >= delta) (other_tasks).

        (* 5) Now we prove that, for any delta, if (num_task_exceeding delta > 0), then the
              cumulative interference caused by the complementary set of interfering tasks fills
              the remaining, not-completely-full (num_cpus - num_tasks_exceeding delta)
              processors. *)
        Lemma bertogna_edf_interference_in_non_full_processors :
          forall delta,
            0 < num_tasks_exceeding delta < num_cpus ->
            \sum_(i <- other_tasks | x i < delta) x i >= delta * (num_cpus - num_tasks_exceeding delta).
        Proof.
          have COMP := bertogna_edf_all_previous_jobs_complete_by_their_period.
          have INV := bertogna_edf_all_cpus_are_busy.
          rename H_all_jobs_from_taskset into FROMTS, H_valid_task_parameters into PARAMS,
                 H_job_of_tsk into JOBtsk, H_sporadic_tasks into SPO,
                 H_tsk_R_in_rt_bounds into INbounds, H_jobs_come_from_arrival_sequence into FROMSEQ,
                 H_all_previous_jobs_completed_on_time into BEFOREok,
                 H_tasks_miss_no_deadlines into NOMISS,
                 H_constrained_deadlines into CONSTR, H_sequential_jobs into SEQ.
          unfold sporadic_task_model in *.
          move => delta /andP [HAS LT].
          rewrite -has_count in HAS.

          set some_interference_A := fun t =>
            has (fun tsk_k => backlogged job_arrival job_cost job_jitter sched j t &&
                              (x tsk_k >= delta) &&
                              task_is_scheduled job_task sched tsk_k t) other_tasks.
          set total_interference_B := fun t =>
              backlogged job_arrival job_cost job_jitter sched j t *
              count (fun tsk_k => (x tsk_k < delta) &&
                    task_is_scheduled job_task sched tsk_k t) other_tasks.

          apply leq_trans with ((\sum_(t1 <= t < t1 + R)
                                some_interference_A t) * (num_cpus - num_tasks_exceeding delta)).
          {
            rewrite leq_mul2r; apply/orP; right.
            move: HAS => /hasP HAS; destruct HAS as [tsk_a INa LEa].
            apply leq_trans with (n := x tsk_a); first by apply LEa.
            unfold x, task_interference, some_interference_A.
            apply leq_sum_nat; move => t /andP [GEt LTt] _.
            destruct (backlogged job_arrival job_cost job_jitter sched j t) eqn:BACK;
              last by rewrite (eq_bigr (fun x => 0)); [by simpl_sum_const | by ins].
            destruct ([exists cpu, task_scheduled_on job_task sched tsk_a cpu t]) eqn:SCHED;
              last first.
            {
              apply negbT in SCHED; rewrite negb_exists in SCHED; move: SCHED => /forallP ALL.
              rewrite (eq_bigr (fun x => 0)); first by simpl_sum_const.
              by intros cpu _; specialize (ALL cpu); apply negbTE in ALL; rewrite ALL.
            }
            move: SCHED => /existsP [cpu SCHED].
            apply leq_trans with (n := 1); last first.
            {
              rewrite lt0b; apply/hasP; exists tsk_a; first by done.
              by rewrite LEa 2!andTb; apply/existsP; exists cpu.
            }
            rewrite (bigD1 cpu) /= // SCHED.
            rewrite (eq_bigr (fun x => 0)); first by simpl_sum_const; rewrite leq_b1.
            intros cpu' DIFF.
            apply/eqP; rewrite eqb0; apply/negP.
            intros SCHED'.
            move: DIFF => /negP DIFF; apply DIFF; apply/eqP.
            unfold task_scheduled_on in *.
            destruct (sched cpu t) as [j1|] eqn:SCHED1; last by done.
            destruct (sched cpu' t) as [j2|] eqn:SCHED2; last by done.
            move: SCHED SCHED' => /eqP JOB /eqP JOB'.
            subst tsk_a; symmetry in JOB'.
            have ARR1: arrives_in arr_seq j1.
              by apply (FROMSEQ j1 t); apply/existsP; exists cpu; apply/eqP.
            have ARR2: arrives_in arr_seq j2.
              by apply (FROMSEQ j2 t); apply/existsP; exists cpu'; apply/eqP.
            assert (PENDING1: pending job_arrival job_cost job_jitter sched j1 t).
            {
              apply scheduled_implies_pending; try by done.
              by apply/existsP; exists cpu; apply/eqP.
            }
            assert (PENDING2: pending job_arrival job_cost job_jitter sched j2 t).
            {
              apply scheduled_implies_pending; try by done.
              by apply/existsP; exists cpu'; apply/eqP.
            }
            assert (BUG: j1 = j2).
            {
              apply platform_at_most_one_pending_job_of_each_task with (task_cost0 := task_cost)
               (job_jitter0 := job_jitter) (task_period0 := task_period) (job_cost0 := job_cost)
               (task_deadline0 := task_deadline) (tsk0 := tsk) (job_task0 := job_task)
               (sched0 := sched) (job_arrival0 := job_arrival) (arr_seq0 := arr_seq)
               (j0 := j) (t0 := t);
              rewrite ?JOBtsk ?SAMEtsk //; first by apply PARAMS; rewrite -JOBtsk FROMTS.
              by intros j0 tsk0 ARR0 TSK0 LE; apply (COMP t); rewrite ?TSK0.
            }
            by subst j2; apply SEQ with (j := j1) (t := t).
          }

          apply leq_trans with (\sum_(t1 <= t < t1 + R) total_interference_B t).
          {
            rewrite big_distrl /=.
            apply leq_sum_nat; move => t LEt _.
            unfold some_interference_A, total_interference_B.
            destruct (backlogged job_arrival job_cost job_jitter sched j t) eqn:BACK;
              [rewrite mul1n /= | by rewrite has_pred0 //].

            destruct (has (fun tsk_k : sporadic_task => (delta <= x tsk_k) &&
                       task_is_scheduled job_task sched tsk_k t) other_tasks) eqn:HAS';
              last by done.
            rewrite mul1n; move: HAS => /hasP [tsk_k INk LEk].
            unfold num_tasks_exceeding.
            apply leq_trans with (n := num_cpus -
                         count (fun i => (x i >= delta) &&
                            task_is_scheduled job_task sched i t) other_tasks).
            {
              apply leq_sub2l.
              rewrite -2!sum1_count big_mkcond /=.
              rewrite [\sum_(_ <- _ | _ <= _)_]big_mkcond /=.
              apply leq_sum; intros i _.
              by destruct (task_is_scheduled job_task sched i t);
                [by rewrite andbT | by rewrite andbF].
            }
            rewrite -count_filter -[count _ other_tasks]count_filter.
            eapply leq_trans with (n := count (predC (fun tsk => delta <= x tsk)) _);
              last by apply eq_leq, eq_in_count; red; ins; rewrite ltnNge.
            rewrite leq_subLR count_predC size_filter.
            by apply leq_trans with (n := count (other_scheduled_task t) ts);
              [by rewrite INV | by rewrite count_filter].
          }
          {
            unfold x at 2, total_interference_B.
            rewrite exchange_big /=; apply leq_sum; intros t _.
            destruct (backlogged job_arrival job_cost job_jitter sched j t) eqn:BACK; last by ins.
            rewrite mul1n -sum1_count.
            rewrite big_mkcond [\sum_(i <- other_tasks | _ < _) _]big_mkcond /=.
            apply leq_sum_seq; move => tsk_k IN _.
            destruct (x tsk_k < delta); [rewrite andTb | by rewrite andFb].
            destruct (task_is_scheduled job_task sched tsk_k t) eqn:SCHED; last by done.
            move: SCHED => /existsP [cpu SCHED].
            by rewrite (bigD1 cpu) /= // SCHED.
          }
        Qed.

        (* 6) Based on lemma (5), we prove that, for any interval delta, if the sum of per-task
              interference exceeds (delta * num_cpus), the same applies for the
              sum of the minimum of the interference and delta. *)
        Lemma bertogna_edf_minimum_exceeds_interference :
          forall delta,
            \sum_(tsk_k <- other_tasks) x tsk_k >= delta * num_cpus ->
               \sum_(tsk_k <- other_tasks) minn (x tsk_k) delta >=
               delta * num_cpus.
        Proof.
          intros delta SUMLESS.
          set more_interf := fun tsk_k => x tsk_k >= delta.
          rewrite [\sum_(_ <- _) minn _ _](bigID more_interf) /=.
          unfold more_interf, minn.
          rewrite [\sum_(_ <- _ | delta <= _)_](eq_bigr (fun i => delta));
            last by intros i COND; rewrite leqNgt in COND; destruct (delta > x i).
          rewrite [\sum_(_ <- _ | ~~_)_](eq_big (fun i => x i < delta)
                                                (fun i => x i));
            [| by red; ins; rewrite ltnNge
             | by intros i COND; rewrite -ltnNge in COND; rewrite COND].

          (* Case 1: num_tasks_exceeding = 0 *)
          destruct (~~ has (fun i => delta <= x i) other_tasks) eqn:HASa.
          {
            rewrite [\sum_(_ <- _ | _ <= _) _]big_hasC; last by apply HASa.
            rewrite big_seq_cond; move: HASa => /hasPn HASa.
            rewrite add0n (eq_bigl (fun i => (i \in other_tasks) && true));
              last by red; intros tsk_k; destruct (tsk_k \in other_tasks) eqn:INk;
                [by rewrite andTb ltnNge; apply HASa | by rewrite andFb].
            by rewrite -big_seq_cond.
          } apply negbFE in HASa.

          (* Case 2: num_tasks_exceeding >= num_cpus *)
          destruct (num_tasks_exceeding delta >= num_cpus) eqn:CARD.
          {
            apply leq_trans with (delta * num_tasks_exceeding delta);
              first by rewrite leq_mul2l; apply/orP; right.
            unfold num_tasks_exceeding; rewrite -sum1_count big_distrr /=.
            rewrite -[\sum_(_ <- _ | _) _]addn0.
            by apply leq_add; [by apply leq_sum; ins; rewrite muln1|by ins].
          } apply negbT in CARD; rewrite -ltnNge in CARD.

          (* Case 3: num_tasks_exceeding < num_cpus *)
          rewrite big_const_seq iter_addn addn0; fold num_tasks_exceeding.
          apply leq_trans with (n := delta * num_tasks_exceeding delta +
                                     delta * (num_cpus - num_tasks_exceeding delta));
            first by rewrite -mulnDr subnKC //; apply ltnW.
          rewrite leq_add2l; apply bertogna_edf_interference_in_non_full_processors.
          by apply/andP; split; first by rewrite -has_count.
        Qed.

        (* 7) Next, using lemmas (0), (4) and (6) we prove that the reduction-based
              interference bound is not enough to cover the sum of the minima over all tasks
              (artifact of the proof by contradiction). *)
        Lemma bertogna_edf_sum_exceeds_total_interference:
          \sum_((tsk_other, R_other) <- rt_bounds | other_task tsk_other)
            minn (x tsk_other) (R - task_cost tsk + 1) > I tsk R.
        Proof.
          have GE_COST := bertogna_edf_R_other_ge_cost.
          have EXCEEDS := bertogna_edf_minimum_exceeds_interference.
          have ALLBUSY := bertogna_edf_interference_on_all_cpus.
          have TOOMUCH := bertogna_edf_too_much_interference.
          rename H_rt_bounds_contains_all_tasks into UNZIP,
            H_response_time_is_fixed_point into REC.
          apply leq_trans with (n := \sum_(tsk_other <- other_tasks) minn (x tsk_other) (R - task_cost tsk + 1));
            last first.
          {
            rewrite (eq_bigr (fun i => minn (x (fst i)) (R - task_cost tsk + 1)));
              last by ins; destruct i.
            move: UNZIP => UNZIP.
            assert (FILTER: filter other_task (unzip1 rt_bounds) =
                            filter other_task ts).
              by f_equal.
            unfold other_tasks; rewrite -FILTER; clear FILTER.
            rewrite -[\sum_(_ <- rt_bounds | _)_]big_filter.
            assert (SUBST: [seq i <- rt_bounds
                             | let '(tsk_other, _) := i in other_task tsk_other] =
                           [seq i <- rt_bounds | other_task (fst i)]).
            {
              by apply eq_filter; red; intro i; destruct i.
            } rewrite SUBST; clear SUBST.
            have MAP := big_map (fun x => fst x) (fun i => true) (fun i => minn (x i) (R - task_cost tsk + 1)).
            by rewrite -MAP; apply eq_leq; f_equal; rewrite filter_map.
          }

          apply ltn_div_trunc with (d := num_cpus); first by apply H_at_least_one_cpu.
          rewrite -(ltn_add2l (task_cost tsk)) -REC; last by done.
          rewrite -addn1 -leq_subLR.
          rewrite -[R + 1 - _]subh1; last by apply GE_COST.
          rewrite leq_divRL; last by apply H_at_least_one_cpu.
          apply EXCEEDS.
          apply leq_trans with (n := X * num_cpus); last by rewrite ALLBUSY.
          by rewrite leq_mul2r; apply/orP; right; apply TOOMUCH.
        Qed.

        (* 8) After concluding that the sum of the minima exceeds (R - e_i + 1),
              we prove that there exists a tuple (tsk_k, R_k) that satisfies
              min (x_k, R - e_i + 1) > min (W_k, I_edf, R - e_i + 1).
              This implies that either x_k > W_k or x_k > I_edf, which is a contradiction,
              since both W_k and I_edf are valid task interference bounds. *)
        Lemma bertogna_edf_exists_task_that_exceeds_bound :
          exists tsk_other R_other,
            (tsk_other, R_other) \in rt_bounds /\
            (minn (x tsk_other) (R - task_cost tsk + 1) > interference_bound tsk_other R_other).
        Proof.
          have SUM := bertogna_edf_sum_exceeds_total_interference.
          have BOUND := bertogna_edf_workload_bounds_interference.
          have EDFBOUND := bertogna_edf_specific_bound_holds.
          rename H_rt_bounds_contains_all_tasks into UNZIP.
          assert (HAS: has (fun tup : task_with_response_time =>
                              let (tsk_other, R_other) := tup in
                              (tsk_other \in ts) && other_task tsk_other &&
                                (minn (x tsk_other) (R - task_cost tsk + 1)  >
                                interference_bound tsk_other R_other))
                           rt_bounds).
          {
            apply/negP; unfold not; intro NOTHAS.
            move: NOTHAS => /negP /hasPn ALL.
            rewrite -[_ < _]negbK in SUM.
            move: SUM => /negP SUM; apply SUM; rewrite -leqNgt.
            unfold I, total_interference_bound_edf.
            rewrite big_seq_cond [X in _ <= X]big_seq_cond.
            apply leq_sum; move => tsk_k /andP [INBOUNDSk INTERFk]; destruct tsk_k as [tsk_k R_k].
            specialize (ALL (tsk_k, R_k) INBOUNDSk).
            unfold interference_bound_edf; simpl in *.
            rewrite leq_min; apply/andP; split.
            {
              unfold interference_bound; rewrite leq_min; apply/andP; split;
                last by rewrite geq_minr.
              by apply leq_trans with (n := x tsk_k);
                [by rewrite geq_minl | by apply BOUND].
            }
            {
              apply leq_trans with (n := x tsk_k); first by rewrite geq_minl.
              by apply EDFBOUND.
            }
          }
          move: HAS => /hasP HAS; destruct HAS as [[tsk_k R_k] HPk MIN].
          move: MIN => /andP [/andP [INts INTERFk] MINk].
          by exists tsk_k, R_k; repeat split.
        Qed.

      End DerivingContradiction.

    End Lemmas.

    Section MainProof.

      (* Let (tsk, R) be any task to be analyzed, with its response-time bound R. *)
      Variable tsk: sporadic_task.
      Variable R: time.
      Hypothesis H_tsk_R_in_rt_bounds: (tsk, R) \in rt_bounds.

      (* Using the lemmas above, we prove that R bounds the response time of task tsk. *)
      Theorem bertogna_cirinei_response_time_bound_edf :
        response_time_bounded_by tsk (task_jitter tsk + R).
      Proof.
        have EXISTS := bertogna_edf_exists_task_that_exceeds_bound.
        have BASICBOUND := bertogna_edf_workload_bounds_interference.
        have EDFBOUND := bertogna_edf_specific_bound_holds.
        rename H_valid_job_parameters into JOBPARAMS.
        unfold valid_sporadic_job_with_jitter, valid_sporadic_job in *.
        intros j ARRj JOBtsk.

        rewrite addnA.
        (* First, rewrite the claim in terms of the *absolute* response-time bound (arrival + R) *)
        remember (job_arrival j + task_jitter tsk + R) as ctime.

        revert H_tsk_R_in_rt_bounds.
        generalize dependent R; generalize dependent tsk; generalize dependent j.

        (* Now, we apply strong induction on the absolute response-time bound. *)
        induction ctime as [ctime IH] using strong_ind.

        intros j ARRj tsk' JOBtsk R' EQc INbounds; subst ctime.

        (* First, let's simplify the induction hypothesis. *)
        assert (BEFOREok: forall j0 tsk R0,
                                 arrives_in arr_seq j0 ->
                                 job_task j0 = tsk ->
                               (tsk, R0) \in rt_bounds ->
                               job_arrival j0 + task_jitter tsk + R0 < job_arrival j + task_jitter tsk' + R' ->
                               service sched j0 (job_arrival j0 + task_jitter tsk + R0) >= job_cost j0).
        {
            by ins; apply IH with (tsk := tsk0) (R := R0).
        }
        clear IH.

        (* The proof follows by contradiction. Assume that job j does not complete by its
           response-time bound. By the induction hypothesis, all jobs with absolute
           response-time bound t < (job_arrival j + R) have correct response-time bounds. *)
        destruct (completed job_cost sched j (job_arrival j + job_jitter j + R')) eqn:NOTCOMP.
        {
          apply completion_monotonic with (t := job_arrival j + job_jitter j + R'); try (by done).
          rewrite leq_add2r leq_add2l.
          specialize (JOBPARAMS j ARRj); des.
          by rewrite -JOBtsk; apply JOBPARAMS0.
        }
        apply negbT in NOTCOMP; exfalso.

        (* Next, we derive a contradiction using the previous lemmas. *)
        exploit (EXISTS tsk' R' INbounds j ARRj JOBtsk NOTCOMP).
        {
          by ins; apply IH with (tsk := tsk_other) (R := R_other).
        }
        intro EX; destruct EX as [tsk_other [R_other [HP LTmin]]].
        unfold interference_bound_edf, interference_bound_generic in LTmin.
        rewrite minnAC in LTmin; apply min_lt_same in LTmin.
        specialize (BASICBOUND tsk' R' j ARRj JOBtsk BEFOREok tsk_other R_other HP).
        specialize (EDFBOUND tsk' R' j ARRj JOBtsk BEFOREok tsk_other R_other HP).
        unfold minn in LTmin; clear -LTmin HP BASICBOUND EDFBOUND tsk; desf.
        {
          by apply (leq_ltn_trans BASICBOUND) in LTmin; rewrite ltnn in LTmin.
        }
        {
          by apply (leq_ltn_trans EDFBOUND) in LTmin; rewrite ltnn in LTmin.
        }
      Qed.

    End MainProof.

  End ResponseTimeBound.

End ResponseTimeAnalysisEDFJitter.


Require Import Metalib.Metatheory.
Require Import Coq.Program.Equality.
Require Import Strings.String.
Require Import Program.Tactics.
Require Import Language Tactical.
Require Import Subtyping.Subtyping.
Require Import Subtyping.Splitable.

Set Printing Parentheses.

(** * Definitions *)

(** ** Arguments *)

Definition arg := option type.

(** ** Applicative Subtyping (Binary) *)

Inductive auxas : arg -> type -> Prop :=
| Aas_Refl : forall A,
    auxas None A
| Aas_Arr : forall A B C,
    sub C A ->
    auxas (Some C) (Arr A B)
| Aas_And_L : forall A B C,
    auxas (Some C) A ->
    auxas (Some C) (And A B)
| Aas_And_R : forall A B C,
    auxas (Some C) B ->
    auxas (Some C) (And A B).

Hint Constructors auxas : core.
Notation "appsub? S A" := (auxas S A) (at level 40).

(** ** Applicative Subtyping *)

Inductive appsub : arg -> type -> type -> Prop :=
| As_Refl : forall A,
    appsub None A A
| As_Arr : forall A B C,
    sub C A ->
    appsub (Some C) (Arr A B) B
| As_And_L : forall A B C D,
    appsub (Some C) A D ->
    not (auxas (Some C) B) ->
    appsub (Some C) (And A B) D
| As_And_R : forall A B C D,
    appsub (Some C) B D ->
    not (auxas (Some C) A) ->
    appsub (Some C) (And A B) D
| As_And_P : forall A B C D1 D2,
    appsub (Some C) A D1 ->
    appsub (Some C) B D2 ->
    appsub (Some C) (And A B) (And D1 D2).

Hint Constructors appsub : core.
Notation "S ⊢ A <: B" := (appsub S A B) (at level 40).

(** * Automations *)

(** ** Structural Inversions *)

Ltac solve_auxas :=
  match goal with
  | [H: auxas _ Int |- _] => (inversion H)
  | [H: auxas _ Top |- _] => (inversion H)
  end.

Ltac solve_appsub :=
  match goal with
  | [H: appsub _ Int _ |- _] => (inversion H)
  | [H: appsub _ Top _ |- _] => (inversion H)
  end.

Hint Extern 5 => solve_auxas : core.
Hint Extern 5 => solve_appsub : core.

(** ** Contradictions *)

Lemma appsub_to_auxas :
  forall A B S,
    appsub S A B ->
    auxas S A.
Proof.
  intros.
  dependent induction H; eauto.
Qed.

Hint Resolve appsub_to_auxas : core.

Lemma auxas_false :
  forall A B S,
    not (auxas S A) ->
    appsub S A B ->
    False.
Proof.
  intros.
  eapply appsub_to_auxas in H0.
  contradiction.
Qed.

Ltac contra_appsub :=
  match goal with
  | [H1: not (auxas ?S ?A), H2: appsub ?S ?A _ |- _] =>
      (pose proof (auxas_false _ _ _ H1 H2) as Contra; inversion Contra)
  | [H1: not (auxas ?S ?A), H2: auxas ?S ?A |- _] =>
      (contradiction)
  end.

Hint Extern 5 => contra_appsub : core.

(** * Properties *)

(** ** Determinism *)

Lemma appsub_determinism :
  forall A B1 B2 S,
    appsub S A B1 ->
    appsub S A B2 ->
    B1 = B2.
Proof.
  introv As1 As2. gen B2.
  dependent induction As1; intros;
    dependent destruction As2; eauto.
  pose proof (IHAs1_1 _ As2_1).
  pose proof (IHAs1_2 _ As2_2).
  congruence.
Qed.

(** ** Completeness *)

Lemma appsub_complete :
  forall A B C,
    appsub (Some B) A C -> sub A (Arr B C).
Proof.
  introv As.
  dependent induction As; eauto.
  - pose proof (IHAs1 B).
    pose proof (IHAs2 B).
    eapply Sub_And; eauto.
Qed.

(** * Appsub & Isomorphic Subtyping *)

(** ** Inversion Lemmas *)

Lemma appsub_split_inversion :
  forall A B C B1 B2,
    appsub (Some A) B C ->
    splitable B B1 B2 ->
    (appsub (Some A) B1 C) /\ (not (auxas (Some A) B2)) \/
      (appsub (Some A) B2 C) /\ (not (auxas (Some A) B1)) \/
      (exists C1 C2, (appsub (Some A) B1 C1) /\ (appsub (Some A) B2 C2) /\ (isosub (And C1 C2) C)).
Proof.
  introv Has Hspl.
  gen A C B1 B2.
  proper_ind B; intros; eauto. subst_splitable.
  dependent destruction Hspl; eauto.
  - Case "And".
    dependent destruction Has; eauto.
    right. right. exists D1. exists D2.
    split; eauto.
  - Case "Arr".
    right. right.
    dependent destruction Has.
    pose proof (As_Arr _ B1 _ H) as As1.
    pose proof (As_Arr _ B2 _ H) as As2.
    pose proof (IHPr1 _ _ As1).
    pose proof (IHPr2 _ _ As2).
    dependent destruction Hspl.
    * exists A1. exists B. split; eauto.
    * exists (Arr A1 B1). exists (Arr A1 B2).
      split; eauto.
Qed.

(** ** Arguments *)

Lemma auxas_iso1 :
  forall A B H,
    auxas (Some A) B ->
    isosub A H ->
    auxas (Some H) B.
Proof.
  introv Aas Isub.
  gen A H.
  proper_ind B; intros; eauto.
  - Case "Arr".
    dependent destruction Aas.
    pose proof (isosub_sound _ _ Isub) as Isub'.
    destruct Isub'.
    eapply Aas_Arr.
    eapply sub_transitivity; eauto.
  - Case "Split".
    dependent destruction Aas.
    + econstructor.
      eapply isosub_to_sub2 in Isub.
      eapply sub_transitivity; eauto.
    + dependent destruction H; eauto.
    + dependent destruction H; eauto.
Qed.

Lemma appsub_iso1 :
  forall A B C H,
    appsub (Some A) B C ->
    isosub H A ->
    exists D, appsub (Some H) B D /\ isosub D C.
Proof.
  introv As Isub.
  pose proof (isosub_to_sub1 _ _ Isub).
  exists C. split; eauto.
  dependent induction As.
  - eapply As_Arr; eauto.
    eapply sub_transitivity; eauto.
  - eapply As_And_L; eauto.
    intros Contra. eapply auxas_iso1 in Contra; eauto.
  - eapply As_And_R; eauto.
    intros Contra. eapply auxas_iso1 in Contra; eauto.
  - eapply As_And_P; eauto.
Qed.

(** ** Functions *)

Lemma auxas_iso2 :
  forall A B H,
    auxas (Some A) B ->
    isosub B H ->
    auxas (Some A) H.
Proof.
  introv As Isub. gen A H.
  proper_ind B; intros; eauto.
  - Case "Arr".
    dependent destruction Isub. eauto.
  - Case "Split".
    dependent destruction H.
    + SCase "And".
      dependent destruction Isub.
      * SSCase "Refl".
        assumption.
      * SSCase "Split".
        (* H have two cases: arrow and intersection *)
        dependent destruction H.
        ** SSSCase "And".
           dependent destruction As.
           *** pose proof (IHPr1 _ As _ Isub1). eauto.
           *** pose proof (IHPr2 _ As _ Isub2). eauto.
        ** SSSCase "Arr".
           eapply Aas_Arr; eauto.
           dependent destruction As.
           *** pose proof (IHPr1 _ As _ Isub1).
               dependent destruction H0; eauto.
           *** pose proof (IHPr2 _ As _ Isub2).
               dependent destruction H0; eauto.
    + SCase "Arr".
      dependent destruction Isub; eauto.
Qed.

Lemma appsub_iso2 :
  forall A B C H,
    appsub (Some A) B C ->
    isosub H B ->
    (exists D, appsub (Some A) H D /\ isosub D C).
Proof.
  introv As Isub. gen A C H.
  proper_ind B; intros; eauto.
  - Case "Arrow".
    dependent destruction Isub; eauto.
  - Case "Split".
    dependent destruction Isub; eauto.
    subst_splitable.
    eapply appsub_split_inversion in H0; eauto.
    destruct H0.
    + SCase "L".
      destruct H.
      pose proof (IHPr1 _ _ H _ Isub1).
      destruct H1. destruct H1.
      exists x. split; eauto. eapply As_And_L; eauto.
      intros Hcontra. eapply auxas_iso2 in Hcontra; eauto.
    + destruct H.
      * SCase "R".
        destruct H.
        pose proof (IHPr2 _ _ H _ Isub2).
        destruct H1. destruct H1.
        exists x. split; eauto. eapply As_And_R; eauto.
        intros Hcontra. eapply auxas_iso2 in Hcontra; eauto.
      * SCase "P".
        destruct H. destruct H. destruct H. destruct H0.
        pose proof (IHPr1 _ _ H _ Isub1).
        pose proof (IHPr2 _ _ H0 _ Isub2).
        destruct H2. destruct H2. destruct H3. destruct H3.
        exists (And x1 x2). split.
        ** eapply As_And_P; eauto.
        ** assert (isosub (And x1 x2) (And x x0)) by eauto.
           eapply isosub_transitivity; eauto.
Qed.

(** ** Generalization *)

Lemma appsub_iso :
  forall A B C H1 H2,
    appsub (Some A) B C ->
    isosub H1 A ->
    isosub H2 B ->
    (exists D, appsub (Some H1) H2 D /\ isosub D C).
Proof.
  introv As Isub1 Isub2.
  pose proof (appsub_iso1 A B C H1 As Isub1) as Iso1.
  destruct Iso1. destruct H.
  pose proof (appsub_iso2 _ _ _ _ H Isub2).
  destruct_conjs. eexists. split; eauto.
  eapply isosub_transitivity; eauto.
Qed.


(** ** Reduction and Values *)

Require Export ARS Coq.Program.Equality.
Require Import core fintype.
Import ScopedNotations.
From Chapter9 Require Export stlc.
Set Implicit Arguments.
Unset Strict Implicit.

Ltac inv H := dependent destruction H.
Hint Constructors star.

(** *** Single-step reduction *)
Inductive step {n} : tm n -> tm n -> Prop :=
| step_beta A b t : step (app (lam A b) t) (b[t..])
| step_abs A b1 b2 : @step (S n) b1 b2 -> step (lam A b1) (lam A b2)
| step_appL s1 s2 t : step s1 s2 -> step (app s1 t) (app s2 t)
| step_appR s t1 t2 : step t1 t2 -> step (app s t1) (app s t2).

Hint Constructors step.

Lemma step_beta' n A b (t t': tm n):
  t' = b[t..] -> step (app (lam A b) t) t'.
Proof. intros ->. now constructor. Qed.

(** *** Multi-step reduction *)

Lemma mstep_lam n A (s t : tm (S n)) :
  star step s t -> star step (lam A s) (lam A t).
Proof. induction 1; eauto. Qed.

Lemma mstep_app n (s1 s2 : tm n) (t1 t2 : tm n) :
  star step s1 s2 -> star step t1 t2 -> star step (app s1 t1) (app s2 t2).
Proof with eauto.
  intros ms. induction 1. induction ms... auto...
Qed.

(** *** Substitutivity *)

(* Ltac fsimpl2 := *)
(*   repeat match goal with *)
(*          | [|- context[id >> ?f]] => change (id >> f) with f (* AsimplCompIdL *); idtac "id comp" *)
(*          | [|- context[?f >> id]] => change (f >> id) with f (* AsimplCompIdR *); idtac "comp id" *)
(*          | [|- context [id ?s]] => change (id s) with s; idtac "ideval" *)
(*          | [|- context[(?f >> ?g) >> ?h]] => change ((f >> g) >> h) with (f >> (g >> h)) (* AsimplComp *); idtac "funcomp assoc" *)
(*          (* | [|- zero_p >> scons_p ?f ?g] => rewrite scons_p_head *) *)
(*          | [|- context[(?s .: ?sigma) var_zero]] => change ((s.:sigma) var_zero) with s; idtac "scons head" *)
(*          | [|- context[(?s .: ?sigma) (shift ?m)]] => change ((s.:sigma) (shift m)) with (sigma m); idtac "scons tail" *)
(*          | [|- context[idren >> ?f]] => change (idren >> f) with f; idtac "idren comp" *)
(*          | [|- context[?f >> idren]] => change (f >> idren) with f; idtac "comp idren" *)
(*          | [|- context[?f >> (?x .: ?g)]] => change (f >> (x .: g)) with g (* f should evaluate to shift *); idtac "shift scons" *)
(*          | [|- context[?x2 .: (funcomp ?f shift)]] => change (scons x2 (funcomp f shift)) with (scons (f var_zero) (funcomp f shift)); setoid_rewrite (@scons_eta' _ _ f); eta_reduce; idtac "scons eta 1" *)
(*          | [|- context[?f var_zero .: ?g]] => change (scons (f var_zero) g) with (scons (f var_zero) (funcomp f shift)); setoid_rewrite scons_eta'; eta_reduce; idtac "scons eta 2" *)
(*          |[|- _ =  ?h (?f ?s)] => change (h (f s)) with ((f >> h) s); idtac "funcomp 1" *)
(*          |[|-  ?h (?f ?s) = _] => change (h (f s)) with ((f >> h) s); idtac "funcomp 2" *)
(*          | [|- context[funcomp _ (scons _ _)]] => setoid_rewrite scons_comp'; eta_reduce; idtac "scons comp" *)
(*          | [|- context[funcomp _ (scons_p _ _ _)]] => setoid_rewrite scons_p_comp'; eta_reduce; idtac "scons_p comp" *)
(*          | [|- context[scons (@var_zero ?n) shift]] => setoid_rewrite scons_eta_id'; eta_reduce; idtac "eta_id" *)
(*          (* | _ => progress autorewrite with FunctorInstances *) *)
(*          | [|- context[funcomp (zero_p _) (scons_p _ _ _)]] => setoid_rewrite scons_p_head'; idtac "head" *)
(*          | [|- context[funcomp (shift_p _) (scons_p _ _ _)]] => setoid_rewrite scons_p_tail'; idtac "tail" *)
(*          end. *)

(* Ltac asimpl2' := repeat (first *)
(*                  [ progress setoid_rewrite substSubst_tm; idtac "substSubst" *)
(*                  | progress setoid_rewrite renSubst_tm; idtac "renSubst" *)
(*                  | progress setoid_rewrite substRen_tm; idtac "substRen" *)
(*                  | progress setoid_rewrite renRen_tm; idtac "renRent" *)
(*                  | progress setoid_rewrite varLRen'_tm; idtac "varLRen" *)
(*                  | progress setoid_rewrite varL'_tm; idtac "varL" *)
(*                  | progress setoid_rewrite rinstId'_tm; idtac "rinstId" *)
(*                  | progress setoid_rewrite instId'_tm; idtac "instId" *)
(*                  | progress *)
(*                     unfold up_list_tm_tm, up_tm_tm, upRen_list_tm_tm, *)
(*                      upRen_tm_tm, up_ren; idtac "unfold" *)
(*                  | progress cbn[subst_tm ren_tm]; idtac "cbn" *)
(*                  | idtac "presimpl"; progress fsimpl2; idtac "fsimpl" ]). *)

(* Ltac asimpl2 := check_no_evars; repeat try unfold_funcomp; *)
(*                 repeat *)
(*                  unfold VarInstance_tm, Var, ids, Ren_tm, Ren1, ren1, *)
(*                   Up_tm_tm, Up_tm, up_tm, Subst_tm, Subst1, subst1 in *; *)
(*                 asimpl2'; minimize. *)

Lemma step_inst {m n} (f : fin m -> tm n) (s t : tm m) :
  step s t -> step (subst_tm f s) (subst_tm f t).
Proof.
   intros st. revert n f.  induction st as  [m b s t |m A b1 b2 _ ih|m s1 s2 t _ ih|m s t1 t2 _ ih]; intros n f; cbn.
   - apply step_beta'.
     (* TODO declare those as opaue. otherwise setoid rewrite does spurious rewrites -> infinite loop
      * any var_tm can be expanded to (ren_tm id var_tm) and then varLRen triggers *)
     Hint Opaque ren_tm : rewrite.
     Hint Opaque subst_tm : rewrite.
     now asimpl.
     (* check_no_evars; repeat try unfold_funcomp; *)
     (*   repeat *)
     (*     unfold VarInstance_tm, Var, ids, Ren_tm, Ren1, ren1, *)
     (*   Up_tm_tm, Up_tm, up_tm, Subst_tm, Subst1, subst1 in *. *)
     (* (first *)
     (*             [ progress setoid_rewrite substSubst_tm; idtac "substSubst" *)
     (*             | progress setoid_rewrite renSubst_tm; idtac "renSubst" *)
     (*             | progress setoid_rewrite substRen_tm; idtac "substRen" *)
     (*             | progress setoid_rewrite renRen_tm; idtac "renRent" *)
     (*             | progress setoid_rewrite varLRen'_tm; idtac "varLRen" *)
     (*             | progress setoid_rewrite varL'_tm; idtac "varL" *)
     (*             | progress setoid_rewrite rinstId'_tm; idtac "rinstId" *)
     (*             | progress setoid_rewrite instId'_tm; idtac "instId" *)
     (*             | progress *)
     (*                unfold up_list_tm_tm, up_tm_tm, upRen_list_tm_tm, *)
     (*                 upRen_tm_tm, up_ren; idtac "unfold" *)
     (*             | progress cbn[subst_tm ren_tm]; idtac "cbn" *)
     (*             | idtac "presimpl"; progress fsimpl2; idtac "fsimpl" ]). *)
     (* Unset Printing Notations. *)
     (* unfold up_tm_tm. *)
     (* (* rewrite_strat innermost varLRen'_tm. *) *)
     (* (* rewrite_strat innermost varLRen'_tm. *) *)
     (* (* setoid_rewrite -> varLRen'_tm. *) *)
     (* fsimpl2. *)
  - apply step_abs. eapply ih.
  - apply step_appL, ih.
  - apply step_appR, ih.
Qed.

Lemma mstep_inst m n (f : fin m -> tm n) (s t : tm m) :
  star step s t -> star step (s[f]) (t[f]).
Proof. induction 1; eauto using step_inst. Qed.

Lemma mstep_subst m n (f g : fin m -> tm n) (s t : tm m) :
  star step s t -> (forall i, star step (f i) (g i)) ->
  star step (s[f]) (t[g]).
Proof with eauto.
  intros st fg.
  apply star_trans with (y := t[f]); [eauto using mstep_inst|].
  clear s st. revert n f g fg.
  induction t; eauto using mstep_app; intros; simpl.
  - cbn. apply mstep_lam. apply IHt. intros [i|]; [|constructor].
    + asimpl.  cbn. unfold funcomp. substify. now apply mstep_inst.
Qed.

Lemma mstep_beta n (s1 s2 : tm (S n)) (t1 t2 : tm n) :
  star step s1 s2 -> star step t1 t2 ->
  star step (s1 [t1..]) (s2 [t2..]).
Proof.
  intros st1 st2. apply mstep_subst; [assumption|].
  now intros [|].
Qed.

Lemma step_naturality m n (M: tm m) (rho: fin m -> fin n) M' :
  step (M ⟨rho⟩) M' -> exists M'', step M M'' /\ M' = (M'' ⟨rho⟩).
Proof.
  intros H.
  dependent induction H.
  - destruct M; try inversion x. subst.
    destruct M1; try inversion H0. subst.
    exists (M1[M2..]). split. eauto.
    asimpl. reflexivity.
  - destruct M; inversion x. subst.
    edestruct (IHstep _ M) as (?&?&?); [reflexivity|].
    subst. eexists; eauto.
  - destruct M; inversion x. subst.
    edestruct (IHstep _ M1) as (?&?&?); [reflexivity|].
    subst. eexists; eauto.
  - destruct M; inversion x. subst.
    edestruct (IHstep _ M2) as (?&?&?); [reflexivity|].
    subst. eexists; eauto.
Qed.

Definition value {m} (e : tm m) : Prop :=
  match e with
  | lam  _ _ => True
  | _ => False
  end.

Lemma value_anti {m n} (xi : fin m -> fin n) (s : tm m) :
  value (s⟨xi⟩) -> value s.
Proof.
  destruct s; eauto.
Qed.


(*

  Copyright 2014 Cornell University

  This file is part of VPrl (the Verified Nuprl project).

  VPrl is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  VPrl is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.

  Website: http://nuprl.org/html/verification/
  Authors: Abhishek Anand & Vincent Rahli

*)

Require Export bin_rels.
Require Export alphaeq.

(** printing #  $\times$ #×# *)
(** printing <=>  $\Leftrightarrow$ #<=># *)
(** printing [+]  $+$ #[+]# *)
(** printing <  $<$ #<# *)
(** printing $  $\times$ #×# *)
(** printing &  $\times$ #×# *)
(** printing {[  $[$ #[# *)
(** printing ]}  $]$ #]# *)

Notation "tls {[ m ]}" := (selectbt tls m)
  (at level 99).

(** When we define the type system in the next chapter, we will
    want it to respect many computational relations.
    In Agda, Coq and Nuprl, if [t] reduces to [t'],
    and [t] is in some type [T], then [t]
    and [t'] are equal in [T].
    In addition, it is useful to have our types respect a
    %\emph{congruence}% that contains the computation relation.  For
    example, Coq has a notion of definitional equality which is a
    congruence.  In Nuprl, we have a computation equivalence
    $\sim$ %\cite{Howe:1989}%, which is a coinductively
    defined congruence that permits more powerful equational reasoning.
    For example, all diverging programs are equivalent under
    $\sim$.  The same holds for all programs that
    generate an infinite stream of zeroes.

    Following him, we will first define his computational approximation
    ([approx]) and prove that it is a congruence.
    The desired equivalence([cequiv]) is defined as a conjuction of
    [approx] with its inverse. In the next chapter,
    our definition of Nuprl's type system
    will respect [cequiv] by definition.
    We often denote [cequiv] by $\sim$.

    We will also prove many domain theoretic properties about [approx] in the
    next section. These properties will be useful in defining partial types.
 *)

(** We begin by describing some key definitions involved in the defining
    of [approx]. Firstly, [olift] lifts a binary relation that is
    meaningful only on programs to
    to one on well-formed([nt_wf]) terms that
    may have free variables. Recall
    that a program is a well-formed term that is also closed.
    the [wf_sub] predicate on [Substitution] asserts that the range of
    the substitution consists of well-formed terms.
    (One could have used the [CTerm] type to make
    this definition more compact.)
    Intuitively,  [(olift R) s t] asserts
    that for all substitutions that turn [s] and [t]
    to closed terms [s'] and [t'], [R s' t'] holds.
*)

Definition NTrel {o} := @NTerm o -> @NTerm o -> [univ].

Definition olift {p} (R : NTrel) (x y : NTerm) : [univ] :=
  nt_wf x # nt_wf y
  # forall sub: @Substitution p,
      wf_sub sub
      -> isprogram (lsubst x sub)
      -> isprogram (lsubst y sub)
      -> R (lsubst x sub) (lsubst y sub).

(**

  We show later that oliftp and olift are equivalent if R respects
  alpha equivalence.

*)
Definition oliftp {p} (R : NTrel) (x y :NTerm) : [univ] :=
  nt_wf x # nt_wf y
  # forall sub: @CSub p,
      cover_vars x sub
      -> cover_vars y sub
      -> R (csubst x sub) (csubst y sub).

(** % \noindent \\* % [blift] and [lblift]
    lift a binary relation on [NTerm]s to one on [BTerm]s and one on
    lists of [BTerm] respectively.
   *)

Definition blift {p} (R: NTrel) (bt1 bt2: BTerm): [univ] :=
{lv: (list NVar) &  {nt1,nt2 : @NTerm p $ R nt1 nt2
  # alpha_eq_bterm bt1 (bterm lv nt1) # alpha_eq_bterm bt2 (bterm lv nt2) }}.

Definition lblift {p} (R: NTrel)
                      (tls trs: list (@BTerm p)): [univ] :=
length tls = length trs
# forall n : nat,  n < length tls -> blift R (tls{[n]}) (trs{[n]}).

(** %\fxnote{coqdoc notation messed up above : ]\}}% *)
(* begin hide *)
Definition blift_old {p} (R : NTerm -> NTerm -> Type) (a b : BTerm) : Type :=
  num_bvars a = num_bvars b
  # forall lnt : list (@NTerm p),
       (**approx_refl proof required the next 2 lines*)
       length lnt = num_bvars a
       -> (forall nt : NTerm, LIn nt lnt -> isprogram nt)
       -> R (apply_bterm a lnt) (apply_bterm b lnt).

Definition is_rel_on_progs {p} (R: bin_rel (@NTerm p)) : Type :=
  forall t1 t2, R t1 t2 -> isprogram t1 # isprogram t2.

Theorem le_blift {p} :
  forall (R1 R2 : bin_rel (@NTerm p)),
    le_bin_rel R1 R2 -> le_bin_rel (blift  R1) (blift R2).
Proof.
  unfold le_bin_rel.
  intros R1 R2 Hle a b Hrel.
  allunfold @blift. sp.
  exists lv nt1 nt2.
  split; eauto.
Defined.

Theorem le_olift {p} :
  forall (R1 R2 : bin_rel (@NTerm p)),
    le_bin_rel R1 R2 -> le_bin_rel (olift  R1) (olift R2).
Proof.
  unfold le_bin_rel, olift. sp.
Defined.

Hint Resolve @le_olift : slow.

Theorem le_blift2 {p} : forall (R1 R2 : bin_rel (@NTerm p)),
  (le_bin_rel R1 R2) -> forall a b, (blift  R1  a b) -> (blift R2  a b).
Proof. intros R1 R2 n H.
  fold (@le_bin_rel (BTerm ) (blift R1 ) (blift R2 )).
 apply le_blift. auto.
Defined.

Hint Resolve le_blift2 : slow.

Theorem le_lblift {p} : forall (R1 R2 : bin_rel (@NTerm p)),
  (le_bin_rel R1 R2) -> le_bin_rel (lblift  R1) (lblift  R2).
Proof.
  unfold lblift; sp.
  unfold le_bin_rel; sp.
  generalize (X0 n); sp.
  apply @le_blift2 with (R1 := R1); sp.
Defined.

Theorem le_lblift2 {p} : forall (R1 R2 : bin_rel (@NTerm p)),
  (le_bin_rel R1 R2) -> forall a b, (lblift R1 a b) -> (lblift  R2 a b).
Proof. intros R1 R2 H.
  fold (@le_bin_rel (list BTerm) (lblift R1 ) (lblift R2 )).
 apply le_lblift. auto.
Defined.

(*
Inductive toProp (T: Type): Prop :=
trunc : T -> toProp T.
*)

Theorem eq_blift_olift {p} :
  forall (R1 R2 : bin_rel (@NTerm p)),
    eq_bin_rel R1 R2 -> eq_bin_rel (olift  R1) (olift R2).
Proof.
  unfold eq_bin_rel. split; repnd; eauto with slow.
Qed.

Lemma blift_refl {p} :
  forall (R : bin_rel (@NTerm p)),
    refl_rel R
    -> refl_rel (blift R).
Proof.
  unfold refl_rel, blift; sp.
  destruct x as [lv nt].
  exists lv nt nt.
  eauto with slow.
Qed.

(* end hide *)
(** Below, we define some abstractions to denote that
  a relation respects another relation. In particular,
  we are interested in proving that many relations
  respect alpha equaliity *)

Definition respects2_l {T1 T2 : tuniv}
           (Rr : T1 -> T1 -> [univ])
           (R  : T1 -> T2 -> [univ]) :=
  forall a b a', Rr a a' -> R a b -> R a' b.

Definition respects2_r {T1 T2 : tuniv}
           (Rr : T2 -> T2 -> [univ])
           (R  : T1 -> T2 -> [univ]) :=
  forall a b b', Rr b b' -> R a b -> R a b'.

Definition respects2 {T : tuniv}
           (Rr : T -> T -> [univ])
           (R : T -> T -> [univ]):=
  (respects2_l Rr R) # (respects2_r Rr R).

Notation respects_alpha := (respects2 alpha_eq).

Lemma olift_iff_oliftp {p} :
  forall R a b,
    respects_alpha R
    -> (@olift p R a b <=> oliftp R a b).
Proof.
  introv resp; unfold olift, oliftp; split; intro o; repnd; dands; auto.

  - introv cva cvb.
    generalize (o (csub2sub sub)); intro k.
    repeat (autodimp k hyp).

    + apply isprogram_lsubst; auto.

      * introv i; apply in_csub2sub in i; auto.

      * introv i.
        rw @cover_vars_eq in cva.
        rw subvars_prop in cva.
        apply cva in i.
        rw @dom_csub_eq; auto.

    + apply isprogram_lsubst; auto.

      * introv i; apply in_csub2sub in i; auto.

      * introv i.
        rw @cover_vars_eq in cvb.
        rw subvars_prop in cvb.
        apply cvb in i.
        rw @dom_csub_eq; auto.

  - introv wfsub ispa ispb.
    generalize (lsubst_trim2_alpha1 a b sub ispa ispb); intro k.
    remember (sub_keep_first sub (free_vars a ++ free_vars b)).
    simpl in k; repnd.
    generalize (lsubst_trim2_alpha2 a b sub wfsub ispa ispb); intro ps.
    rw <- Heqs in ps.
    generalize (prog_sub_exists_csub s ps); intro e; exrepnd.
    assert (dom_csub s0 = dom_sub s) as domeq by (rw <- e0; rw @dom_csub_eq; auto).

    assert (cover_vars a s0) as ca.
    rw @cover_vars_eq.
    rw subvars_prop; introv i.
    rw domeq.
    rw Heqs.
    apply lsubst_program_implies in ispa.
    applydup ispa in i.
    applydup @in_dom_sub_exists in i0; exrepnd.
    apply @in_dom_sub with (t := t).
    apply in_sub_keep_first; dands; auto.
    rw in_app_iff; auto.

    assert (cover_vars b s0) as cb.
    rw @cover_vars_eq.
    rw subvars_prop; introv i.
    rw domeq.
    rw Heqs.
    apply lsubst_program_implies in ispb.
    applydup ispb in i.
    applydup @in_dom_sub_exists in i0; exrepnd.
    apply @in_dom_sub with (t := t).
    apply in_sub_keep_first; dands; auto.
    rw in_app_iff; auto.

    generalize (o s0 ca cb); intro r.
    unfold csubst in r.
    rw e0 in r.

    destruct resp as [rl rr].
    applydup @alpha_eq_sym in k0.
    applydup @alpha_eq_sym in k.
    generalize (rl (lsubst a s) (lsubst b sub) (lsubst a sub) k1);
      intro j1; repeat (autodimp j1 hyp).
    generalize (rr (lsubst a s) (lsubst b s) (lsubst b sub) k2);
      intro j2; repeat (autodimp j2 hyp).
Qed.

(* begin hide *)

Notation  respects_alpha_l :=  (@respects2_l NTerm NTerm alpha_eq).
Notation  respects_alpha_r :=  (@respects2_r NTerm NTerm alpha_eq).

Definition respects1 {T : tuniv} (Rr : T -> T -> [univ])
                                 (R : T  -> [univ]):=
     forall a a', Rr a a' -> R a -> R a'.

Definition respects3_l {TL TM TR : tuniv} (Rr : TL -> TL -> [univ])
                                      (R : TL -> TM -> TR -> [univ]):=
     forall a b c a' , Rr a a' -> R a b c -> R a' b c.

Definition respects3_m {TL TM TR : tuniv} (Rr : TM -> TM -> [univ])
                                      (R : TL -> TM -> TR -> [univ]):=
     forall a b c b', Rr b b' -> R a b c -> R a b' c.

Definition respects3_r {TL TM TR : tuniv} (Rr : TR -> TR -> [univ])
                                      (R : TL -> TM -> TR -> [univ]):=
     forall a b c c', Rr c c' -> R a b c -> R a b c'.

Definition respects3 {T : tuniv} (Rr : T -> T -> [univ])
                                 (R : T -> T -> T -> [univ]):=
     (respects3_l Rr R) # (respects3_m Rr R) # (respects3_r Rr R).

Lemma respects2_l_eauto : forall {T: tuniv} Rr (R : T-> T-> [univ]),
  respects2 Rr R -> (respects2_l Rr R).
Proof.
  intros. repnud X.
  auto.
Qed.

Lemma respects2_r_eauto : forall {T: tuniv} Rr (R : T-> T-> [univ]),
  respects2 Rr R -> (respects2_r Rr R).
Proof.
  intros. repnud X.
  auto.
Qed.

Hint Resolve respects2_l_eauto  respects2_r_eauto : respects.

Ltac rwhg  Hal H := let xrr := fresh "XRR" in
match type of Hal with
| ?Rr ?la ?ra =>
  match type of H with
  | ?R la => assert (respects1 Rr R) as xrr by eauto with respects;
      apply (xrr _ _ Hal) in H;clear xrr

  | ?R la _ => assert (respects2_l Rr R) as xrr by eauto with respects;
      apply (xrr _ _ _ Hal) in H;clear xrr
  | ?R _ la => assert (respects2_r Rr R) as xrr by eauto with respects;
      apply (xrr _ _ _ Hal) in H;clear xrr

  | ?R la _ _ => assert (respects3_l Rr R) as xrr by eauto with respects;
      apply (xrr _ _ _ _ Hal) in H;clear xrr
  | ?R _ la _ => assert (respects3_m Rr R) as xrr by eauto with respects;
      apply (xrr _ _ _ _ Hal) in H;clear xrr
  | ?R _ _ la => assert (respects3_r Rr R) as xrr by eauto with respects;
      apply (xrr _ _ _ _ Hal) in H;clear xrr
  end
end.

Lemma sym_alpha_eauto {p} : symm_rel (@alpha_eq p).
Proof.
  introv Hab.
  eauto with slow.
Qed.

Hint Resolve  sym_alpha_eauto: respects.

Ltac rwg  Hal := let xrr := fresh "XRR" in
                let Xsym := fresh "Xsym" in
match type of Hal with
| ?Rr ?la ?ra => assert (symm_rel Rr) as Xsym;
  [eauto with respects;
    idtac ":add symmetry of this relation to the database"; fail|];
  match goal with
  | [ |- ?R la ] => assert (respects1 Rr R) as xrr by (eauto with respects;
       idtac "missing hint:1");
      apply (xrr _ _  (Xsym _ _ Hal));clear xrr

  | [ |- ?R la _ ] => assert (respects2_l Rr R) as xrr by (eauto with respects;
       idtac "missing hint:2_l");
      apply (xrr _ _ _ (Xsym _ _ Hal));clear xrr
  | [ |- ?R _ la ]  => assert (respects2_r Rr R) as xrr by (eauto with respects;
       idtac "missing hint:2_r");
      apply (xrr _ _ _ (Xsym _ _ Hal));clear xrr

  | [ |- ?R la _ _] => assert (respects3_l Rr R) as xrr by eauto with respects;
      apply (xrr _ _ _ _ (Xsym _ _ Hal));clear xrr
  | [ |- ?R _ la _]  => assert (respects3_m Rr R) as xrr by eauto with respects;
      apply (xrr _ _ _ _ (Xsym _ _ Hal));clear xrr
  | [ |- ?R _ _ la ]  => assert (respects3_r Rr R) as xrr by eauto with respects;
      apply (xrr _ _ _ _ (Xsym _ _ Hal));clear xrr

  end; clear Xsym
end.

Lemma respects3_l_eauto : forall {T: tuniv} Rr (R : T-> T -> T -> [univ]),
  respects3 Rr R -> (respects3_l Rr R).
Proof.
  intros. repnud X.
  auto.
Qed.

Lemma respects3_m_eauto : forall {T: tuniv} Rr (R : T->  T -> T-> [univ]),
  respects3 Rr R -> (respects3_m Rr R).
Proof.
  intros. repnud X.
  auto.
Qed.

Lemma respects3_r_eauto : forall {T: tuniv} Rr (R : T-> T -> T -> [univ]),
  respects3 Rr R -> (respects3_r Rr R).
Proof.
  intros. repnud X.
  auto.
Qed.

Hint Resolve respects3_l_eauto respects3_m_eauto respects3_r_eauto : respects.

Ltac symmt Hal :=
  let Xsym := fresh "Xsym" in
  match type of Hal with
    | ?Rr ?la ?ra =>
      assert (symm_rel Rr) as Xsym;
        [ eauto with respects;
          idtac ":add symmetry of this relation to the database";
          fail
        | apply Xsym in Hal;
          clear Xsym
        ]
  end.

Ltac rwgs Hal := (rwg Hal || (symmt Hal; rwg Hal) ).

Theorem olift_relates_only_wf {p} : forall R t1 t2, (@olift p R) t1 t2
  -> nt_wf t1 # nt_wf t2.
Proof. introv H. repnud H. split; auto.
Qed.

Theorem olift_vars_lsubst {p} :
  forall R a b lvi lvo, let sub := @var_ren p lvi lvo in
   (respects_alpha R)
   ->  (olift R) a b
   -> (olift R) (lsubst a sub) (lsubst b sub).
Proof.
  introv Hra Hap.
  applydup @olift_relates_only_wf in Hap.
  pose proof (@wf_sub_vars p lvi lvo) as Hwf.
  repeat(split; [apply lsubst_wf_iff;sp;fail|]).
  introv Hwfs H1ps H2pr.
  repnud Hap.
  pose proof (@allvars_combine p lvi lvo) as Hss.
  pose proof (combine_1var_sub_wspec (var_ren lvi lvo) sub) as Hsub.
  repeat(dest_imp Hsub HH).
  exrepnd.
  pose proof (Hsub0 a) as Hala. alpha_hyps Hala.
  pose proof (Hsub0 b) as Halb. alpha_hyps Halb.
  pose proof (Hap sub3) as XX.
  repeat(dest_imp XX HH).
  rwg Hala.
  rwg Halb.
  trivial.
Qed.

Lemma respects_alpha_olift_l {p} : forall R,
  respects_alpha_l R
  -> respects_alpha_l (@olift p R).
Proof.
  introv Hra.  introv Hal Hap.
  repnud Hap.
  alpha_hyps Hal.
  unfold olift. dands; spcf.
  introv Hwf Hla' Hlb.
  dimp (Hap sub); spc; eauto 3 with slow.
  apply @lsubst_alpha_congr2 with (sub:=sub)in Hal.
  apply alphaeq_preserves_program in Hal.
  destruct Hal; auto.
Qed.

Lemma respects_alpha_olift_r {p} : forall R,
  respects_alpha_r R
  -> respects_alpha_r (@olift p R).
Proof.
  introv Hra.  introv Hal Hap.
  repnud Hap.
  alpha_hyps Hal.
  unfold olift. dands; spcf.
  introv Hwf Hla' Hlb.
  dimp (Hap sub); spc; eauto 3 with slow.
  apply @lsubst_alpha_congr2 with (sub:=sub)in Hal.
  apply alphaeq_preserves_program in Hal.
  destruct Hal; auto.
Qed.

(* end hide *)
Lemma respects_alpha_olift {p}: forall R,
  respects2 alpha_eq R
  -> respects2 alpha_eq (@olift p R).
Proof.
  introv Hr. repnud Hr.
  split.
  - apply respects_alpha_olift_l;  trivial.
  - apply respects_alpha_olift_r; trivial.
Qed.
(* begin hide *)

Hint Resolve respects_alpha_olift : respects.

Lemma blift_oliftd {p} : forall R bt1 bt2 lva,
  (respects_alpha R)
  -> blift (olift R) bt1 bt2
  -> {lvn : (list NVar) & {nt1',nt2' : @NTerm p $ (olift R) nt1' nt2'
          # alpha_eq_bterm bt1 (bterm lvn nt1')
          # alpha_eq_bterm bt2 (bterm lvn nt2')
          # no_repeats lvn
          (* # disjoint lvn (all_vars (get_nt bt1) ++ all_vars (get_nt bt2)) *)
          # disjoint (lvn ++ (bound_vars nt1') ++ (bound_vars nt2')) lva   } }.
Proof.
  introv Hra Hab.
  repnud Hab. exrepnd.
  pose proof (alpha_bterm_pair_change _ _ _ _ _ lva Hab2 Hab0) as Hp.
  exrepnd.
  exists lvn.
  rwhg Hp2 Hab1.
  rwhg Hp3 Hab1.
  exists (lsubst nt1n (var_ren lv lvn)).
  exists (lsubst nt2n (var_ren lv lvn)).
  spc;[| disjoint_reasoningv;spcls;
        apply disjoint_bound_vars_lsubst; spcls;disjoint_reasoningv;fail].
  apply olift_vars_lsubst;spc.
Qed.

Lemma blift_selen_triv {p} : forall R lv a b,
  (respects_alpha R)
  -> blift (olift R )(bterm lv a) (@bterm p lv b)
  -> (olift R) a b.
Proof.
  introv Hra Has.
  apply (blift_oliftd R _ _ lv) in Has; auto.
  exrepnd.
  pose proof (change_bvars_alpha_wspec lv a) as Hfa.
  exrepnd. rename ntcv into a'.
  rwg Hfa0.
  apply @alpha_eq_bterm_congr with (lv:=lv) in Hfa0.
  assert (alpha_eq_bterm (bterm lv a') (bterm lvn nt1'))
      as Xa by eauto with slow.

  pose proof (change_bvars_alpha_wspec lv b) as Hfb.
  exrepnd. rename ntcv into b'.
  rwg Hfb0.
  apply @alpha_eq_bterm_congr with (lv:=lv) in Hfb0.
  assert (alpha_eq_bterm (bterm lv b') (bterm lvn nt2'))
      as Xb by eauto with slow.
  clear dependent a.
  clear dependent b.
  invertsna Xa Hb.
  invertsna Xb Ha.
  apply lsubst_alpha_congr2 with (sub:=var_ren lv3 lv) in Ha3.
  rw @lsubst_nest_vars_same in Ha3;spc; disjoint_reasoningv;[].
  rw @lsubst_nest_vars_same in Ha3;spc; disjoint_reasoningv;[].
  apply lsubst_alpha_congr2 with (sub:=var_ren lv0 lv) in Hb3.
  rw @lsubst_nest_vars_same in Hb3;spc; disjoint_reasoningv;[].
  rw @lsubst_nest_vars_same in Hb3;spc; disjoint_reasoningv;[].
  Hint Resolve lsubst_trivial_alpha : slow.
  assert (alpha_eq b' (lsubst nt2' (var_ren lvn lv))) as Xa by eauto with slow.
  assert (alpha_eq a' (lsubst nt1' (var_ren lvn lv))) as Xb by eauto with slow.
  clear Ha3 Hb3.
  apply olift_vars_lsubst with (lvi:=lvn) (lvo:=lv) in Has1;spc;[].
  rwg Xa.
  rwg Xb.
  auto.
Qed.

Lemma le_blift_olift {p} :
  forall R1 R2 : bin_rel (@NTerm p),
  le_bin_rel R1 R2 -> le_bin_rel (blift (olift R1))
      (blift (olift R2)).
Proof.
  introv Ha.
  apply le_blift.
  apply le_olift; auto.
Qed.

Lemma blift_alpha_fun_r {p} :
  forall R nt1 nt2 nt2',
  @blift p R nt1 nt2
  -> alpha_eq_bterm nt2 nt2'
  -> blift R nt1 nt2'.
Proof.
  introv Has Hal.
  repnud Has .
  exrepnd.
  unfold blift.
  exists lv nt0 nt3.
  dands; eauto with slow.
Qed.

Lemma blift_alpha_fun_l {p} :
  forall R nt1 nt1' nt2,
  @blift p R nt1 nt2
  -> alpha_eq_bterm nt1 nt1'
  -> blift R nt1' nt2.
Proof.
  introv Has Hal.
  repnud Has .
  exrepnd.
  unfold blift.
  exists lv nt0 nt3.
  dands; eauto with slow.
Qed.

(* end hide *)
(** %\noindent% Because of the way alpha equality
    is baked into the definition of [blift],
    for any binary relation [R] on [NTerm],
    [blift R] respects alpha equality of bound terms.
*)

Lemma respects_blift_alphabt {p} : forall (R : bin_rel (@NTerm p)),
  respects2 alpha_eq_bterm (blift R).
Proof.
  intros Hr.
  split; introv Hyp;
  eauto using blift_alpha_fun_l, blift_alpha_fun_r.
Qed.

(** %\noindent% We will use the following lemmas later
    in this document.

*)
Lemma blift_numbvars {p} : forall R bt1 bt2,
  @blift p R bt1 bt2
  -> num_bvars bt1= num_bvars bt2.
Proof.
  introv Hr.
  repnud Hr.
  exrepnd.
  inverts Hr0.
  inverts Hr2.
  unfold num_bvars. simpl. spc.
Qed.
(* begin hide *)

Ltac blift_nums :=
repeat match goal with
[H : blift _ (bterm _ _) (bterm _ _) |- _ ] =>
  let Hnum := fresh H "num" in
  pose proof (blift_numbvars _ _ _ H) as Hnum; hide_hyp H
end; show_hyps.

Ltac remove_relbt_samevar :=
repeat match goal with
[H : blift _ (bterm ?lv _) (bterm ?lv _) |- _ ] =>
  let Hnorel := fresh H "norel" in
  pose proof H as Hnorel;
  apply blift_selen_triv in Hnorel; eauto with respects; hide_hyp H;
  try(idtac; [| idtac "hint missing"])
end; show_hyps.

Lemma symmrel_alpha_eq_bterm_eauto {p} : symm_rel (@alpha_eq_bterm p).
Proof.
  introv Hb.
  eauto with slow.
Qed.

Hint Resolve symmrel_alpha_eq_bterm_eauto : respects.

Lemma respect_eauto_albt {p} : respects1 alpha_eq_bterm (@bt_wf p).
Proof.
  introv. introns XX.
  apply (alphaeqbt_preserves_wf _ _ XX) in XX0.
  auto.
Qed.

Lemma symm_rel_eauto_99 {p} : symm_rel (@alpha_eq_bterm p).
Proof.
  introv ; eauto with slow.
Qed.

Hint Resolve respect_eauto_albt symm_rel_eauto_99 : respects.

Lemma alphabt_blift {p} : forall R,
(le_bin_rel ( fun x y => @alpha_eq p x y # nt_wf x # nt_wf y) R)
-> (le_bin_rel ( fun x y => alpha_eq_bterm x y # bt_wf x # bt_wf y) (blift R)).
Proof.
  introv Hle Hal. allsimpl.
  unfolds_base. repnd.
  applydup @alpha_eq_bterm_unify in Hal0.
  exrepnd.
  exists lv nta ntb.
  dands; auto. apply Hle.
  assert (alpha_eq_bterm (bterm lv nta) (bterm lv ntb)) as Hnal by
    eauto using alpha_eq_bterm_trans, alpha_eq_bterm_sym.
  rwhg Hal3 Hal.
  rwhg Hal2 Hal1.
  invertsn Hal.
  invertsn Hal1.
  dands; auto.
  apply alpha_eq_bterm_triv in Hnal.
  auto.
Qed.

(*
Lemma lblift_refl :
  forall R,
    rel_rel NTerm R
    -> rel_rel (list BTerm) (lblift R).
Proof.
  sp; unfold rel_rel; sp.
  constructor; sp.
  apply blift_refl in X.
  unfold rel_rel in X; sp.
Qed.

Lemma blift_refl_p :
  forall R : NTerm -> NTerm -> Type,
    (forall t, isprogram t -> R t t)
    -> forall bt, isprogram_bt bt -> blift R bt bt.
Proof.
  sp; constructor; sp.
  apply X.
  unfold apply_bterm; destruct bt; allsimpl.
  inversion X0.
  inversion X2; subst.
  apply isprogram_lsubst; sp.
  allapply in_combine; sp.
  inversion H0.
  rw <- null_iff_nil in H2.
  rw null_remove_nvars in H2.
  apply_in_hyp p.
  apply implies_in_combine; sp.
Qed.

Lemma lblift_refl_p :
  forall R : NTerm -> NTerm -> Type,
    (forall t, isprogram t -> R t t)
    -> forall l, (forall bt, LIn bt l -> isprogram_bt bt) -> lblift R l l.
Proof.
  sp; constructor; sp.
  apply blift_refl_p; sp.
  apply X0.
  apply selectbt_in; sp.
Qed.
*)