@@ -713,3 +713,64 @@ Definition fold_term {Acc} (f : Acc -> term -> Acc) (acc : Acc) (t : term) : Acc
713713(** Monadic variant of [fold_term]. *)
714714Definition fold_termM {M} `{Monad M} {Acc} (f : Acc -> term -> M Acc) (acc : Acc) (t : term) : M Acc :=
715715 @fold_term_with_bindersM M _ Acc unit tt (fun _ _ => ret tt) (fun _ => f) acc t.
716+
717+
718+ (** * Traversal functions with a context *)
719+ Definition rebuild_case_predicate_ctx_with_context (Σ : global_env) ind (p : predicate term) : context :=
720+ match lookup_ind_decl Σ (inductive_mind ind) (inductive_ind ind) with
721+ | TypeError _ => []
722+ | Checked (mib, oib) => case_predicate_context ind mib oib p
723+ end .
724+
725+ Definition map_context_with_context (f : context -> term -> term) (c : context) Γ : context :=
726+ fold_left (fun acc decl => map_decl (f (Γ ,,, acc)) decl :: acc) (List.rev c) [].
727+
728+ Definition map_predicate_with_context (Σ : global_env) (f : context -> term -> term) Γ ind (p : predicate term) :=
729+ let pctx := rebuild_case_predicate_ctx_with_context Σ ind p in
730+ let Γparams := map_context_with_context f pctx Γ in
731+ {| pparams := map (f Γ) p.(pparams);
732+ puinst := p.(puinst);
733+ pcontext := p.(pcontext);
734+ preturn := f (Γparams ++ Γ) (preturn p) |}.
735+
736+ Definition rebuild_case_branch_ctx_with_context Σ ind i p br :=
737+ match lookup_constructor_decl Σ (inductive_mind ind) (inductive_ind ind) i with
738+ | TypeError _ => []
739+ | Checked (mib, cdecl) => case_branch_context ind mib cdecl p br
740+ end .
741+
742+ Definition map_case_branch_with_context Σ ind i (f : context -> term -> term) Γ p br :=
743+ let ctx := rebuild_case_branch_ctx_with_context Σ ind i p br in
744+ map_branch (f (Γ ,,, ctx)) br.
745+
746+ Definition map_term_with_context Σ (f : context -> term -> term) Γ (t : term) : term :=
747+ match t with
748+ | tRel i => t
749+ | tEvar ev args => tEvar ev (List.map (f Γ) args)
750+ | tLambda na T M =>
751+ let T' := f Γ T in
752+ tLambda na T' (f (Γ,, vass na T') M)
753+ | tApp u v => tApp (f Γ u) (List.map (f Γ) v)
754+ | tProd na A B =>
755+ let A' := f Γ A in
756+ tProd na A' (f (Γ ,, vass na A') B)
757+ | tCast c kind t => tCast (f Γ c) kind (f Γ t)
758+ | tLetIn na b t c =>
759+ let b' := f Γ b in
760+ let t' := f Γ t in
761+ tLetIn na b' t' (f (Γ ,, vdef na b' t') c)
762+ | tCase ci p c brs =>
763+ let p' := map_predicate_with_context Σ f Γ ci.(ci_ind) p in
764+ let brs' := mapi (fun i x => map_case_branch_with_context Σ ci.(ci_ind) i f Γ p' x) brs in
765+ tCase ci p' (f Γ c) brs'
766+ | tProj p c => tProj p (f Γ c)
767+ | tFix mfix idx =>
768+ let Γ' := fix_decls mfix ++ Γ in
769+ let mfix' := List.map (map_def (f Γ) (f Γ')) mfix in
770+ tFix mfix' idx
771+ | tCoFix mfix k =>
772+ let Γ' := fix_decls mfix ++ Γ in
773+ let mfix' := List.map (map_def (f Γ) (f Γ')) mfix in
774+ tCoFix mfix' k
775+ | x => x
776+ end .
0 commit comments