Skip to content

Commit 66fcc56

Browse files
committed
Auto merge of #49714 - nikomatsakis:issue-49631, r=eddyb
mem-categorization, coherence fix make mem-categorization use adjusted type for patterns: Fixes #49631 do not propagate `Err` when determing causal info: Fixes #48728 r? @eddyb
2 parents 08ad376 + 939bb32 commit 66fcc56

File tree

6 files changed

+158
-23
lines changed

6 files changed

+158
-23
lines changed

src/librustc/middle/mem_categorization.rs

+33-4
Original file line numberDiff line numberDiff line change
@@ -503,8 +503,37 @@ impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
503503
self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
504504
}
505505

506+
/// Returns the type of value that this pattern matches against.
507+
/// Some non-obvious cases:
508+
///
509+
/// - a `ref x` binding matches against a value of type `T` and gives
510+
/// `x` the type `&T`; we return `T`.
511+
/// - a pattern with implicit derefs (thanks to default binding
512+
/// modes #42640) may look like `Some(x)` but in fact have
513+
/// implicit deref patterns attached (e.g., it is really
514+
/// `&Some(x)`). In that case, we return the "outermost" type
515+
/// (e.g., `&Option<T>).
506516
fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
517+
// Check for implicit `&` types wrapping the pattern; note
518+
// that these are never attached to binding patterns, so
519+
// actually this is somewhat "disjoint" from the code below
520+
// that aims to account for `ref x`.
521+
if let Some(vec) = self.tables.pat_adjustments().get(pat.hir_id) {
522+
if let Some(first_ty) = vec.first() {
523+
debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
524+
return Ok(first_ty);
525+
}
526+
}
527+
528+
self.pat_ty_unadjusted(pat)
529+
}
530+
531+
532+
/// Like `pat_ty`, but ignores implicit `&` patterns.
533+
fn pat_ty_unadjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
507534
let base_ty = self.node_ty(pat.hir_id)?;
535+
debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty);
536+
508537
// This code detects whether we are looking at a `ref x`,
509538
// and if so, figures out what the type *being borrowed* is.
510539
let ret_ty = match pat.node {
@@ -531,8 +560,8 @@ impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
531560
}
532561
_ => base_ty,
533562
};
534-
debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
535-
pat, base_ty, ret_ty);
563+
debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty);
564+
536565
Ok(ret_ty)
537566
}
538567

