Skip to content

Commit 8f0e73e

Browse files
committed
Address review comments
1 parent 9bcfdb7 commit 8f0e73e

File tree

9 files changed

+99
-107
lines changed

9 files changed

+99
-107
lines changed

src/librustc/middle/traits/project.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -100,21 +100,21 @@ pub enum ProjectionMode {
100100
}
101101

102102
impl ProjectionMode {
103-
pub fn topmost(&self) -> bool {
103+
pub fn is_topmost(&self) -> bool {
104104
match *self {
105105
ProjectionMode::Topmost => true,
106106
_ => false,
107107
}
108108
}
109109

110-
pub fn any_final(&self) -> bool {
110+
pub fn is_any_final(&self) -> bool {
111111
match *self {
112112
ProjectionMode::AnyFinal => true,
113113
_ => false,
114114
}
115115
}
116116

117-
pub fn any(&self) -> bool {
117+
pub fn is_any(&self) -> bool {
118118
match *self {
119119
ProjectionMode::Any => true,
120120
_ => false,
@@ -665,7 +665,7 @@ fn project_type<'cx,'tcx>(
665665
// In Any (i.e. trans) mode, all projections succeed;
666666
// otherwise, we need to be sensitive to `default` and
667667
// specialization.
668-
if !selcx.projection_mode().any() {
668+
if !selcx.projection_mode().is_any() {
669669
if let ProjectionTyCandidate::Impl(ref impl_data) = candidate {
670670
if let Some(node_item) = assoc_ty_def(selcx,
671671
impl_data.impl_def_id,
@@ -1116,7 +1116,7 @@ fn assoc_ty_def<'cx, 'tcx>(selcx: &SelectionContext<'cx, 'tcx>, impl_def_id: Def
11161116
{
11171117
let trait_def_id = selcx.tcx().impl_trait_ref(impl_def_id).unwrap().def_id;
11181118

1119-
if selcx.projection_mode().topmost() {
1119+
if selcx.projection_mode().is_topmost() {
11201120
let impl_node = specialization_graph::Node::Impl(impl_def_id);
11211121
for item in impl_node.items(selcx.tcx()) {
11221122
if let ty::TypeTraitItem(assoc_ty) = item {

src/librustc/middle/traits/specialize/mod.rs

Lines changed: 56 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use middle::def_id::DefId;
2525
use middle::infer::{self, InferCtxt, TypeOrigin};
2626
use middle::region;
2727
use middle::subst::{Subst, Substs};
28-
use middle::traits::{self, ProjectionMode};
28+
use middle::traits::ProjectionMode;
2929
use middle::ty;
3030
use syntax::codemap::DUMMY_SP;
3131

@@ -41,45 +41,43 @@ pub struct Overlap<'a, 'tcx: 'a> {
4141
/// Given a subst for the requested impl, translate it to a subst
4242
/// appropriate for the actual item definition (whether it be in that impl,
4343
/// a parent impl, or the trait).
44-
//
45-
// When we have selected one impl, but are actually using item definitions from
46-
// a parent impl providing a default, we need a way to translate between the
47-
// type parameters of the two impls. Here the `source_impl` is the one we've
48-
// selected, and `source_substs` is a substitution of its generics (and
49-
// possibly some relevant `FnSpace` variables as well). And `target_node` is
50-
// the impl/trait we're actually going to get the definition from. The resulting
51-
// substitution will map from `target_node`'s generics to `source_impl`'s
52-
// generics as instantiated by `source_subst`.
53-
//
54-
// For example, consider the following scenario:
55-
//
56-
// ```rust
57-
// trait Foo { ... }
58-
// impl<T, U> Foo for (T, U) { ... } // target impl
59-
// impl<V> Foo for (V, V) { ... } // source impl
60-
// ```
61-
//
62-
// Suppose we have selected "source impl" with `V` instantiated with `u32`.
63-
// This function will produce a substitution with `T` and `U` both mapping to `u32`.
64-
//
65-
// Where clauses add some trickiness here, because they can be used to "define"
66-
// an argument indirectly:
67-
//
68-
// ```rust
69-
// impl<'a, I, T: 'a> Iterator for Cloned<I>
70-
// where I: Iterator<Item=&'a T>, T: Clone
71-
// ```
72-
//
73-
// In a case like this, the substitution for `T` is determined indirectly,
74-
// through associated type projection. We deal with such cases by using
75-
// *fulfillment* to relate the two impls, requiring that all projections are
76-
// resolved.
44+
/// When we have selected one impl, but are actually using item definitions from
45+
/// a parent impl providing a default, we need a way to translate between the
46+
/// type parameters of the two impls. Here the `source_impl` is the one we've
47+
/// selected, and `source_substs` is a substitution of its generics (and
48+
/// possibly some relevant `FnSpace` variables as well). And `target_node` is
49+
/// the impl/trait we're actually going to get the definition from. The resulting
50+
/// substitution will map from `target_node`'s generics to `source_impl`'s
51+
/// generics as instantiated by `source_subst`.
52+
///
53+
/// For example, consider the following scenario:
54+
///
55+
/// ```rust
56+
/// trait Foo { ... }
57+
/// impl<T, U> Foo for (T, U) { ... } // target impl
58+
/// impl<V> Foo for (V, V) { ... } // source impl
59+
/// ```
60+
///
61+
/// Suppose we have selected "source impl" with `V` instantiated with `u32`.
62+
/// This function will produce a substitution with `T` and `U` both mapping to `u32`.
63+
///
64+
/// Where clauses add some trickiness here, because they can be used to "define"
65+
/// an argument indirectly:
66+
///
67+
/// ```rust
68+
/// impl<'a, I, T: 'a> Iterator for Cloned<I>
69+
/// where I: Iterator<Item=&'a T>, T: Clone
70+
/// ```
71+
///
72+
/// In a case like this, the substitution for `T` is determined indirectly,
73+
/// through associated type projection. We deal with such cases by using
74+
/// *fulfillment* to relate the two impls, requiring that all projections are
75+
/// resolved.
7776
pub fn translate_substs<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
7877
source_impl: DefId,
7978
source_substs: Substs<'tcx>,
8079
target_node: specialization_graph::Node)
81-
-> Substs<'tcx>
82-
{
80+
-> Substs<'tcx> {
8381
let source_trait_ref = infcx.tcx
8482
.impl_trait_ref(source_impl)
8583
.unwrap()
@@ -116,29 +114,16 @@ pub fn translate_substs<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
116114
target_substs.with_method_from_subst(&source_substs)
117115
}
118116

119-
120-
fn skolemizing_subst_for_impl<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
121-
impl_def_id: DefId)
122-
-> Substs<'tcx>
123-
{
124-
let impl_generics = infcx.tcx.lookup_item_type(impl_def_id).generics;
125-
126-
let types = impl_generics.types.map(|def| infcx.tcx.mk_param_from_def(def));
127-
128-
// TODO: figure out what we actually want here
129-
let regions = impl_generics.regions.map(|_| ty::Region::ReStatic);
130-
// |d| infcx.next_region_var(infer::RegionVariableOrigin::EarlyBoundRegion(span, d.name)));
131-
132-
Substs::new(types, regions)
133-
}
134-
135117
/// Is impl1 a specialization of impl2?
136118
///
137119
/// Specialization is determined by the sets of types to which the impls apply;
138120
/// impl1 specializes impl2 if it applies to a subset of the types impl2 applies
139121
/// to.
140122
pub fn specializes(tcx: &ty::ctxt, impl1_def_id: DefId, impl2_def_id: DefId) -> bool {
141-
if !tcx.sess.features.borrow().specialization {
123+
// The feature gate should prevent introducing new specializations, but not
124+
// taking advantage of upstream ones.
125+
if !tcx.sess.features.borrow().specialization &&
126+
(impl1_def_id.is_local() || impl2_def_id.is_local()) {
142127
return false;
143128
}
144129

@@ -156,33 +141,24 @@ pub fn specializes(tcx: &ty::ctxt, impl1_def_id: DefId, impl2_def_id: DefId) ->
156141

157142
// Currently we do not allow e.g. a negative impl to specialize a positive one
158143
if tcx.trait_impl_polarity(impl1_def_id) != tcx.trait_impl_polarity(impl2_def_id) {
159-
return false
144+
return false;
160145
}
161146

162147
let mut infcx = infer::normalizing_infer_ctxt(tcx, &tcx.tables, ProjectionMode::Topmost);
163148

164-
// Skiolemize impl1: we want to prove that "for all types matched by impl1,
165-
// those types are also matched by impl2".
166-
let impl1_substs = skolemizing_subst_for_impl(&infcx, impl1_def_id);
167-
let (impl1_trait_ref, impl1_obligations) = {
168-
let selcx = &mut SelectionContext::new(&infcx);
169-
impl_trait_ref_and_oblig(selcx, impl1_def_id, &impl1_substs)
170-
};
149+
// create a parameter environment corresponding to a (skolemized) instantiation of impl1
150+
let scheme = tcx.lookup_item_type(impl1_def_id);
151+
let predicates = tcx.lookup_predicates(impl1_def_id);
152+
let penv = tcx.construct_parameter_environment(DUMMY_SP,
153+
&scheme.generics,
154+
&predicates,
155+
region::DUMMY_CODE_EXTENT);
156+
let impl1_trait_ref = tcx.impl_trait_ref(impl1_def_id)
157+
.unwrap()
158+
.subst(tcx, &penv.free_substs);
171159

172-
// Add impl1's obligations as assumptions to the environment.
173-
let impl1_predicates: Vec<_> = impl1_obligations.iter()
174-
.cloned()
175-
.map(|oblig| oblig.predicate)
176-
.collect();
177-
infcx.parameter_environment = ty::ParameterEnvironment {
178-
tcx: tcx,
179-
free_substs: impl1_substs,
180-
implicit_region_bound: ty::ReEmpty, // TODO: is this OK?
181-
caller_bounds: impl1_predicates,
182-
selection_cache: traits::SelectionCache::new(),
183-
evaluation_cache: traits::EvaluationCache::new(),
184-
free_id_outlive: region::DUMMY_CODE_EXTENT, // TODO: is this OK?
185-
};
160+
// Install the parameter environment, which means we take the predicates of impl1 as assumptions:
161+
infcx.parameter_environment = penv;
186162

187163
// Attempt to prove that impl2 applies, given all of the above.
188164
fulfill_implication(&infcx, impl1_trait_ref, impl2_def_id).is_ok()
@@ -196,9 +172,8 @@ pub fn specializes(tcx: &ty::ctxt, impl1_def_id: DefId, impl2_def_id: DefId) ->
196172
fn fulfill_implication<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
197173
source_trait_ref: ty::TraitRef<'tcx>,
198174
target_impl: DefId)
199-
-> Result<Substs<'tcx>, ()>
200-
{
201-
infcx.probe(|_| {
175+
-> Result<Substs<'tcx>, ()> {
176+
infcx.commit_if_ok(|_| {
202177
let selcx = &mut SelectionContext::new(&infcx);
203178
let target_substs = fresh_type_vars_for_impl(&infcx, DUMMY_SP, target_impl);
204179
let (target_trait_ref, obligations) = impl_trait_ref_and_oblig(selcx,
@@ -227,23 +202,20 @@ fn fulfill_implication<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
227202

228203
if let Err(errors) = infer::drain_fulfillment_cx(&infcx, &mut fulfill_cx, &()) {
229204
// no dice!
230-
debug!("fulfill_implication: for impls on {:?} and {:?}, could not fulfill: {:?} \
231-
given {:?}",
205+
debug!("fulfill_implication: for impls on {:?} and {:?}, could not fulfill: {:?} given \
206+
{:?}",
232207
source_trait_ref,
233208
target_trait_ref,
234209
errors,
235210
infcx.parameter_environment.caller_bounds);
236211
Err(())
237212
} else {
238-
debug!("fulfill_implication: an impl for {:?} specializes {:?} (`where` clauses \
239-
elided)",
213+
debug!("fulfill_implication: an impl for {:?} specializes {:?} (`where` clauses elided)",
240214
source_trait_ref,
241215
target_trait_ref);
242216

243217
// Now resolve the *substitution* we built for the target earlier, replacing
244218
// the inference variables inside with whatever we got from fulfillment.
245-
246-
// TODO: should this use `fully_resolve` instead?
247219
Ok(infcx.resolve_type_vars_if_possible(&target_substs))
248220
}
249221
})

src/librustc/middle/traits/specialize/specialization_graph.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -65,14 +65,15 @@ impl Graph {
6565
let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
6666
let trait_def_id = trait_ref.def_id;
6767

68-
debug!("inserting TraitRef {:?} into specialization graph", trait_ref);
68+
debug!("insert({:?}): inserting TraitRef {:?} into specialization graph",
69+
impl_def_id, trait_ref);
6970

7071
// if the reference itself contains an earlier error (e.g., due to a
7172
// resolution failure), then we just insert the impl at the top level of
7273
// the graph and claim that there's no overlap (in order to supress
7374
// bogus errors).
7475
if trait_ref.references_error() {
75-
debug!("Inserting dummy node for erroneous TraitRef {:?}, \
76+
debug!("insert: inserting dummy node for erroneous TraitRef {:?}, \
7677
impl_def_id={:?}, trait_def_id={:?}",
7778
trait_ref, impl_def_id, trait_def_id);
7879

@@ -101,15 +102,15 @@ impl Graph {
101102
let ge = specializes(tcx, possible_sibling, impl_def_id);
102103

103104
if le && !ge {
104-
let parent_trait_ref = tcx.impl_trait_ref(possible_sibling).unwrap();
105-
debug!("descending as child of TraitRef {:?}", parent_trait_ref);
105+
debug!("descending as child of TraitRef {:?}",
106+
tcx.impl_trait_ref(possible_sibling).unwrap());
106107

107108
// the impl specializes possible_sibling
108109
parent = possible_sibling;
109110
continue 'descend;
110111
} else if ge && !le {
111-
let child_trait_ref = tcx.impl_trait_ref(possible_sibling).unwrap();
112-
debug!("placing as parent of TraitRef {:?}", child_trait_ref);
112+
debug!("placing as parent of TraitRef {:?}",
113+
tcx.impl_trait_ref(possible_sibling).unwrap());
113114

114115
// possible_sibling specializes the impl
115116
*slot = impl_def_id;
@@ -158,10 +159,10 @@ impl Graph {
158159
}
159160
}
160161

161-
#[derive(Debug, Copy, Clone)]
162162
/// A node in the specialization graph is either an impl or a trait
163163
/// definition; either can serve as a source of item definitions.
164164
/// There is always exactly one trait definition node: the root.
165+
#[derive(Debug, Copy, Clone)]
165166
pub enum Node {
166167
Impl(DefId),
167168
Trait(DefId),
@@ -316,7 +317,7 @@ impl<'a, 'tcx> Iterator for ConstDefs<'a, 'tcx> {
316317
}
317318

318319
impl<'a, 'tcx> Ancestors<'a, 'tcx> {
319-
/// Seach the items from the given ancestors, returning each type definition
320+
/// Search the items from the given ancestors, returning each type definition
320321
/// with the given name.
321322
pub fn type_defs(self, tcx: &'a ty::ctxt<'tcx>, name: Name) -> TypeDefs<'a, 'tcx> {
322323
let iter = self.flat_map(move |node| {
@@ -337,7 +338,7 @@ impl<'a, 'tcx> Ancestors<'a, 'tcx> {
337338
TypeDefs { iter: Box::new(iter) }
338339
}
339340

340-
/// Seach the items from the given ancestors, returning each fn definition
341+
/// Search the items from the given ancestors, returning each fn definition
341342
/// with the given name.
342343
pub fn fn_defs(self, tcx: &'a ty::ctxt<'tcx>, name: Name) -> FnDefs<'a, 'tcx> {
343344
let iter = self.flat_map(move |node| {
@@ -358,7 +359,7 @@ impl<'a, 'tcx> Ancestors<'a, 'tcx> {
358359
FnDefs { iter: Box::new(iter) }
359360
}
360361

361-
/// Seach the items from the given ancestors, returning each const
362+
/// Search the items from the given ancestors, returning each const
362363
/// definition with the given name.
363364
pub fn const_defs(self, tcx: &'a ty::ctxt<'tcx>, name: Name) -> ConstDefs<'a, 'tcx> {
364365
let iter = self.flat_map(move |node| {

src/librustc_typeck/check/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -870,8 +870,8 @@ fn report_forbidden_specialization(tcx: &ty::ctxt,
870870
{
871871
let mut err = struct_span_err!(
872872
tcx.sess, impl_item.span, E0520,
873-
"item `{}` is provided by an implementation that specializes \
874-
another, but the item in the parent implementations is not \
873+
"item `{}` is provided by an `impl` that specializes \
874+
another, but the item in the parent `impl` is not \
875875
marked `default` and so it cannot be specialized.",
876876
impl_item.name);
877877

src/test/compile-fail/specialization-default-projection.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,22 @@ impl Foo for u8 {
2525
}
2626

2727
fn generic<T>() -> <T as Foo>::Assoc {
28-
() //~ ERROR
28+
// `T` could be some downstream crate type that specializes (or,
29+
// for that matter, `u8`).
30+
31+
() //~ ERROR E0308
32+
}
33+
34+
fn monomorphic() -> () {
35+
// Even though we know that `()` is not specialized in a
36+
// downstream crate, typeck refuses to project here.
37+
38+
generic::<()>() //~ ERROR E0308
2939
}
3040

3141
fn main() {
42+
// No error here, we CAN project from `u8`, as there is no `default`
43+
// in that impl.
3244
let s: String = generic::<u8>();
33-
println!("{}", s); // bad news
45+
println!("{}", s); // bad news if this all compiles
3446
}

src/test/compile-fail/specialization-default-types.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ trait Example {
2222
impl<T> Example for T {
2323
default type Output = Box<T>;
2424
default fn generate(self) -> Self::Output {
25-
Box::new(self) //~ ERROR
25+
Box::new(self) //~ ERROR E0308
2626
}
2727
}
2828

@@ -32,7 +32,7 @@ impl Example for bool {
3232
}
3333

3434
fn trouble<T>(t: T) -> Box<T> {
35-
Example::generate(t) //~ ERROR
35+
Example::generate(t) //~ ERROR E0308
3636
}
3737

3838
fn weaponize() -> bool {

src/test/compile-fail/specialization-feature-gate-default.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
// Check that specialization must be ungated to use the `default` keyword
12+
1113
trait Foo {
1214
fn foo(&self);
1315
}
1416

1517
impl<T> Foo for T {
16-
default fn foo(&self) {} //~ ERROR
18+
default fn foo(&self) {} //~ ERROR specialization is unstable
1719
}
1820

1921
fn main() {}

0 commit comments

Comments
 (0)