3 use rustc::hir::def::DefKind;
4 use rustc::hir::def_id::DefId;
5 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
6 use rustc::hir::map::definitions::DefPathData;
7 use rustc::hir::{self, ImplPolarity};
16 ProgramClauseCategory,
20 use rustc::ty::query::Providers;
21 use rustc::ty::{self, List, TyCtxt};
22 use rustc::ty::subst::{Subst, InternalSubsts};
27 crate fn provide(p: &mut Providers<'_>) {
30 program_clauses_for_env: environment::program_clauses_for_env,
31 environment: environment::environment,
36 crate trait Lower<T> {
37 /// Lower a rustc construct (e.g., `ty::TraitPredicate`) to a chalk-like type.
41 impl<T, U> Lower<Vec<U>> for Vec<T>
45 fn lower(&self) -> Vec<U> {
46 self.iter().map(|item| item.lower()).collect()
50 impl<'tcx> Lower<WhereClause<'tcx>> for ty::TraitPredicate<'tcx> {
51 fn lower(&self) -> WhereClause<'tcx> {
52 WhereClause::Implemented(*self)
56 impl<'tcx> Lower<WhereClause<'tcx>> for ty::ProjectionPredicate<'tcx> {
57 fn lower(&self) -> WhereClause<'tcx> {
58 WhereClause::ProjectionEq(*self)
62 impl<'tcx> Lower<WhereClause<'tcx>> for ty::RegionOutlivesPredicate<'tcx> {
63 fn lower(&self) -> WhereClause<'tcx> {
64 WhereClause::RegionOutlives(*self)
68 impl<'tcx> Lower<WhereClause<'tcx>> for ty::TypeOutlivesPredicate<'tcx> {
69 fn lower(&self) -> WhereClause<'tcx> {
70 WhereClause::TypeOutlives(*self)
74 impl<'tcx, T> Lower<DomainGoal<'tcx>> for T
76 T: Lower<WhereClause<'tcx>>,
78 fn lower(&self) -> DomainGoal<'tcx> {
79 DomainGoal::Holds(self.lower())
83 /// `ty::Binder` is used for wrapping a rustc construction possibly containing generic
84 /// lifetimes, e.g., `for<'a> T: Fn(&'a i32)`. Instead of representing higher-ranked things
85 /// in that leaf-form (i.e., `Holds(Implemented(Binder<TraitPredicate>))` in the previous
86 /// example), we model them with quantified domain goals, e.g., as for the previous example:
87 /// `forall<'a> { T: Fn(&'a i32) }` which corresponds to something like
88 /// `Binder<Holds(Implemented(TraitPredicate))>`.
89 impl<'tcx, T> Lower<PolyDomainGoal<'tcx>> for ty::Binder<T>
91 T: Lower<DomainGoal<'tcx>> + ty::fold::TypeFoldable<'tcx>,
93 fn lower(&self) -> PolyDomainGoal<'tcx> {
94 self.map_bound_ref(|p| p.lower())
98 impl<'tcx> Lower<PolyDomainGoal<'tcx>> for ty::Predicate<'tcx> {
99 fn lower(&self) -> PolyDomainGoal<'tcx> {
100 use rustc::ty::Predicate;
103 Predicate::Trait(predicate) => predicate.lower(),
104 Predicate::RegionOutlives(predicate) => predicate.lower(),
105 Predicate::TypeOutlives(predicate) => predicate.lower(),
106 Predicate::Projection(predicate) => predicate.lower(),
108 Predicate::WellFormed(..) |
109 Predicate::ObjectSafe(..) |
110 Predicate::ClosureKind(..) |
111 Predicate::Subtype(..) |
112 Predicate::ConstEvaluatable(..) => {
113 bug!("unexpected predicate {}", self)
119 /// Used for implied bounds related rules (see rustc guide).
120 trait IntoFromEnvGoal {
121 /// Transforms an existing goal into a `FromEnv` goal.
122 fn into_from_env_goal(self) -> Self;
125 /// Used for well-formedness related rules (see rustc guide).
126 trait IntoWellFormedGoal {
127 /// Transforms an existing goal into a `WellFormed` goal.
128 fn into_well_formed_goal(self) -> Self;
131 impl<'tcx> IntoFromEnvGoal for DomainGoal<'tcx> {
132 fn into_from_env_goal(self) -> DomainGoal<'tcx> {
133 use self::WhereClause::*;
136 DomainGoal::Holds(Implemented(trait_ref)) => {
137 DomainGoal::FromEnv(FromEnv::Trait(trait_ref))
144 impl<'tcx> IntoWellFormedGoal for DomainGoal<'tcx> {
145 fn into_well_formed_goal(self) -> DomainGoal<'tcx> {
146 use self::WhereClause::*;
149 DomainGoal::Holds(Implemented(trait_ref)) => {
150 DomainGoal::WellFormed(WellFormed::Trait(trait_ref))
157 crate fn program_clauses_for<'a, 'tcx>(
158 tcx: TyCtxt<'a, 'tcx, 'tcx>,
161 // FIXME(eddyb) this should only be using `def_kind`.
162 match tcx.def_key(def_id).disambiguated_data.data {
163 DefPathData::TypeNs(..) => match tcx.def_kind(def_id) {
165 | Some(DefKind::TraitAlias) => program_clauses_for_trait(tcx, def_id),
166 // FIXME(eddyb) deduplicate this `associated_item` call with
167 // `program_clauses_for_associated_type_{value,def}`.
168 Some(DefKind::AssociatedTy) => match tcx.associated_item(def_id).container {
169 ty::AssociatedItemContainer::ImplContainer(_) =>
170 program_clauses_for_associated_type_value(tcx, def_id),
171 ty::AssociatedItemContainer::TraitContainer(_) =>
172 program_clauses_for_associated_type_def(tcx, def_id)
174 Some(DefKind::Struct)
175 | Some(DefKind::Enum)
176 | Some(DefKind::TyAlias)
177 | Some(DefKind::Union)
178 | Some(DefKind::Existential) => program_clauses_for_type_def(tcx, def_id),
181 DefPathData::Impl => program_clauses_for_impl(tcx, def_id),
186 fn program_clauses_for_trait<'a, 'tcx>(
187 tcx: TyCtxt<'a, 'tcx, 'tcx>,
190 // `trait Trait<P1..Pn> where WC { .. } // P0 == Self`
192 // Rule Implemented-From-Env (see rustc guide)
195 // forall<Self, P1..Pn> {
196 // Implemented(Self: Trait<P1..Pn>) :- FromEnv(Self: Trait<P1..Pn>)
200 let bound_vars = InternalSubsts::bound_vars_for_item(tcx, def_id);
202 // `Self: Trait<P1..Pn>`
203 let trait_pred = ty::TraitPredicate {
204 trait_ref: ty::TraitRef {
210 // `Implemented(Self: Trait<P1..Pn>)`
211 let impl_trait: DomainGoal<'_> = trait_pred.lower();
213 // `FromEnv(Self: Trait<P1..Pn>)`
214 let from_env_goal = tcx.mk_goal(impl_trait.into_from_env_goal().into_goal());
215 let hypotheses = tcx.intern_goals(&[from_env_goal]);
217 // `Implemented(Self: Trait<P1..Pn>) :- FromEnv(Self: Trait<P1..Pn>)`
218 let implemented_from_env = ProgramClause {
221 category: ProgramClauseCategory::ImpliedBound,
224 let implemented_from_env = Clause::ForAll(ty::Binder::bind(implemented_from_env));
226 let predicates = &tcx.predicates_defined_on(def_id).predicates;
228 // Warning: these where clauses are not substituted for bound vars yet,
229 // so that we don't need to adjust binders in the `FromEnv` rules below
231 let where_clauses = &predicates
233 .map(|(wc, _)| wc.lower())
234 .collect::<Vec<_>>();
236 // Rule Implied-Bound-From-Trait
238 // For each where clause WC:
240 // forall<Self, P1..Pn> {
241 // FromEnv(WC) :- FromEnv(Self: Trait<P1..Pn)
245 // `FromEnv(WC) :- FromEnv(Self: Trait<P1..Pn>)`, for each where clause WC
246 let implied_bound_clauses = where_clauses
250 // `FromEnv(WC) :- FromEnv(Self: Trait<P1..Pn>)`
252 // we move binders to the left
253 wc.map_bound(|goal| ProgramClause {
254 // FIXME: As where clauses can only bind lifetimes for now, and that named
255 // bound regions have a def-id, it is safe to just inject `bound_vars` and
256 // `hypotheses` (which contain named vars bound at index `0`) into this
257 // binding level. This may change if we ever allow where clauses to bind
258 // types (e.g. for GATs things), because bound types only use a `BoundVar`
259 // index (no def-id).
260 goal: goal.subst(tcx, bound_vars).into_from_env_goal(),
263 category: ProgramClauseCategory::ImpliedBound,
266 .map(Clause::ForAll);
268 // Rule WellFormed-TraitRef
270 // Here `WC` denotes the set of all where clauses:
272 // forall<Self, P1..Pn> {
273 // WellFormed(Self: Trait<P1..Pn>) :- Implemented(Self: Trait<P1..Pn>) && WellFormed(WC)
278 let wf_conditions = where_clauses
280 .map(|wc| wc.subst(tcx, bound_vars))
281 .map(|wc| wc.map_bound(|goal| goal.into_well_formed_goal()));
283 // `WellFormed(Self: Trait<P1..Pn>) :- Implemented(Self: Trait<P1..Pn>) && WellFormed(WC)`
284 let wf_clause = ProgramClause {
285 goal: DomainGoal::WellFormed(WellFormed::Trait(trait_pred)),
286 hypotheses: tcx.mk_goals(
287 iter::once(tcx.mk_goal(GoalKind::DomainGoal(impl_trait))).chain(
288 wf_conditions.map(|wc| tcx.mk_goal(GoalKind::from_poly_domain_goal(wc, tcx)))
291 category: ProgramClauseCategory::WellFormed,
293 let wf_clause = Clause::ForAll(ty::Binder::bind(wf_clause));
296 iter::once(implemented_from_env)
297 .chain(implied_bound_clauses)
298 .chain(iter::once(wf_clause))
302 fn program_clauses_for_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Clauses<'tcx> {
303 if let ImplPolarity::Negative = tcx.impl_polarity(def_id) {
304 return List::empty();
307 // Rule Implemented-From-Impl (see rustc guide)
309 // `impl<P0..Pn> Trait<A1..An> for A0 where WC { .. }`
313 // Implemented(A0: Trait<A1..An>) :- WC
317 let bound_vars = InternalSubsts::bound_vars_for_item(tcx, def_id);
319 let trait_ref = tcx.impl_trait_ref(def_id)
320 .expect("not an impl")
321 .subst(tcx, bound_vars);
323 // `Implemented(A0: Trait<A1..An>)`
324 let trait_pred = ty::TraitPredicate { trait_ref }.lower();
327 let predicates = &tcx.predicates_of(def_id).predicates;
328 let where_clauses = predicates
330 .map(|(wc, _)| wc.lower())
331 .map(|wc| wc.subst(tcx, bound_vars));
333 // `Implemented(A0: Trait<A1..An>) :- WC`
334 let clause = ProgramClause {
336 hypotheses: tcx.mk_goals(
338 .map(|wc| tcx.mk_goal(GoalKind::from_poly_domain_goal(wc, tcx))),
340 category: ProgramClauseCategory::Other,
342 tcx.mk_clauses(iter::once(Clause::ForAll(ty::Binder::bind(clause))))
345 pub fn program_clauses_for_type_def<'a, 'tcx>(
346 tcx: TyCtxt<'a, 'tcx, 'tcx>,
349 // Rule WellFormed-Type
351 // `struct Ty<P1..Pn> where WC1, ..., WCm`
355 // WellFormed(Ty<...>) :- WellFormed(WC1), ..., WellFormed(WCm)`
359 let bound_vars = InternalSubsts::bound_vars_for_item(tcx, def_id);
362 let ty = tcx.type_of(def_id).subst(tcx, bound_vars);
364 // Warning: these where clauses are not substituted for bound vars yet,
365 // so that we don't need to adjust binders in the `FromEnv` rules below
367 let where_clauses = tcx.predicates_of(def_id).predicates
369 .map(|(wc, _)| wc.lower())
370 .collect::<Vec<_>>();
372 // `WellFormed(Ty<...>) :- WellFormed(WC1), ..., WellFormed(WCm)`
373 let well_formed_clause = ProgramClause {
374 goal: DomainGoal::WellFormed(WellFormed::Ty(ty)),
375 hypotheses: tcx.mk_goals(
378 .map(|wc| wc.subst(tcx, bound_vars))
379 .map(|wc| wc.map_bound(|bound| bound.into_well_formed_goal()))
380 .map(|wc| tcx.mk_goal(GoalKind::from_poly_domain_goal(wc, tcx))),
382 category: ProgramClauseCategory::WellFormed,
384 let well_formed_clause = Clause::ForAll(ty::Binder::bind(well_formed_clause));
386 // Rule Implied-Bound-From-Type
388 // For each where clause `WC`:
391 // FromEnv(WC) :- FromEnv(Ty<...>)
395 // `FromEnv(Ty<...>)`
396 let from_env_goal = tcx.mk_goal(DomainGoal::FromEnv(FromEnv::Ty(ty)).into_goal());
397 let hypotheses = tcx.intern_goals(&[from_env_goal]);
399 // For each where clause `WC`:
400 let from_env_clauses = where_clauses
403 // `FromEnv(WC) :- FromEnv(Ty<...>)`
405 // move the binders to the left
406 wc.map_bound(|goal| ProgramClause {
407 // FIXME: we inject `bound_vars` and `hypotheses` into this binding
408 // level, which may be incorrect in the future: see the FIXME in
409 // `program_clauses_for_trait`.
410 goal: goal.subst(tcx, bound_vars).into_from_env_goal(),
413 category: ProgramClauseCategory::ImpliedBound,
417 .map(Clause::ForAll);
419 tcx.mk_clauses(iter::once(well_formed_clause).chain(from_env_clauses))
422 pub fn program_clauses_for_associated_type_def<'a, 'tcx>(
423 tcx: TyCtxt<'a, 'tcx, 'tcx>,
426 // Rule ProjectionEq-Placeholder
429 // trait Trait<P1..Pn> {
430 // type AssocType<Pn+1..Pm>;
434 // `ProjectionEq` can succeed by skolemizing, see "associated type"
437 // forall<Self, P1..Pn, Pn+1..Pm> {
439 // <Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> =
440 // (Trait::AssocType)<Self, P1..Pn, Pn+1..Pm>
445 let item = tcx.associated_item(item_id);
446 debug_assert_eq!(item.kind, ty::AssociatedKind::Type);
447 let trait_id = match item.container {
448 ty::AssociatedItemContainer::TraitContainer(trait_id) => trait_id,
449 _ => bug!("not an trait container"),
452 let trait_bound_vars = InternalSubsts::bound_vars_for_item(tcx, trait_id);
453 let trait_ref = ty::TraitRef {
455 substs: trait_bound_vars,
458 let projection_ty = ty::ProjectionTy::from_ref_and_name(tcx, trait_ref, item.ident);
459 let placeholder_ty = tcx.mk_ty(ty::UnnormalizedProjection(projection_ty));
460 let projection_eq = WhereClause::ProjectionEq(ty::ProjectionPredicate {
465 let projection_eq_clause = ProgramClause {
466 goal: DomainGoal::Holds(projection_eq),
467 hypotheses: ty::List::empty(),
468 category: ProgramClauseCategory::Other,
470 let projection_eq_clause = Clause::ForAll(ty::Binder::bind(projection_eq_clause));
472 // Rule WellFormed-AssocTy
474 // forall<Self, P1..Pn, Pn+1..Pm> {
475 // WellFormed((Trait::AssocType)<Self, P1..Pn, Pn+1..Pm>)
476 // :- WellFormed(Self: Trait<P1..Pn>)
480 let trait_predicate = ty::TraitPredicate { trait_ref };
481 let hypothesis = tcx.mk_goal(
482 DomainGoal::WellFormed(WellFormed::Trait(trait_predicate)).into_goal()
485 let wf_clause = ProgramClause {
486 goal: DomainGoal::WellFormed(WellFormed::Ty(placeholder_ty)),
487 hypotheses: tcx.mk_goals(iter::once(hypothesis)),
488 category: ProgramClauseCategory::WellFormed,
490 let wf_clause = Clause::ForAll(ty::Binder::bind(wf_clause));
492 // Rule Implied-Trait-From-AssocTy
494 // forall<Self, P1..Pn, Pn+1..Pm> {
495 // FromEnv(Self: Trait<P1..Pn>)
496 // :- FromEnv((Trait::AssocType)<Self, P1..Pn, Pn+1..Pm>)
500 let hypothesis = tcx.mk_goal(
501 DomainGoal::FromEnv(FromEnv::Ty(placeholder_ty)).into_goal()
504 let from_env_clause = ProgramClause {
505 goal: DomainGoal::FromEnv(FromEnv::Trait(trait_predicate)),
506 hypotheses: tcx.mk_goals(iter::once(hypothesis)),
507 category: ProgramClauseCategory::ImpliedBound,
509 let from_env_clause = Clause::ForAll(ty::Binder::bind(from_env_clause));
511 // Rule ProjectionEq-Normalize
513 // ProjectionEq can succeed by normalizing:
515 // forall<Self, P1..Pn, Pn+1..Pm, U> {
516 // ProjectionEq(<Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> = U) :-
517 // Normalize(<Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> -> U)
521 let offset = tcx.generics_of(trait_id).params
526 // Add a new type param after the existing ones (`U` in the comment above).
527 let ty_var = ty::Bound(
529 ty::BoundVar::from_u32(offset + 1).into()
532 // `ProjectionEq(<Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> = U)`
533 let projection = ty::ProjectionPredicate {
535 ty: tcx.mk_ty(ty_var),
538 // `Normalize(<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm> -> U)`
539 let hypothesis = tcx.mk_goal(
540 DomainGoal::Normalize(projection).into_goal()
543 // ProjectionEq(<Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> = U) :-
544 // Normalize(<Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> -> U)
545 let normalize_clause = ProgramClause {
546 goal: DomainGoal::Holds(WhereClause::ProjectionEq(projection)),
547 hypotheses: tcx.mk_goals(iter::once(hypothesis)),
548 category: ProgramClauseCategory::Other,
550 let normalize_clause = Clause::ForAll(ty::Binder::bind(normalize_clause));
552 let clauses = iter::once(projection_eq_clause)
553 .chain(iter::once(wf_clause))
554 .chain(iter::once(from_env_clause))
555 .chain(iter::once(normalize_clause));
557 tcx.mk_clauses(clauses)
560 pub fn program_clauses_for_associated_type_value<'a, 'tcx>(
561 tcx: TyCtxt<'a, 'tcx, 'tcx>,
564 // Rule Normalize-From-Impl (see rustc guide)
567 // impl<P0..Pn> Trait<A1..An> for A0 {
568 // type AssocType<Pn+1..Pm> = T;
572 // FIXME: For the moment, we don't account for where clauses written on the associated
573 // ty definition (i.e., in the trait def, as in `type AssocType<T> where T: Sized`).
576 // forall<Pn+1..Pm> {
577 // Normalize(<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm> -> T) :-
578 // Implemented(A0: Trait<A1..An>)
583 let item = tcx.associated_item(item_id);
584 debug_assert_eq!(item.kind, ty::AssociatedKind::Type);
585 let impl_id = match item.container {
586 ty::AssociatedItemContainer::ImplContainer(impl_id) => impl_id,
587 _ => bug!("not an impl container"),
590 let impl_bound_vars = InternalSubsts::bound_vars_for_item(tcx, impl_id);
592 // `A0 as Trait<A1..An>`
593 let trait_ref = tcx.impl_trait_ref(impl_id)
595 .subst(tcx, impl_bound_vars);
598 let ty = tcx.type_of(item_id);
600 // `Implemented(A0: Trait<A1..An>)`
601 let trait_implemented: DomainGoal<'_> = ty::TraitPredicate { trait_ref }.lower();
603 // `<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm>`
604 let projection_ty = ty::ProjectionTy::from_ref_and_name(tcx, trait_ref, item.ident);
606 // `Normalize(<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm> -> T)`
607 let normalize_goal = DomainGoal::Normalize(ty::ProjectionPredicate { projection_ty, ty });
609 // `Normalize(... -> T) :- ...`
610 let normalize_clause = ProgramClause {
611 goal: normalize_goal,
612 hypotheses: tcx.mk_goals(
613 iter::once(tcx.mk_goal(GoalKind::DomainGoal(trait_implemented)))
615 category: ProgramClauseCategory::Other,
617 let normalize_clause = Clause::ForAll(ty::Binder::bind(normalize_clause));
619 tcx.mk_clauses(iter::once(normalize_clause))
622 pub fn dump_program_clauses<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
623 if !tcx.features().rustc_attrs {
627 let mut visitor = ClauseDumper { tcx };
630 .visit_all_item_likes(&mut visitor.as_deep_visitor());
633 struct ClauseDumper<'a, 'tcx: 'a> {
634 tcx: TyCtxt<'a, 'tcx, 'tcx>,
637 impl<'a, 'tcx> ClauseDumper<'a, 'tcx> {
638 fn process_attrs(&mut self, hir_id: hir::HirId, attrs: &[ast::Attribute]) {
639 let def_id = self.tcx.hir().local_def_id_from_hir_id(hir_id);
641 let mut clauses = None;
643 if attr.check_name("rustc_dump_program_clauses") {
644 clauses = Some(self.tcx.program_clauses_for(def_id));
647 if attr.check_name("rustc_dump_env_program_clauses") {
648 let environment = self.tcx.environment(def_id);
649 clauses = Some(self.tcx.program_clauses_for_env(environment));
652 if let Some(clauses) = clauses {
656 .struct_span_err(attr.span, "program clause dump");
658 let mut strings: Vec<_> = clauses
660 .map(|clause| clause.to_string())
665 for string in strings {
675 impl<'a, 'tcx> Visitor<'tcx> for ClauseDumper<'a, 'tcx> {
676 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
677 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
680 fn visit_item(&mut self, item: &'tcx hir::Item) {
681 self.process_attrs(item.hir_id, &item.attrs);
682 intravisit::walk_item(self, item);
685 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
686 self.process_attrs(trait_item.hir_id, &trait_item.attrs);
687 intravisit::walk_trait_item(self, trait_item);
690 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
691 self.process_attrs(impl_item.hir_id, &impl_item.attrs);
692 intravisit::walk_impl_item(self, impl_item);
695 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
696 self.process_attrs(s.hir_id, &s.attrs);
697 intravisit::walk_struct_field(self, s);