@@ -1246,7 +1275,7 @@ impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
12461275
self.tcx.adt_def(enum_def).variant_with_id(def_id).fields.len())
12471276
}
12481277
Def::StructCtor(_, CtorKind::Fn) => {
1249-
match self.pat_ty(&pat)?.sty {
1278+
match self.pat_ty_unadjusted(&pat)?.sty {
12501279
ty::TyAdt(adt_def, _) => {
12511280
(cmt, adt_def.non_enum_variant().fields.len())
12521281
}
@@ -1297,7 +1326,7 @@ impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
12971326

12981327
PatKind::Tuple(ref subpats, ddpos) => {
12991328
// (p1, ..., pN)
1300-
let expected_len = match self.pat_ty(&pat)?.sty {
1329+
let expected_len = match self.pat_ty_unadjusted(&pat)?.sty {
13011330
ty::TyTuple(ref tys) => tys.len(),
13021331
ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
13031332
};

src/librustc/traits/select.rs

+43-19
Original file line numberDiff line numberDiff line change
@@ -961,11 +961,21 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
961961
if self.can_use_global_caches(param_env) {
962962
let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
963963
if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
964+
debug!(
965+
"insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
966+
trait_ref,
967+
result,
968+
);
964969
cache.insert(trait_ref, WithDepNode::new(dep_node, result));
965970
return;
966971
}
967972
}
968973

974+
debug!(
975+
"insert_evaluation_cache(trait_ref={:?}, candidate={:?})",
976+
trait_ref,
977+
result,
978+
);
969979
self.infcx.evaluation_cache.hashmap
970980
.borrow_mut()
971981
.insert(trait_ref, WithDepNode::new(dep_node, result));
@@ -1069,25 +1079,29 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
10691079
if self.intercrate_ambiguity_causes.is_some() {
10701080
debug!("evaluate_stack: intercrate_ambiguity_causes is some");
10711081
// Heuristics: show the diagnostics when there are no candidates in crate.
1072-
let candidate_set = self.assemble_candidates(stack)?;
1073-
if !candidate_set.ambiguous && candidate_set.vec.iter().all(|c| {
1074-
!self.evaluate_candidate(stack, &c).may_apply()
1075-
}) {
1076-
let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1077-
let self_ty = trait_ref.self_ty();
1078-
let trait_desc = trait_ref.to_string();
1079-
let self_desc = if self_ty.has_concrete_skeleton() {
1080-
Some(self_ty.to_string())
1081-
} else {
1082-
None
1083-
};
1084-
let cause = if let Conflict::Upstream = conflict {
1085-
IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1086-
} else {
1087-
IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1088-
};
1089-
debug!("evaluate_stack: pushing cause = {:?}", cause);
1090-
self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1082+
if let Ok(candidate_set) = self.assemble_candidates(stack) {
1083+
if !candidate_set.ambiguous && candidate_set.vec.iter().all(|c| {
1084+
!self.evaluate_candidate(stack, &c).may_apply()
1085+
}) {
1086+
let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1087+
let self_ty = trait_ref.self_ty();
1088+
let trait_desc = trait_ref.to_string();
1089+
let self_desc = if self_ty.has_concrete_skeleton() {
1090+
Some(self_ty.to_string())
1091+
} else {
1092+
None
1093+
};
1094+
let cause = if let Conflict::Upstream = conflict {
1095+
IntercrateAmbiguityCause::UpstreamCrateUpdate {
1096+
trait_desc,
1097+
self_desc,
1098+
}
1099+
} else {
1100+
IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1101+
};
1102+
debug!("evaluate_stack: pushing cause = {:?}", cause);
1103+
self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1104+
}
10911105
}
10921106
}
10931107
return Ok(None);
@@ -1285,12 +1299,22 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
12851299
let mut cache = tcx.selection_cache.hashmap.borrow_mut();
12861300
if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
12871301
if let Some(candidate) = tcx.lift_to_global(&candidate) {
1302+
debug!(
1303+
"insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1304+
trait_ref,
1305+
candidate,
1306+
);
12881307
cache.insert(trait_ref, WithDepNode::new(dep_node, candidate));
12891308
return;
12901309
}
12911310
}
12921311
}
12931312

1313+
debug!(
1314+
"insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1315+
trait_ref,
1316+
candidate,
1317+
);
12941318
self.infcx.selection_cache.hashmap
12951319
.borrow_mut()
12961320
.insert(trait_ref, WithDepNode::new(dep_node, candidate));

src/test/ui/issue-48728.rs

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// Regression test for #48728, an ICE that occurred computing
12+
// coherence "help" information.
13+
14+
#[derive(Clone)] //~ ERROR conflicting implementations of trait `std::clone::Clone`
15+
struct Node<T: ?Sized>(Box<T>);
16+
17+
impl<T: Clone + ?Sized> Clone for Node<[T]> {
18+
fn clone(&self) -> Self {
19+
Node(Box::clone(&self.0))
20+
}
21+
}
22+
23+
fn main() {}

src/test/ui/issue-48728.stderr

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
error[E0119]: conflicting implementations of trait `std::clone::Clone` for type `Node<[_]>`:
2+
--> $DIR/issue-48728.rs:14:10
3+
|
4+
LL | #[derive(Clone)] //~ ERROR conflicting implementations of trait `std::clone::Clone`
5+
| ^^^^^ conflicting implementation for `Node<[_]>`
6+
...
7+
LL | impl<T: Clone + ?Sized> Clone for Node<[T]> {
8+
| ------------------------------------------- first implementation here
9+
10+
error: aborting due to previous error
11+
12+
For more information about this error, try `rustc --explain E0119`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
12+
pub struct Foo {
13+
}
14+
15+
impl Foo {
16+
fn get(&self) -> Option<&Result<String, String>> {
17+
None
18+
}
19+
20+
fn mutate(&mut self) { }
21+
}
22+
23+
fn main() {
24+
let mut foo = Foo { };
25+
26+
// foo.get() returns type Option<&Result<String, String>>, so
27+
// using `string` keeps borrow of `foo` alive. Hence calling
28+
// `foo.mutate()` should be an error.
29+
while let Some(Ok(string)) = foo.get() {
30+
foo.mutate();
31+
//~^ ERROR cannot borrow `foo` as mutable
32+
println!("foo={:?}", *string);
33+
}
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
error[E0502]: cannot borrow `foo` as mutable because it is also borrowed as immutable
2+
--> $DIR/borrowck-issue-49631.rs:30:9
3+
|
4+
LL | while let Some(Ok(string)) = foo.get() {
5+
| --- - immutable borrow ends here
6+
| |
7+
| immutable borrow occurs here
8+
LL | foo.mutate();
9+
| ^^^ mutable borrow occurs here
10+
11+
error: aborting due to previous error
12+
13+
For more information about this error, try `rustc --explain E0502`.

0 commit comments

Comments
 (0)