1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use CrateCtxt;
use astconv::AstConv;
use check::{self, FnCtxt};
use middle::ty::{self, Ty};
use middle::def;
use metadata::{csearch, cstore, decoder};
use util::ppaux::UserString;
use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::print::pprust;
use std::cell;
use std::cmp::Ordering;
use super::{MethodError, CandidateSource, impl_method, trait_method};
pub fn report_error<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
rcvr_ty: Ty<'tcx>,
method_name: ast::Name,
rcvr_expr: Option<&ast::Expr>,
error: MethodError)
{
if ty::type_is_error(rcvr_ty) {
return
}
match error {
MethodError::NoMatch(static_sources, out_of_scope_traits) => {
let cx = fcx.tcx();
let method_ustring = method_name.user_string(cx);
fcx.type_error_message(
span,
|actual| {
format!("type `{}` does not implement any \
method in scope named `{}`",
actual,
method_ustring)
},
rcvr_ty,
None);
if let (&ty::ty_struct(did, _), Some(_)) = (&rcvr_ty.sty, rcvr_expr) {
let fields = ty::lookup_struct_fields(cx, did);
if fields.iter().any(|f| f.name == method_name) {
cx.sess.span_note(span,
&format!("use `(s.{0})(...)` if you meant to call the \
function stored in the `{0}` field", method_ustring));
}
}
if !static_sources.is_empty() {
fcx.tcx().sess.fileline_note(
span,
"found defined static methods, maybe a `self` is missing?");
report_candidates(fcx, span, method_name, static_sources);
}
suggest_traits_to_import(fcx, span, rcvr_ty, method_name,
rcvr_expr, out_of_scope_traits)
}
MethodError::Ambiguity(sources) => {
span_err!(fcx.sess(), span, E0034,
"multiple applicable methods in scope");
report_candidates(fcx, span, method_name, sources);
}
MethodError::ClosureAmbiguity(trait_def_id) => {
let msg = format!("the `{}` method from the `{}` trait cannot be explicitly \
invoked on this closure as we have not yet inferred what \
kind of closure it is",
method_name.user_string(fcx.tcx()),
ty::item_path_str(fcx.tcx(), trait_def_id));
let msg = if let Some(callee) = rcvr_expr {
format!("{}; use overloaded call notation instead (e.g., `{}()`)",
msg, pprust::expr_to_string(callee))
} else {
msg
};
fcx.sess().span_err(span, &msg);
}
}
fn report_candidates(fcx: &FnCtxt,
span: Span,
method_name: ast::Name,
mut sources: Vec<CandidateSource>) {
sources.sort();
sources.dedup();
for (idx, source) in sources.iter().enumerate() {
match *source {
CandidateSource::ImplSource(impl_did) => {
let method = impl_method(fcx.tcx(), impl_did, method_name).unwrap();
let impl_span = fcx.tcx().map.def_id_span(impl_did, span);
let method_span = fcx.tcx().map.def_id_span(method.def_id, impl_span);
let impl_ty = check::impl_self_ty(fcx, span, impl_did).ty;
let insertion = match ty::impl_trait_ref(fcx.tcx(), impl_did) {
None => format!(""),
Some(trait_ref) => format!(" of the trait `{}`",
ty::item_path_str(fcx.tcx(),
trait_ref.def_id)),
};
span_note!(fcx.sess(), method_span,
"candidate #{} is defined in an impl{} for the type `{}`",
idx + 1,
insertion,
impl_ty.user_string(fcx.tcx()));
}
CandidateSource::TraitSource(trait_did) => {
let (_, method) = trait_method(fcx.tcx(), trait_did, method_name).unwrap();
let method_span = fcx.tcx().map.def_id_span(method.def_id, span);
span_note!(fcx.sess(), method_span,
"candidate #{} is defined in the trait `{}`",
idx + 1,
ty::item_path_str(fcx.tcx(), trait_did));
}
}
}
}
}
pub type AllTraitsVec = Vec<TraitInfo>;
fn suggest_traits_to_import<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
rcvr_ty: Ty<'tcx>,
method_name: ast::Name,
rcvr_expr: Option<&ast::Expr>,
valid_out_of_scope_traits: Vec<ast::DefId>)
{
let tcx = fcx.tcx();
let method_ustring = method_name.user_string(tcx);
if !valid_out_of_scope_traits.is_empty() {
let mut candidates = valid_out_of_scope_traits;
candidates.sort();
candidates.dedup();
let msg = format!(
"methods from traits can only be called if the trait is in scope; \
the following {traits_are} implemented but not in scope, \
perhaps add a `use` for {one_of_them}:",
traits_are = if candidates.len() == 1 {"trait is"} else {"traits are"},
one_of_them = if candidates.len() == 1 {"it"} else {"one of them"});
fcx.sess().fileline_help(span, &msg[..]);
for (i, trait_did) in candidates.iter().enumerate() {
fcx.sess().fileline_help(span,
&*format!("candidate #{}: use `{}`",
i + 1,
ty::item_path_str(fcx.tcx(), *trait_did)))
}
return
}
let type_is_local = type_derefs_to_local(fcx, span, rcvr_ty, rcvr_expr);
let mut candidates = all_traits(fcx.ccx)
.filter(|info| {
(type_is_local || ast_util::is_local(info.def_id))
&& trait_method(tcx, info.def_id, method_name).is_some()
})
.collect::<Vec<_>>();
if !candidates.is_empty() {
candidates.sort_by(|a, b| a.cmp(b).reverse());
candidates.dedup();
let msg = format!(
"methods from traits can only be called if the trait is implemented and in scope; \
the following {traits_define} a method `{name}`, \
perhaps you need to implement {one_of_them}:",
traits_define = if candidates.len() == 1 {"trait defines"} else {"traits define"},
one_of_them = if candidates.len() == 1 {"it"} else {"one of them"},
name = method_ustring);
fcx.sess().fileline_help(span, &msg[..]);
for (i, trait_info) in candidates.iter().enumerate() {
fcx.sess().fileline_help(span,
&*format!("candidate #{}: `{}`",
i + 1,
ty::item_path_str(fcx.tcx(), trait_info.def_id)))
}
}
}
fn type_derefs_to_local<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
rcvr_ty: Ty<'tcx>,
rcvr_expr: Option<&ast::Expr>) -> bool {
fn is_local(ty: Ty) -> bool {
match ty.sty {
ty::ty_enum(did, _) | ty::ty_struct(did, _) => ast_util::is_local(did),
ty::ty_trait(ref tr) => ast_util::is_local(tr.principal_def_id()),
ty::ty_param(_) => true,
_ => false
}
}
if rcvr_expr.is_none() {
return is_local(fcx.resolve_type_vars_if_possible(rcvr_ty));
}
check::autoderef(fcx, span, rcvr_ty, None,
check::UnresolvedTypeAction::Ignore, check::NoPreference,
|ty, _| {
if is_local(ty) {
Some(())
} else {
None
}
}).2.is_some()
}
#[derive(Copy, Clone)]
pub struct TraitInfo {
pub def_id: ast::DefId,
}
impl TraitInfo {
fn new(def_id: ast::DefId) -> TraitInfo {
TraitInfo {
def_id: def_id,
}
}
}
impl PartialEq for TraitInfo {
fn eq(&self, other: &TraitInfo) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for TraitInfo {}
impl PartialOrd for TraitInfo {
fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> { Some(self.cmp(other)) }
}
impl Ord for TraitInfo {
fn cmp(&self, other: &TraitInfo) -> Ordering {
let lhs = (other.def_id.krate, other.def_id.node);
let rhs = (self.def_id.krate, self.def_id.node);
lhs.cmp(&rhs)
}
}
pub fn all_traits<'a>(ccx: &'a CrateCtxt) -> AllTraits<'a> {
if ccx.all_traits.borrow().is_none() {
use syntax::visit;
let mut traits = vec![];
struct Visitor<'a> {
traits: &'a mut AllTraitsVec,
}
impl<'v, 'a> visit::Visitor<'v> for Visitor<'a> {
fn visit_item(&mut self, i: &'v ast::Item) {
match i.node {
ast::ItemTrait(..) => {
self.traits.push(TraitInfo::new(ast_util::local_def(i.id)));
}
_ => {}
}
visit::walk_item(self, i)
}
}
visit::walk_crate(&mut Visitor {
traits: &mut traits
}, ccx.tcx.map.krate());
fn handle_external_def(traits: &mut AllTraitsVec,
ccx: &CrateCtxt,
cstore: &cstore::CStore,
dl: decoder::DefLike) {
match dl {
decoder::DlDef(def::DefTrait(did)) => {
traits.push(TraitInfo::new(did));
}
decoder::DlDef(def::DefMod(did)) => {
csearch::each_child_of_item(cstore, did, |dl, _, _| {
handle_external_def(traits, ccx, cstore, dl)
})
}
_ => {}
}
}
let cstore = &ccx.tcx.sess.cstore;
cstore.iter_crate_data(|cnum, _| {
csearch::each_top_level_item_of_crate(cstore, cnum, |dl, _, _| {
handle_external_def(&mut traits, ccx, cstore, dl)
})
});
*ccx.all_traits.borrow_mut() = Some(traits);
}
let borrow = ccx.all_traits.borrow();
assert!(borrow.is_some());
AllTraits {
borrow: borrow,
idx: 0
}
}
pub struct AllTraits<'a> {
borrow: cell::Ref<'a, Option<AllTraitsVec>>,
idx: usize
}
impl<'a> Iterator for AllTraits<'a> {
type Item = TraitInfo;
fn next(&mut self) -> Option<TraitInfo> {
let AllTraits { ref borrow, ref mut idx } = *self;
borrow.as_ref().unwrap().get(*idx).map(|info| {
*idx += 1;
*info
})
}
}