Skip to content

Commit c11fe55

Browse files
Create check_ref method to allow to check coercion with & types
1 parent b2d0ec0 commit c11fe55

File tree

7 files changed

+114
-69
lines changed

7 files changed

+114
-69
lines changed

src/libcollections/lib.rs

-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828

2929
#![cfg_attr(test, allow(deprecated))] // rand
3030
#![cfg_attr(not(stage0), deny(warnings))]
31-
#![cfg_attr(not(stage0), feature(safe_suggestion))]
3231

3332
#![feature(alloc)]
3433
#![feature(allow_internal_unstable)]

src/libcollections/string.rs

-1
Original file line numberDiff line numberDiff line change
@@ -1231,7 +1231,6 @@ impl String {
12311231
/// assert_eq!(a.len(), 3);
12321232
/// ```
12331233
#[inline]
1234-
#[cfg_attr(not(stage0), safe_suggestion)]
12351234
#[stable(feature = "rust1", since = "1.0.0")]
12361235
pub fn len(&self) -> usize {
12371236
self.vec.len()

src/librustc/infer/error_reporting.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -549,7 +549,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
549549
{
550550
let expected_found = match values {
551551
None => None,
552-
Some(ref values) => match self.values_str(&values) {
552+
Some(values) => match self.values_str(&values) {
553553
Some((expected, found)) => Some((expected, found)),
554554
None => {
555555
// Derived error. Cancel the emitter.

src/librustc_typeck/check/demand.rs

+61-55
Original file line numberDiff line numberDiff line change
@@ -19,28 +19,10 @@ use syntax_pos::{self, Span};
1919
use rustc::hir;
2020
use rustc::ty::{self, ImplOrTraitItem};
2121

22-
use hir::def_id::DefId;
23-
2422
use std::rc::Rc;
2523

2624
use super::method::probe;
2725

28-
struct MethodInfo<'tcx> {
29-
ast: Option<ast::Attribute>,
30-
id: DefId,
31-
item: Rc<ImplOrTraitItem<'tcx>>,
32-
}
33-
34-
impl<'tcx> MethodInfo<'tcx> {
35-
fn new(ast: Option<ast::Attribute>, id: DefId, item: Rc<ImplOrTraitItem<'tcx>>) -> MethodInfo {
36-
MethodInfo {
37-
ast: ast,
38-
id: id,
39-
item: item,
40-
}
41-
}
42-
}
43-
4426
impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
4527
// Requires that the two types unify, and prints an error message if
4628
// they don't.
@@ -79,41 +61,70 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
7961
}
8062
}
8163

64+
fn check_ref(&self, expr: &hir::Expr, checked_ty: Ty<'tcx>,
65+
expected: Ty<'tcx>) -> Option<String> {
66+
match (&checked_ty.sty, &expected.sty) {
67+
(&ty::TyRef(_, x_mutability), &ty::TyRef(_, y_mutability)) => {
68+
// check if there is a mutability difference
69+
if x_mutability.mutbl == hir::Mutability::MutImmutable &&
70+
x_mutability.mutbl != y_mutability.mutbl &&
71+
self.can_sub_types(&x_mutability.ty, y_mutability.ty).is_ok() {
72+
if let Ok(src) = self.tcx.sess.codemap().span_to_snippet(expr.span) {
73+
return Some(format!("try with `&mut {}`", &src.replace("&", "")));
74+
}
75+
}
76+
None
77+
}
78+
(_, &ty::TyRef(_, mutability)) => {
79+
// check if it can work when put into a ref
80+
let ref_ty = match mutability.mutbl {
81+
hir::Mutability::MutMutable => self.tcx.mk_mut_ref(
82+
self.tcx.mk_region(ty::ReStatic),
83+
checked_ty),
84+
hir::Mutability::MutImmutable => self.tcx.mk_imm_ref(
85+
self.tcx.mk_region(ty::ReStatic),
86+
checked_ty),
87+
};
88+
if self.try_coerce(expr, ref_ty, expected).is_ok() {
89+
if let Ok(src) = self.tcx.sess.codemap().span_to_snippet(expr.span) {
90+
return Some(format!("try with `{}{}`",
91+
match mutability.mutbl {
92+
hir::Mutability::MutMutable => "&mut ",
93+
hir::Mutability::MutImmutable => "&",
94+
},
95+
&src));
96+
}
97+
}
98+
None
99+
}
100+
_ => None,
101+
}
102+
}
103+
82104
// Checks that the type of `expr` can be coerced to `expected`.
83105
pub fn demand_coerce(&self, expr: &hir::Expr, checked_ty: Ty<'tcx>, expected: Ty<'tcx>) {
84106
let expected = self.resolve_type_vars_with_obligations(expected);
85107
if let Err(e) = self.try_coerce(expr, checked_ty, expected) {
86108
let cause = self.misc(expr.span);
87109
let expr_ty = self.resolve_type_vars_with_obligations(checked_ty);
88110
let mode = probe::Mode::MethodCall;
89-
let suggestions =
90-
if let Ok(methods) = self.probe_return(syntax_pos::DUMMY_SP, mode, expected,
91-
checked_ty, ast::DUMMY_NODE_ID) {
111+
let suggestions = if let Some(s) = self.check_ref(expr, checked_ty, expected) {
112+
Some(s)
113+
} else if let Ok(methods) = self.probe_return(syntax_pos::DUMMY_SP,
114+
mode,
115+
expected,
116+
checked_ty,
117+
ast::DUMMY_NODE_ID) {
92118
let suggestions: Vec<_> =
93119
methods.iter()
94-
.filter_map(|ref x| {
95-
if let Some(id) = self.get_impl_id(&x.item) {
96-
Some(MethodInfo::new(None, id, Rc::new(x.item.clone())))
97-
} else {
98-
None
99-
}})
120+
.map(|ref x| {
121+
Rc::new(x.item.clone())
122+
})
100123
.collect();
101124
if suggestions.len() > 0 {
102-
let safe_suggestions: Vec<_> =
103-
suggestions.iter()
104-
.map(|ref x| MethodInfo::new(
105-
self.find_attr(x.id, "safe_suggestion"),
106-
x.id,
107-
x.item.clone()))
108-
.filter(|ref x| x.ast.is_some())
109-
.collect();
110-
Some(if safe_suggestions.len() > 0 {
111-
self.get_best_match(&safe_suggestions)
112-
} else {
113-
format!("no safe suggestion found, here are functions which match your \
114-
needs but be careful:\n - {}",
115-
self.get_best_match(&suggestions))
116-
})
125+
Some(format!("here are some functions which \
126+
might fulfill your needs:\n - {}",
127+
self.get_best_match(&suggestions)))
117128
} else {
118129
None
119130
}
@@ -132,34 +143,29 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
132143
}
133144
}
134145

135-
fn get_best_match(&self, methods: &[MethodInfo<'tcx>]) -> String {
146+
fn get_best_match(&self, methods: &[Rc<ImplOrTraitItem<'tcx>>]) -> String {
136147
if methods.len() == 1 {
137-
return format!(" - {}", methods[0].item.name());
148+
return format!(" - {}", methods[0].name());
138149
}
139-
let no_argument_methods: Vec<&MethodInfo> =
150+
let no_argument_methods: Vec<&Rc<ImplOrTraitItem<'tcx>>> =
140151
methods.iter()
141-
.filter(|ref x| self.has_not_input_arg(&*x.item))
152+
.filter(|ref x| self.has_not_input_arg(&*x))
142153
.collect();
143154
if no_argument_methods.len() > 0 {
144155
no_argument_methods.iter()
145-
.map(|method| format!("{}", method.item.name()))
156+
.take(5)
157+
.map(|method| format!("{}", method.name()))
146158
.collect::<Vec<String>>()
147159
.join("\n - ")
148160
} else {
149161
methods.iter()
150-
.map(|method| format!("{}", method.item.name()))
162+
.take(5)
163+
.map(|method| format!("{}", method.name()))
151164
.collect::<Vec<String>>()
152165
.join("\n - ")
153166
}
154167
}
155168

156-
fn get_impl_id(&self, impl_: &ImplOrTraitItem<'tcx>) -> Option<DefId> {
157-
match *impl_ {
158-
ty::ImplOrTraitItem::MethodTraitItem(ref m) => Some((*m).def_id),
159-
_ => None,
160-
}
161-
}
162-
163169
fn has_not_input_arg(&self, method: &ImplOrTraitItem<'tcx>) -> bool {
164170
match *method {
165171
ImplOrTraitItem::MethodTraitItem(ref x) => {

src/librustc_typeck/check/method/probe.rs

+11-5
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
194194
// think cause spurious errors. Really though this part should
195195
// take place in the `self.probe` below.
196196
let steps = if mode == Mode::MethodCall {
197-
match self.create_steps(span, self_ty) {
197+
match self.create_steps(span, self_ty, &looking_for) {
198198
Some(steps) => steps,
199199
None => {
200200
return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
@@ -247,7 +247,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
247247

248248
fn create_steps(&self,
249249
span: Span,
250-
self_ty: Ty<'tcx>)
250+
self_ty: Ty<'tcx>,
251+
looking_for: &LookingFor<'tcx>)
251252
-> Option<Vec<CandidateStep<'tcx>>> {
252253
// FIXME: we don't need to create the entire steps in one pass
253254

@@ -262,7 +263,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
262263
})
263264
.collect();
264265

265-
let final_ty = autoderef.unambiguous_final_ty();
266+
let final_ty = match looking_for {
267+
&LookingFor::MethodName(_) => autoderef.unambiguous_final_ty(),
268+
&LookingFor::ReturnType(_) => self_ty,
269+
};
266270
match final_ty.sty {
267271
ty::TyArray(elem_ty, _) => {
268272
let dereferences = steps.len() - 1;
@@ -628,13 +632,15 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
628632
}
629633

630634
pub fn matches_return_type(&self, method: &ty::ImplOrTraitItem<'tcx>,
631-
expected: ty::Ty<'tcx>) -> bool {
635+
expected: ty::Ty<'tcx>) -> bool {
632636
match *method {
633637
ty::ImplOrTraitItem::MethodTraitItem(ref x) => {
634638
self.probe(|_| {
635639
let output = self.replace_late_bound_regions_with_fresh_var(
636640
self.span, infer::FnCall, &x.fty.sig.output());
637-
self.can_sub_types(output.0, expected).is_ok()
641+
let substs = self.fresh_substs_for_item(self.span, method.def_id());
642+
let output = output.0.subst(self.tcx, substs);
643+
self.can_sub_types(output, expected).is_ok()
638644
})
639645
}
640646
_ => false,

src/libsyntax/feature_gate.rs

-6
Original file line numberDiff line numberDiff line change
@@ -652,12 +652,6 @@ pub const BUILTIN_ATTRIBUTES: &'static [(&'static str, AttributeType, AttributeG
652652
"internal implementation detail",
653653
cfg_fn!(rustc_attrs))),
654654

655-
("safe_suggestion", Whitelisted, Gated(Stability::Unstable,
656-
"safe_suggestion",
657-
"the `#[safe_suggestion]` attribute \
658-
is an experimental feature",
659-
cfg_fn!(safe_suggestion))),
660-
661655
// FIXME: #14408 whitelist docs since rustdoc looks at them
662656
("doc", Whitelisted, Ungated),
663657

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Copyright 2016 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+
fn test(_x: &mut String) {}
12+
fn test2(_x: &mut i32) {}
13+
14+
fn main() {
15+
let x: usize = String::new();
16+
//^ ERROR E0308
17+
//| NOTE expected type `usize`
18+
//| NOTE found type `std::string::String`
19+
//| NOTE here are some functions which might fulfill your needs:
20+
let x: &str = String::new();
21+
//^ ERROR E0308
22+
//| NOTE expected type `&str`
23+
//| NOTE found type `std::string::String`
24+
//| NOTE try with `&String::new()`
25+
let y = String::new();
26+
test(&y);
27+
//^ ERROR E0308
28+
//| NOTE expected type `&mut std::string::String`
29+
//| NOTE found type `&std::string::String`
30+
//| NOTE try with `&mut y`
31+
test2(&y);
32+
//^ ERROR E0308
33+
//| NOTE expected type `&mut i32`
34+
//| NOTE found type `&std::string::String`
35+
//| NOTE try with `&mut y`
36+
let f;
37+
f = box f;
38+
//^ ERROR E0308
39+
//| NOTE expected type `_`
40+
//| NOTE found type `Box<_>`
41+
}

0 commit comments

Comments
 (0)