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;
16 ProgramClauseCategory,
20 use rustc::ty::query::Providers;
21 use rustc::ty::{self, List, TyCtxt};
22 use rustc::ty::subst::{Subst, InternalSubsts};
24 use syntax::symbol::sym;
28 crate fn provide(p: &mut Providers<'_>) {
31 program_clauses_for_env: environment::program_clauses_for_env,
32 environment: environment::environment,
37 crate trait Lower<T> {
38 /// Lower a rustc construct (e.g., `ty::TraitPredicate`) to a chalk-like type.
42 impl<T, U> Lower<Vec<U>> for Vec<T>
46 fn lower(&self) -> Vec<U> {
47 self.iter().map(|item| item.lower()).collect()
51 impl<'tcx> Lower<WhereClause<'tcx>> for ty::TraitPredicate<'tcx> {
52 fn lower(&self) -> WhereClause<'tcx> {
53 WhereClause::Implemented(*self)
57 impl<'tcx> Lower<WhereClause<'tcx>> for ty::ProjectionPredicate<'tcx> {
58 fn lower(&self) -> WhereClause<'tcx> {
59 WhereClause::ProjectionEq(*self)
63 impl<'tcx> Lower<WhereClause<'tcx>> for ty::RegionOutlivesPredicate<'tcx> {
64 fn lower(&self) -> WhereClause<'tcx> {
65 WhereClause::RegionOutlives(*self)
69 impl<'tcx> Lower<WhereClause<'tcx>> for ty::TypeOutlivesPredicate<'tcx> {
70 fn lower(&self) -> WhereClause<'tcx> {
71 WhereClause::TypeOutlives(*self)
75 impl<'tcx, T> Lower<DomainGoal<'tcx>> for T
77 T: Lower<WhereClause<'tcx>>,
79 fn lower(&self) -> DomainGoal<'tcx> {
80 DomainGoal::Holds(self.lower())
84 /// `ty::Binder` is used for wrapping a rustc construction possibly containing generic
85 /// lifetimes, e.g., `for<'a> T: Fn(&'a i32)`. Instead of representing higher-ranked things
86 /// in that leaf-form (i.e., `Holds(Implemented(Binder<TraitPredicate>))` in the previous
87 /// example), we model them with quantified domain goals, e.g., as for the previous example:
88 /// `forall<'a> { T: Fn(&'a i32) }` which corresponds to something like
89 /// `Binder<Holds(Implemented(TraitPredicate))>`.
90 impl<'tcx, T> Lower<PolyDomainGoal<'tcx>> for ty::Binder<T>
92 T: Lower<DomainGoal<'tcx>> + ty::fold::TypeFoldable<'tcx>,
94 fn lower(&self) -> PolyDomainGoal<'tcx> {
95 self.map_bound_ref(|p| p.lower())
99 impl<'tcx> Lower<PolyDomainGoal<'tcx>> for ty::Predicate<'tcx> {
100 fn lower(&self) -> PolyDomainGoal<'tcx> {
101 use rustc::ty::Predicate;
104 Predicate::Trait(predicate) => predicate.lower(),
105 Predicate::RegionOutlives(predicate) => predicate.lower(),
106 Predicate::TypeOutlives(predicate) => predicate.lower(),
107 Predicate::Projection(predicate) => predicate.lower(),
109 Predicate::WellFormed(..) |
110 Predicate::ObjectSafe(..) |
111 Predicate::ClosureKind(..) |
112 Predicate::Subtype(..) |
113 Predicate::ConstEvaluatable(..) => {
114 bug!("unexpected predicate {}", self)
120 /// Used for implied bounds related rules (see rustc guide).
121 trait IntoFromEnvGoal {
122 /// Transforms an existing goal into a `FromEnv` goal.
123 fn into_from_env_goal(self) -> Self;
126 /// Used for well-formedness related rules (see rustc guide).
127 trait IntoWellFormedGoal {
128 /// Transforms an existing goal into a `WellFormed` goal.
129 fn into_well_formed_goal(self) -> Self;
132 impl<'tcx> IntoFromEnvGoal for DomainGoal<'tcx> {
133 fn into_from_env_goal(self) -> DomainGoal<'tcx> {
134 use self::WhereClause::*;
137 DomainGoal::Holds(Implemented(trait_ref)) => {
138 DomainGoal::FromEnv(FromEnv::Trait(trait_ref))
145 impl<'tcx> IntoWellFormedGoal for DomainGoal<'tcx> {
146 fn into_well_formed_goal(self) -> DomainGoal<'tcx> {
147 use self::WhereClause::*;
150 DomainGoal::Holds(Implemented(trait_ref)) => {
151 DomainGoal::WellFormed(WellFormed::Trait(trait_ref))
158 crate fn program_clauses_for(tcx: TyCtxt<'_>, def_id: DefId) -> Clauses<'_> {
159 // FIXME(eddyb) this should only be using `def_kind`.
160 match tcx.def_key(def_id).disambiguated_data.data {
161 DefPathData::TypeNs(..) => match tcx.def_kind(def_id) {
163 | Some(DefKind::TraitAlias) => program_clauses_for_trait(tcx, def_id),
164 // FIXME(eddyb) deduplicate this `associated_item` call with
165 // `program_clauses_for_associated_type_{value,def}`.
166 Some(DefKind::AssocTy) => match tcx.associated_item(def_id).container {
167 ty::AssocItemContainer::ImplContainer(_) =>
168 program_clauses_for_associated_type_value(tcx, def_id),
169 ty::AssocItemContainer::TraitContainer(_) =>
170 program_clauses_for_associated_type_def(tcx, def_id)
172 Some(DefKind::Struct)
173 | Some(DefKind::Enum)
174 | Some(DefKind::TyAlias)
175 | Some(DefKind::Union)
176 | Some(DefKind::OpaqueTy) => program_clauses_for_type_def(tcx, def_id),
179 DefPathData::Impl => program_clauses_for_impl(tcx, def_id),
184 fn program_clauses_for_trait(tcx: TyCtxt<'_>, def_id: DefId) -> Clauses<'_> {
185 // `trait Trait<P1..Pn> where WC { .. } // P0 == Self`
187 // Rule Implemented-From-Env (see rustc guide)
190 // forall<Self, P1..Pn> {
191 // Implemented(Self: Trait<P1..Pn>) :- FromEnv(Self: Trait<P1..Pn>)
195 let bound_vars = InternalSubsts::bound_vars_for_item(tcx, def_id);
197 // `Self: Trait<P1..Pn>`
198 let trait_pred = ty::TraitPredicate {
199 trait_ref: ty::TraitRef {
205 // `Implemented(Self: Trait<P1..Pn>)`
206 let impl_trait: DomainGoal<'_> = trait_pred.lower();
208 // `FromEnv(Self: Trait<P1..Pn>)`
209 let from_env_goal = tcx.mk_goal(impl_trait.into_from_env_goal().into_goal());
210 let hypotheses = tcx.intern_goals(&[from_env_goal]);
212 // `Implemented(Self: Trait<P1..Pn>) :- FromEnv(Self: Trait<P1..Pn>)`
213 let implemented_from_env = ProgramClause {
216 category: ProgramClauseCategory::ImpliedBound,
219 let implemented_from_env = Clause::ForAll(ty::Binder::bind(implemented_from_env));
221 let predicates = tcx.predicates_defined_on(def_id).predicates;
223 // Warning: these where clauses are not substituted for bound vars yet,
224 // so that we don't need to adjust binders in the `FromEnv` rules below
226 let where_clauses = &predicates
228 .map(|(wc, _)| wc.lower())
229 .collect::<Vec<_>>();
231 // Rule Implied-Bound-From-Trait
233 // For each where clause WC:
235 // forall<Self, P1..Pn> {
236 // FromEnv(WC) :- FromEnv(Self: Trait<P1..Pn)
240 // `FromEnv(WC) :- FromEnv(Self: Trait<P1..Pn>)`, for each where clause WC
241 let implied_bound_clauses = where_clauses
245 // `FromEnv(WC) :- FromEnv(Self: Trait<P1..Pn>)`
247 // we move binders to the left
248 wc.map_bound(|goal| ProgramClause {
249 // FIXME: As where clauses can only bind lifetimes for now, and that named
250 // bound regions have a def-id, it is safe to just inject `bound_vars` and
251 // `hypotheses` (which contain named vars bound at index `0`) into this
252 // binding level. This may change if we ever allow where clauses to bind
253 // types (e.g. for GATs things), because bound types only use a `BoundVar`
254 // index (no def-id).
255 goal: goal.subst(tcx, bound_vars).into_from_env_goal(),
258 category: ProgramClauseCategory::ImpliedBound,
261 .map(Clause::ForAll);
263 // Rule WellFormed-TraitRef
265 // Here `WC` denotes the set of all where clauses:
267 // forall<Self, P1..Pn> {
268 // WellFormed(Self: Trait<P1..Pn>) :- Implemented(Self: Trait<P1..Pn>) && WellFormed(WC)
273 let wf_conditions = where_clauses
275 .map(|wc| wc.subst(tcx, bound_vars))
276 .map(|wc| wc.map_bound(|goal| goal.into_well_formed_goal()));
278 // `WellFormed(Self: Trait<P1..Pn>) :- Implemented(Self: Trait<P1..Pn>) && WellFormed(WC)`
279 let wf_clause = ProgramClause {
280 goal: DomainGoal::WellFormed(WellFormed::Trait(trait_pred)),
281 hypotheses: tcx.mk_goals(
282 iter::once(tcx.mk_goal(GoalKind::DomainGoal(impl_trait))).chain(
283 wf_conditions.map(|wc| tcx.mk_goal(GoalKind::from_poly_domain_goal(wc, tcx)))
286 category: ProgramClauseCategory::WellFormed,
288 let wf_clause = Clause::ForAll(ty::Binder::bind(wf_clause));
291 iter::once(implemented_from_env)
292 .chain(implied_bound_clauses)
293 .chain(iter::once(wf_clause))
297 fn program_clauses_for_impl(tcx: TyCtxt<'tcx>, def_id: DefId) -> Clauses<'tcx> {
298 if let ty::ImplPolarity::Negative = tcx.impl_polarity(def_id) {
299 return List::empty();
302 // Rule Implemented-From-Impl (see rustc guide)
304 // `impl<P0..Pn> Trait<A1..An> for A0 where WC { .. }`
308 // Implemented(A0: Trait<A1..An>) :- WC
312 let bound_vars = InternalSubsts::bound_vars_for_item(tcx, def_id);
314 let trait_ref = tcx.impl_trait_ref(def_id)
315 .expect("not an impl")
316 .subst(tcx, bound_vars);
318 // `Implemented(A0: Trait<A1..An>)`
319 let trait_pred = ty::TraitPredicate { trait_ref }.lower();
322 let predicates = tcx.predicates_of(def_id).predicates;
323 let where_clauses = predicates
325 .map(|(wc, _)| wc.lower())
326 .map(|wc| wc.subst(tcx, bound_vars));
328 // `Implemented(A0: Trait<A1..An>) :- WC`
329 let clause = ProgramClause {
331 hypotheses: tcx.mk_goals(
333 .map(|wc| tcx.mk_goal(GoalKind::from_poly_domain_goal(wc, tcx))),
335 category: ProgramClauseCategory::Other,
337 tcx.mk_clauses(iter::once(Clause::ForAll(ty::Binder::bind(clause))))
340 pub fn program_clauses_for_type_def(tcx: TyCtxt<'_>, def_id: DefId) -> Clauses<'_> {
341 // Rule WellFormed-Type
343 // `struct Ty<P1..Pn> where WC1, ..., WCm`
347 // WellFormed(Ty<...>) :- WellFormed(WC1), ..., WellFormed(WCm)`
351 let bound_vars = InternalSubsts::bound_vars_for_item(tcx, def_id);
354 let ty = tcx.type_of(def_id).subst(tcx, bound_vars);
356 // Warning: these where clauses are not substituted for bound vars yet,
357 // so that we don't need to adjust binders in the `FromEnv` rules below
359 let where_clauses = tcx.predicates_of(def_id).predicates
361 .map(|(wc, _)| wc.lower())
362 .collect::<Vec<_>>();
364 // `WellFormed(Ty<...>) :- WellFormed(WC1), ..., WellFormed(WCm)`
365 let well_formed_clause = ProgramClause {
366 goal: DomainGoal::WellFormed(WellFormed::Ty(ty)),
367 hypotheses: tcx.mk_goals(
370 .map(|wc| wc.subst(tcx, bound_vars))
371 .map(|wc| wc.map_bound(|bound| bound.into_well_formed_goal()))
372 .map(|wc| tcx.mk_goal(GoalKind::from_poly_domain_goal(wc, tcx))),
374 category: ProgramClauseCategory::WellFormed,
376 let well_formed_clause = Clause::ForAll(ty::Binder::bind(well_formed_clause));
378 // Rule Implied-Bound-From-Type
380 // For each where clause `WC`:
383 // FromEnv(WC) :- FromEnv(Ty<...>)
387 // `FromEnv(Ty<...>)`
388 let from_env_goal = tcx.mk_goal(DomainGoal::FromEnv(FromEnv::Ty(ty)).into_goal());
389 let hypotheses = tcx.intern_goals(&[from_env_goal]);
391 // For each where clause `WC`:
392 let from_env_clauses = where_clauses
395 // `FromEnv(WC) :- FromEnv(Ty<...>)`
397 // move the binders to the left
398 wc.map_bound(|goal| ProgramClause {
399 // FIXME: we inject `bound_vars` and `hypotheses` into this binding
400 // level, which may be incorrect in the future: see the FIXME in
401 // `program_clauses_for_trait`.
402 goal: goal.subst(tcx, bound_vars).into_from_env_goal(),
405 category: ProgramClauseCategory::ImpliedBound,
409 .map(Clause::ForAll);
411 tcx.mk_clauses(iter::once(well_formed_clause).chain(from_env_clauses))
414 pub fn program_clauses_for_associated_type_def(
418 // Rule ProjectionEq-Placeholder
421 // trait Trait<P1..Pn> {
422 // type AssocType<Pn+1..Pm>;
426 // `ProjectionEq` can succeed by skolemizing, see "associated type"
429 // forall<Self, P1..Pn, Pn+1..Pm> {
431 // <Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> =
432 // (Trait::AssocType)<Self, P1..Pn, Pn+1..Pm>
437 let item = tcx.associated_item(item_id);
438 debug_assert_eq!(item.kind, ty::AssocKind::Type);
439 let trait_id = match item.container {
440 ty::AssocItemContainer::TraitContainer(trait_id) => trait_id,
441 _ => bug!("not an trait container"),
444 let trait_bound_vars = InternalSubsts::bound_vars_for_item(tcx, trait_id);
445 let trait_ref = ty::TraitRef {
447 substs: trait_bound_vars,
450 let projection_ty = ty::ProjectionTy::from_ref_and_name(tcx, trait_ref, item.ident);
451 let placeholder_ty = tcx.mk_ty(ty::UnnormalizedProjection(projection_ty));
452 let projection_eq = WhereClause::ProjectionEq(ty::ProjectionPredicate {
457 let projection_eq_clause = ProgramClause {
458 goal: DomainGoal::Holds(projection_eq),
459 hypotheses: ty::List::empty(),
460 category: ProgramClauseCategory::Other,
462 let projection_eq_clause = Clause::ForAll(ty::Binder::bind(projection_eq_clause));
464 // Rule WellFormed-AssocTy
466 // forall<Self, P1..Pn, Pn+1..Pm> {
467 // WellFormed((Trait::AssocType)<Self, P1..Pn, Pn+1..Pm>)
468 // :- WellFormed(Self: Trait<P1..Pn>)
472 let trait_predicate = ty::TraitPredicate { trait_ref };
473 let hypothesis = tcx.mk_goal(
474 DomainGoal::WellFormed(WellFormed::Trait(trait_predicate)).into_goal()
477 let wf_clause = ProgramClause {
478 goal: DomainGoal::WellFormed(WellFormed::Ty(placeholder_ty)),
479 hypotheses: tcx.mk_goals(iter::once(hypothesis)),
480 category: ProgramClauseCategory::WellFormed,
482 let wf_clause = Clause::ForAll(ty::Binder::bind(wf_clause));
484 // Rule Implied-Trait-From-AssocTy
486 // forall<Self, P1..Pn, Pn+1..Pm> {
487 // FromEnv(Self: Trait<P1..Pn>)
488 // :- FromEnv((Trait::AssocType)<Self, P1..Pn, Pn+1..Pm>)
492 let hypothesis = tcx.mk_goal(
493 DomainGoal::FromEnv(FromEnv::Ty(placeholder_ty)).into_goal()
496 let from_env_clause = ProgramClause {
497 goal: DomainGoal::FromEnv(FromEnv::Trait(trait_predicate)),
498 hypotheses: tcx.mk_goals(iter::once(hypothesis)),
499 category: ProgramClauseCategory::ImpliedBound,
501 let from_env_clause = Clause::ForAll(ty::Binder::bind(from_env_clause));
503 // Rule ProjectionEq-Normalize
505 // ProjectionEq can succeed by normalizing:
507 // forall<Self, P1..Pn, Pn+1..Pm, U> {
508 // ProjectionEq(<Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> = U) :-
509 // Normalize(<Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> -> U)
513 let offset = tcx.generics_of(trait_id).params
518 // Add a new type param after the existing ones (`U` in the comment above).
519 let ty_var = ty::Bound(
521 ty::BoundVar::from_u32(offset + 1).into()
524 // `ProjectionEq(<Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> = U)`
525 let projection = ty::ProjectionPredicate {
527 ty: tcx.mk_ty(ty_var),
530 // `Normalize(<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm> -> U)`
531 let hypothesis = tcx.mk_goal(
532 DomainGoal::Normalize(projection).into_goal()
535 // ProjectionEq(<Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> = U) :-
536 // Normalize(<Self as Trait<P1..Pn>>::AssocType<Pn+1..Pm> -> U)
537 let normalize_clause = ProgramClause {
538 goal: DomainGoal::Holds(WhereClause::ProjectionEq(projection)),
539 hypotheses: tcx.mk_goals(iter::once(hypothesis)),
540 category: ProgramClauseCategory::Other,
542 let normalize_clause = Clause::ForAll(ty::Binder::bind(normalize_clause));
544 let clauses = iter::once(projection_eq_clause)
545 .chain(iter::once(wf_clause))
546 .chain(iter::once(from_env_clause))
547 .chain(iter::once(normalize_clause));
549 tcx.mk_clauses(clauses)
552 pub fn program_clauses_for_associated_type_value(
556 // Rule Normalize-From-Impl (see rustc guide)
559 // impl<P0..Pn> Trait<A1..An> for A0 {
560 // type AssocType<Pn+1..Pm> = T;
564 // FIXME: For the moment, we don't account for where clauses written on the associated
565 // ty definition (i.e., in the trait def, as in `type AssocType<T> where T: Sized`).
568 // forall<Pn+1..Pm> {
569 // Normalize(<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm> -> T) :-
570 // Implemented(A0: Trait<A1..An>)
575 let item = tcx.associated_item(item_id);
576 debug_assert_eq!(item.kind, ty::AssocKind::Type);
577 let impl_id = match item.container {
578 ty::AssocItemContainer::ImplContainer(impl_id) => impl_id,
579 _ => bug!("not an impl container"),
582 let impl_bound_vars = InternalSubsts::bound_vars_for_item(tcx, impl_id);
584 // `A0 as Trait<A1..An>`
585 let trait_ref = tcx.impl_trait_ref(impl_id)
587 .subst(tcx, impl_bound_vars);
590 let ty = tcx.type_of(item_id);
592 // `Implemented(A0: Trait<A1..An>)`
593 let trait_implemented: DomainGoal<'_> = ty::TraitPredicate { trait_ref }.lower();
595 // `<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm>`
596 let projection_ty = ty::ProjectionTy::from_ref_and_name(tcx, trait_ref, item.ident);
598 // `Normalize(<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm> -> T)`
599 let normalize_goal = DomainGoal::Normalize(ty::ProjectionPredicate { projection_ty, ty });
601 // `Normalize(... -> T) :- ...`
602 let normalize_clause = ProgramClause {
603 goal: normalize_goal,
604 hypotheses: tcx.mk_goals(
605 iter::once(tcx.mk_goal(GoalKind::DomainGoal(trait_implemented)))
607 category: ProgramClauseCategory::Other,
609 let normalize_clause = Clause::ForAll(ty::Binder::bind(normalize_clause));
611 tcx.mk_clauses(iter::once(normalize_clause))
614 pub fn dump_program_clauses(tcx: TyCtxt<'_>) {
615 if !tcx.features().rustc_attrs {
619 let mut visitor = ClauseDumper { tcx };
622 .visit_all_item_likes(&mut visitor.as_deep_visitor());
625 struct ClauseDumper<'tcx> {
629 impl ClauseDumper<'tcx> {
630 fn process_attrs(&mut self, hir_id: hir::HirId, attrs: &[ast::Attribute]) {
631 let def_id = self.tcx.hir().local_def_id(hir_id);
633 let mut clauses = None;
635 if attr.check_name(sym::rustc_dump_program_clauses) {
636 clauses = Some(self.tcx.program_clauses_for(def_id));
639 if attr.check_name(sym::rustc_dump_env_program_clauses) {
640 let environment = self.tcx.environment(def_id);
641 clauses = Some(self.tcx.program_clauses_for_env(environment));
644 if let Some(clauses) = clauses {
648 .struct_span_err(attr.span, "program clause dump");
650 let mut strings: Vec<_> = clauses
652 .map(|clause| clause.to_string())
657 for string in strings {
667 impl Visitor<'tcx> for ClauseDumper<'tcx> {
668 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
669 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
672 fn visit_item(&mut self, item: &'tcx hir::Item) {
673 self.process_attrs(item.hir_id, &item.attrs);
674 intravisit::walk_item(self, item);
677 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
678 self.process_attrs(trait_item.hir_id, &trait_item.attrs);
679 intravisit::walk_trait_item(self, trait_item);
682 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
683 self.process_attrs(impl_item.hir_id, &impl_item.attrs);
684 intravisit::walk_impl_item(self, impl_item);
687 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
688 self.process_attrs(s.hir_id, &s.attrs);
689 intravisit::walk_struct_field(self, s);