]>
Commit | Line | Data |
---|---|---|
f035d41b | 1 | use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion}; |
74b04a01 | 2 | use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext}; |
29967ef6 | 3 | use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind}; |
dfeec247 XL |
4 | use crate::path_names_to_string; |
5 | use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot}; | |
6 | use crate::{PathResult, PathSource, Segment}; | |
416331ca | 7 | |
3dfed10e XL |
8 | use rustc_ast::visit::FnKind; |
9 | use rustc_ast::{self as ast, Expr, ExprKind, Item, ItemKind, NodeId, Path, Ty, TyKind}; | |
29967ef6 | 10 | use rustc_ast_pretty::pprust::path_segment_to_string; |
dfeec247 | 11 | use rustc_data_structures::fx::FxHashSet; |
74b04a01 XL |
12 | use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder}; |
13 | use rustc_hir as hir; | |
dfeec247 | 14 | use rustc_hir::def::Namespace::{self, *}; |
29967ef6 | 15 | use rustc_hir::def::{self, CtorKind, CtorOf, DefKind}; |
3dfed10e | 16 | use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE}; |
dfeec247 | 17 | use rustc_hir::PrimTy; |
1b1a35ee | 18 | use rustc_session::parse::feature_err; |
dfeec247 | 19 | use rustc_span::hygiene::MacroKind; |
fc512014 | 20 | use rustc_span::lev_distance::find_best_match_for_name; |
3dfed10e | 21 | use rustc_span::symbol::{kw, sym, Ident, Symbol}; |
29967ef6 | 22 | use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP}; |
416331ca | 23 | |
3dfed10e | 24 | use tracing::debug; |
60c5eb7d | 25 | |
416331ca XL |
26 | type Res = def::Res<ast::NodeId>; |
27 | ||
28 | /// A field or associated item from self type suggested in case of resolution failure. | |
29 | enum AssocSuggestion { | |
30 | Field, | |
31 | MethodWithSelf, | |
29967ef6 XL |
32 | AssocFn, |
33 | AssocType, | |
34 | AssocConst, | |
35 | } | |
36 | ||
37 | impl AssocSuggestion { | |
38 | fn action(&self) -> &'static str { | |
39 | match self { | |
40 | AssocSuggestion::Field => "use the available field", | |
41 | AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path", | |
42 | AssocSuggestion::AssocFn => "call the associated function", | |
43 | AssocSuggestion::AssocConst => "use the associated `const`", | |
44 | AssocSuggestion::AssocType => "use the associated type", | |
45 | } | |
46 | } | |
416331ca XL |
47 | } |
48 | ||
74b04a01 XL |
49 | crate enum MissingLifetimeSpot<'tcx> { |
50 | Generics(&'tcx hir::Generics<'tcx>), | |
51 | HigherRanked { span: Span, span_type: ForLifetimeSpanType }, | |
3dfed10e | 52 | Static, |
74b04a01 XL |
53 | } |
54 | ||
55 | crate enum ForLifetimeSpanType { | |
56 | BoundEmpty, | |
57 | BoundTail, | |
58 | TypeEmpty, | |
59 | TypeTail, | |
60 | } | |
61 | ||
62 | impl ForLifetimeSpanType { | |
63 | crate fn descr(&self) -> &'static str { | |
64 | match self { | |
65 | Self::BoundEmpty | Self::BoundTail => "bound", | |
66 | Self::TypeEmpty | Self::TypeTail => "type", | |
67 | } | |
68 | } | |
69 | ||
70 | crate fn suggestion(&self, sugg: &str) -> String { | |
71 | match self { | |
72 | Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg), | |
73 | Self::BoundTail | Self::TypeTail => format!(", {}", sugg), | |
74 | } | |
75 | } | |
76 | } | |
77 | ||
78 | impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> { | |
79 | fn into(self) -> MissingLifetimeSpot<'tcx> { | |
80 | MissingLifetimeSpot::Generics(self) | |
81 | } | |
82 | } | |
83 | ||
416331ca XL |
84 | fn is_self_type(path: &[Segment], namespace: Namespace) -> bool { |
85 | namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper | |
86 | } | |
87 | ||
88 | fn is_self_value(path: &[Segment], namespace: Namespace) -> bool { | |
89 | namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower | |
90 | } | |
91 | ||
92 | /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant. | |
93 | fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) { | |
94 | let variant_path = &suggestion.path; | |
95 | let variant_path_string = path_names_to_string(variant_path); | |
96 | ||
97 | let path_len = suggestion.path.segments.len(); | |
98 | let enum_path = ast::Path { | |
99 | span: suggestion.path.span, | |
100 | segments: suggestion.path.segments[0..path_len - 1].to_vec(), | |
1b1a35ee | 101 | tokens: None, |
416331ca XL |
102 | }; |
103 | let enum_path_string = path_names_to_string(&enum_path); | |
104 | ||
105 | (variant_path_string, enum_path_string) | |
106 | } | |
107 | ||
1b1a35ee | 108 | impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> { |
3dfed10e XL |
109 | fn def_span(&self, def_id: DefId) -> Option<Span> { |
110 | match def_id.krate { | |
111 | LOCAL_CRATE => self.r.opt_span(def_id), | |
112 | _ => Some( | |
113 | self.r | |
114 | .session | |
115 | .source_map() | |
116 | .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)), | |
117 | ), | |
118 | } | |
119 | } | |
120 | ||
416331ca XL |
121 | /// Handles error reporting for `smart_resolve_path_fragment` function. |
122 | /// Creates base error and amends it with one short label and possibly some longer helps/notes. | |
123 | pub(crate) fn smart_resolve_report_errors( | |
124 | &mut self, | |
125 | path: &[Segment], | |
126 | span: Span, | |
127 | source: PathSource<'_>, | |
128 | res: Option<Res>, | |
129 | ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) { | |
130 | let ident_span = path.last().map_or(span, |ident| ident.ident.span); | |
131 | let ns = source.namespace(); | |
132 | let is_expected = &|res| source.is_expected(res); | |
f035d41b | 133 | let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _)); |
416331ca XL |
134 | |
135 | // Make the base error. | |
136 | let expected = source.descr_expected(); | |
137 | let path_str = Segment::names_to_string(path); | |
138 | let item_str = path.last().unwrap().ident; | |
e74abb32 | 139 | let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res { |
dfeec247 XL |
140 | ( |
141 | format!("expected {}, found {} `{}`", expected, res.descr(), path_str), | |
416331ca | 142 | format!("not a {}", expected), |
e74abb32 XL |
143 | span, |
144 | match res { | |
145 | Res::Def(DefKind::Fn, _) => { | |
146 | // Verify whether this is a fn call or an Fn used as a type. | |
dfeec247 XL |
147 | self.r |
148 | .session | |
149 | .source_map() | |
150 | .span_to_snippet(span) | |
151 | .map(|snippet| snippet.ends_with(')')) | |
152 | .unwrap_or(false) | |
e74abb32 | 153 | } |
ba9703b0 XL |
154 | Res::Def( |
155 | DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst, | |
156 | _, | |
157 | ) | |
dfeec247 XL |
158 | | Res::SelfCtor(_) |
159 | | Res::PrimTy(_) | |
160 | | Res::Local(_) => true, | |
e74abb32 | 161 | _ => false, |
dfeec247 XL |
162 | }, |
163 | ) | |
416331ca XL |
164 | } else { |
165 | let item_span = path.last().unwrap().ident.span; | |
166 | let (mod_prefix, mod_str) = if path.len() == 1 { | |
167 | (String::new(), "this scope".to_string()) | |
168 | } else if path.len() == 2 && path[0].ident.name == kw::PathRoot { | |
169 | (String::new(), "the crate root".to_string()) | |
170 | } else { | |
171 | let mod_path = &path[..path.len() - 1]; | |
dfeec247 XL |
172 | let mod_prefix = |
173 | match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) { | |
174 | PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(), | |
175 | _ => None, | |
176 | } | |
177 | .map_or(String::new(), |res| format!("{} ", res.descr())); | |
416331ca XL |
178 | (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path))) |
179 | }; | |
dfeec247 XL |
180 | ( |
181 | format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str), | |
f9f354fc XL |
182 | if path_str == "async" && expected.starts_with("struct") { |
183 | "`async` blocks are only allowed in the 2018 edition".to_string() | |
184 | } else { | |
185 | format!("not found in {}", mod_str) | |
186 | }, | |
e74abb32 | 187 | item_span, |
dfeec247 XL |
188 | false, |
189 | ) | |
416331ca XL |
190 | }; |
191 | ||
dfeec247 | 192 | let code = source.error_code(res.is_some()); |
416331ca XL |
193 | let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code); |
194 | ||
1b1a35ee XL |
195 | match (source, self.diagnostic_metadata.in_if_condition) { |
196 | (PathSource::Expr(_), Some(Expr { span, kind: ExprKind::Assign(..), .. })) => { | |
197 | err.span_suggestion_verbose( | |
198 | span.shrink_to_lo(), | |
199 | "you might have meant to use pattern matching", | |
200 | "let ".to_string(), | |
201 | Applicability::MaybeIncorrect, | |
202 | ); | |
203 | self.r.session.if_let_suggestions.borrow_mut().insert(*span); | |
204 | } | |
205 | _ => {} | |
206 | } | |
207 | ||
3dfed10e | 208 | let is_assoc_fn = self.self_type_is_available(span); |
416331ca | 209 | // Emit help message for fake-self from other languages (e.g., `this` in Javascript). |
3dfed10e | 210 | if ["this", "my"].contains(&&*item_str.as_str()) && is_assoc_fn { |
f035d41b | 211 | err.span_suggestion_short( |
416331ca | 212 | span, |
f035d41b | 213 | "you might have meant to use `self` here instead", |
416331ca XL |
214 | "self".to_string(), |
215 | Applicability::MaybeIncorrect, | |
216 | ); | |
3dfed10e XL |
217 | if !self.self_value_is_available(path[0].ident.span, span) { |
218 | if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) = | |
219 | &self.diagnostic_metadata.current_function | |
220 | { | |
221 | let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) { | |
222 | (param.span.shrink_to_lo(), "&self, ") | |
223 | } else { | |
224 | ( | |
225 | self.r | |
226 | .session | |
227 | .source_map() | |
228 | .span_through_char(*fn_span, '(') | |
229 | .shrink_to_hi(), | |
230 | "&self", | |
231 | ) | |
232 | }; | |
233 | err.span_suggestion_verbose( | |
234 | span, | |
235 | "if you meant to use `self`, you are also missing a `self` receiver \ | |
236 | argument", | |
237 | sugg.to_string(), | |
238 | Applicability::MaybeIncorrect, | |
239 | ); | |
240 | } | |
241 | } | |
416331ca XL |
242 | } |
243 | ||
244 | // Emit special messages for unresolved `Self` and `self`. | |
245 | if is_self_type(path, ns) { | |
dfeec247 | 246 | err.code(rustc_errors::error_code!(E0411)); |
e74abb32 XL |
247 | err.span_label( |
248 | span, | |
74b04a01 | 249 | "`Self` is only available in impls, traits, and type definitions".to_string(), |
e74abb32 | 250 | ); |
416331ca XL |
251 | return (err, Vec::new()); |
252 | } | |
253 | if is_self_value(path, ns) { | |
254 | debug!("smart_resolve_path_fragment: E0424, source={:?}", source); | |
255 | ||
dfeec247 | 256 | err.code(rustc_errors::error_code!(E0424)); |
416331ca | 257 | err.span_label(span, match source { |
74b04a01 XL |
258 | PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed" |
259 | .to_string(), | |
260 | _ => "`self` value is a keyword only available in methods with a `self` parameter" | |
261 | .to_string(), | |
416331ca | 262 | }); |
f9f354fc XL |
263 | if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function { |
264 | // The current function has a `self' parameter, but we were unable to resolve | |
265 | // a reference to `self`. This can only happen if the `self` identifier we | |
266 | // are resolving came from a different hygiene context. | |
267 | if fn_kind.decl().inputs.get(0).map(|p| p.is_self()).unwrap_or(false) { | |
268 | err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters"); | |
269 | } else { | |
3dfed10e XL |
270 | let doesnt = if is_assoc_fn { |
271 | let (span, sugg) = fn_kind | |
272 | .decl() | |
273 | .inputs | |
274 | .get(0) | |
275 | .map(|p| (p.span.shrink_to_lo(), "&self, ")) | |
276 | .unwrap_or_else(|| { | |
277 | ( | |
278 | self.r | |
279 | .session | |
280 | .source_map() | |
281 | .span_through_char(*span, '(') | |
282 | .shrink_to_hi(), | |
283 | "&self", | |
284 | ) | |
285 | }); | |
286 | err.span_suggestion_verbose( | |
287 | span, | |
288 | "add a `self` receiver parameter to make the associated `fn` a method", | |
289 | sugg.to_string(), | |
290 | Applicability::MaybeIncorrect, | |
291 | ); | |
292 | "doesn't" | |
293 | } else { | |
294 | "can't" | |
295 | }; | |
296 | if let Some(ident) = fn_kind.ident() { | |
297 | err.span_label( | |
298 | ident.span, | |
299 | &format!("this function {} have a `self` parameter", doesnt), | |
300 | ); | |
301 | } | |
f9f354fc | 302 | } |
e74abb32 | 303 | } |
416331ca XL |
304 | return (err, Vec::new()); |
305 | } | |
306 | ||
307 | // Try to lookup name in more relaxed fashion for better error reporting. | |
308 | let ident = path.last().unwrap().ident; | |
dfeec247 XL |
309 | let candidates = self |
310 | .r | |
f035d41b | 311 | .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected) |
416331ca XL |
312 | .drain(..) |
313 | .filter(|ImportSuggestion { did, .. }| { | |
314 | match (did, res.and_then(|res| res.opt_def_id())) { | |
315 | (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did, | |
316 | _ => true, | |
317 | } | |
318 | }) | |
319 | .collect::<Vec<_>>(); | |
320 | let crate_def_id = DefId::local(CRATE_DEF_INDEX); | |
321 | if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) { | |
f035d41b XL |
322 | let enum_candidates = |
323 | self.r.lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant); | |
416331ca XL |
324 | |
325 | if !enum_candidates.is_empty() { | |
3dfed10e XL |
326 | if let (PathSource::Type, Some(span)) = |
327 | (source, self.diagnostic_metadata.current_type_ascription.last()) | |
328 | { | |
329 | if self | |
330 | .r | |
331 | .session | |
332 | .parse_sess | |
333 | .type_ascription_path_suggestions | |
334 | .borrow() | |
335 | .contains(span) | |
336 | { | |
337 | // Already reported this issue on the lhs of the type ascription. | |
338 | err.delay_as_bug(); | |
339 | return (err, candidates); | |
340 | } | |
341 | } | |
342 | ||
343 | let mut enum_candidates = enum_candidates | |
344 | .iter() | |
345 | .map(|suggestion| import_candidate_to_enum_paths(&suggestion)) | |
346 | .collect::<Vec<_>>(); | |
347 | enum_candidates.sort(); | |
348 | ||
416331ca XL |
349 | // Contextualize for E0412 "cannot find type", but don't belabor the point |
350 | // (that it's a variant) for E0573 "expected type, found variant". | |
351 | let preamble = if res.is_none() { | |
352 | let others = match enum_candidates.len() { | |
353 | 1 => String::new(), | |
354 | 2 => " and 1 other".to_owned(), | |
dfeec247 | 355 | n => format!(" and {} others", n), |
416331ca | 356 | }; |
dfeec247 | 357 | format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others) |
416331ca XL |
358 | } else { |
359 | String::new() | |
360 | }; | |
361 | let msg = format!("{}try using the variant's enum", preamble); | |
362 | ||
363 | err.span_suggestions( | |
364 | span, | |
365 | &msg, | |
dfeec247 XL |
366 | enum_candidates |
367 | .into_iter() | |
416331ca XL |
368 | .map(|(_variant_path, enum_ty_path)| enum_ty_path) |
369 | // Variants re-exported in prelude doesn't mean `prelude::v1` is the | |
370 | // type name! | |
371 | // FIXME: is there a more principled way to do this that | |
372 | // would work for other re-exports? | |
373 | .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1") | |
374 | // Also write `Option` rather than `std::prelude::v1::Option`. | |
375 | .map(|enum_ty_path| { | |
376 | // FIXME #56861: DRY-er prelude filtering. | |
377 | enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned() | |
378 | }), | |
379 | Applicability::MachineApplicable, | |
380 | ); | |
381 | } | |
382 | } | |
383 | if path.len() == 1 && self.self_type_is_available(span) { | |
384 | if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) { | |
385 | let self_is_available = self.self_value_is_available(path[0].ident.span, span); | |
386 | match candidate { | |
387 | AssocSuggestion::Field => { | |
388 | if self_is_available { | |
389 | err.span_suggestion( | |
390 | span, | |
391 | "you might have meant to use the available field", | |
392 | format!("self.{}", path_str), | |
393 | Applicability::MachineApplicable, | |
394 | ); | |
395 | } else { | |
dfeec247 | 396 | err.span_label(span, "a field by this name exists in `Self`"); |
416331ca XL |
397 | } |
398 | } | |
399 | AssocSuggestion::MethodWithSelf if self_is_available => { | |
400 | err.span_suggestion( | |
401 | span, | |
29967ef6 | 402 | "you might have meant to call the method", |
416331ca XL |
403 | format!("self.{}", path_str), |
404 | Applicability::MachineApplicable, | |
405 | ); | |
406 | } | |
29967ef6 XL |
407 | AssocSuggestion::MethodWithSelf |
408 | | AssocSuggestion::AssocFn | |
409 | | AssocSuggestion::AssocConst | |
410 | | AssocSuggestion::AssocType => { | |
416331ca XL |
411 | err.span_suggestion( |
412 | span, | |
29967ef6 | 413 | &format!("you might have meant to {}", candidate.action()), |
416331ca XL |
414 | format!("Self::{}", path_str), |
415 | Applicability::MachineApplicable, | |
416 | ); | |
417 | } | |
418 | } | |
419 | return (err, candidates); | |
420 | } | |
dfeec247 XL |
421 | |
422 | // If the first argument in call is `self` suggest calling a method. | |
423 | if let Some((call_span, args_span)) = self.call_has_self_arg(source) { | |
424 | let mut args_snippet = String::new(); | |
425 | if let Some(args_span) = args_span { | |
426 | if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) { | |
427 | args_snippet = snippet; | |
428 | } | |
429 | } | |
430 | ||
431 | err.span_suggestion( | |
432 | call_span, | |
433 | &format!("try calling `{}` as a method", ident), | |
434 | format!("self.{}({})", path_str, args_snippet), | |
435 | Applicability::MachineApplicable, | |
436 | ); | |
437 | return (err, candidates); | |
438 | } | |
416331ca XL |
439 | } |
440 | ||
441 | // Try Levenshtein algorithm. | |
e74abb32 | 442 | let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span); |
416331ca XL |
443 | // Try context-dependent help if relaxed lookup didn't work. |
444 | if let Some(res) = res { | |
e74abb32 XL |
445 | if self.smart_resolve_context_dependent_help( |
446 | &mut err, | |
447 | span, | |
448 | source, | |
449 | res, | |
450 | &path_str, | |
451 | &fallback_label, | |
452 | ) { | |
3dfed10e XL |
453 | // We do this to avoid losing a secondary span when we override the main error span. |
454 | self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span); | |
416331ca XL |
455 | return (err, candidates); |
456 | } | |
457 | } | |
458 | ||
29967ef6 XL |
459 | if !self.type_ascription_suggestion(&mut err, base_span) { |
460 | let mut fallback = false; | |
461 | if let ( | |
462 | PathSource::Trait(AliasPossibility::Maybe), | |
463 | Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)), | |
464 | ) = (source, res) | |
465 | { | |
466 | if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object { | |
467 | fallback = true; | |
468 | let spans: Vec<Span> = bounds | |
469 | .iter() | |
470 | .map(|bound| bound.span()) | |
471 | .filter(|&sp| sp != base_span) | |
472 | .collect(); | |
473 | ||
474 | let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap(); | |
475 | // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><) | |
476 | let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap(); | |
477 | // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar) | |
478 | let last_bound_span = spans.last().cloned().unwrap(); | |
479 | let mut multi_span: MultiSpan = spans.clone().into(); | |
480 | for sp in spans { | |
481 | let msg = if sp == last_bound_span { | |
482 | format!( | |
483 | "...because of {} bound{}", | |
484 | if bounds.len() <= 2 { "this" } else { "these" }, | |
485 | if bounds.len() <= 2 { "" } else { "s" }, | |
486 | ) | |
487 | } else { | |
488 | String::new() | |
489 | }; | |
490 | multi_span.push_span_label(sp, msg); | |
491 | } | |
492 | multi_span.push_span_label( | |
493 | base_span, | |
494 | "expected this type to be a trait...".to_string(), | |
e74abb32 | 495 | ); |
29967ef6 XL |
496 | err.span_help( |
497 | multi_span, | |
498 | "`+` is used to constrain a \"trait object\" type with lifetimes or \ | |
499 | auto-traits; structs and enums can't be bound in that way", | |
500 | ); | |
501 | if bounds.iter().all(|bound| match bound { | |
502 | ast::GenericBound::Outlives(_) => true, | |
503 | ast::GenericBound::Trait(tr, _) => tr.span == base_span, | |
504 | }) { | |
505 | let mut sugg = vec![]; | |
506 | if base_span != start_span { | |
507 | sugg.push((start_span.until(base_span), String::new())); | |
508 | } | |
509 | if base_span != end_span { | |
510 | sugg.push((base_span.shrink_to_hi().to(end_span), String::new())); | |
511 | } | |
512 | ||
513 | err.multipart_suggestion( | |
514 | "if you meant to use a type and not a trait here, remove the bounds", | |
515 | sugg, | |
516 | Applicability::MaybeIncorrect, | |
517 | ); | |
518 | } | |
e74abb32 | 519 | } |
29967ef6 XL |
520 | } |
521 | ||
522 | fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err); | |
523 | ||
524 | if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) { | |
525 | fallback = true; | |
526 | match self.diagnostic_metadata.current_let_binding { | |
527 | Some((pat_sp, Some(ty_sp), None)) | |
528 | if ty_sp.contains(base_span) && could_be_expr => | |
529 | { | |
530 | err.span_suggestion_short( | |
531 | pat_sp.between(ty_sp), | |
532 | "use `=` if you meant to assign", | |
533 | " = ".to_string(), | |
534 | Applicability::MaybeIncorrect, | |
535 | ); | |
536 | } | |
537 | _ => {} | |
538 | } | |
539 | } | |
540 | if fallback { | |
541 | // Fallback label. | |
542 | err.span_label(base_span, fallback_label); | |
e74abb32 | 543 | } |
416331ca | 544 | } |
fc512014 XL |
545 | if let Some(err_code) = &err.code { |
546 | if err_code == &rustc_errors::error_code!(E0425) { | |
547 | for label_rib in &self.label_ribs { | |
548 | for (label_ident, _) in &label_rib.bindings { | |
549 | if format!("'{}", ident) == label_ident.to_string() { | |
550 | let msg = "a label with a similar name exists"; | |
551 | // FIXME: consider only emitting this suggestion if a label would be valid here | |
552 | // which is pretty much only the case for `break` expressions. | |
553 | err.span_suggestion( | |
554 | span, | |
555 | &msg, | |
556 | label_ident.name.to_string(), | |
557 | Applicability::MaybeIncorrect, | |
558 | ); | |
559 | } | |
560 | } | |
561 | } | |
562 | } | |
563 | } | |
564 | ||
416331ca XL |
565 | (err, candidates) |
566 | } | |
567 | ||
29967ef6 XL |
568 | /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`. |
569 | fn restrict_assoc_type_in_where_clause( | |
570 | &mut self, | |
571 | span: Span, | |
572 | err: &mut DiagnosticBuilder<'_>, | |
573 | ) -> bool { | |
574 | // Detect that we are actually in a `where` predicate. | |
575 | let (bounded_ty, bounds, where_span) = | |
576 | if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { | |
577 | bounded_ty, | |
578 | bound_generic_params, | |
579 | bounds, | |
580 | span, | |
581 | })) = self.diagnostic_metadata.current_where_predicate | |
582 | { | |
583 | if !bound_generic_params.is_empty() { | |
584 | return false; | |
585 | } | |
586 | (bounded_ty, bounds, span) | |
587 | } else { | |
588 | return false; | |
589 | }; | |
590 | ||
591 | // Confirm that the target is an associated type. | |
592 | let (ty, position, path) = if let ast::TyKind::Path( | |
593 | Some(ast::QSelf { ty, position, .. }), | |
594 | path, | |
595 | ) = &bounded_ty.kind | |
596 | { | |
597 | // use this to verify that ident is a type param. | |
598 | let partial_res = if let Ok(Some(partial_res)) = self.resolve_qpath_anywhere( | |
599 | bounded_ty.id, | |
600 | None, | |
601 | &Segment::from_path(path), | |
602 | Namespace::TypeNS, | |
603 | span, | |
604 | true, | |
605 | CrateLint::No, | |
606 | ) { | |
607 | partial_res | |
608 | } else { | |
609 | return false; | |
610 | }; | |
611 | if !(matches!( | |
612 | partial_res.base_res(), | |
613 | hir::def::Res::Def(hir::def::DefKind::AssocTy, _) | |
614 | ) && partial_res.unresolved_segments() == 0) | |
615 | { | |
616 | return false; | |
617 | } | |
618 | (ty, position, path) | |
619 | } else { | |
620 | return false; | |
621 | }; | |
622 | ||
623 | if let ast::TyKind::Path(None, type_param_path) = &ty.peel_refs().kind { | |
624 | // Confirm that the `SelfTy` is a type parameter. | |
625 | let partial_res = if let Ok(Some(partial_res)) = self.resolve_qpath_anywhere( | |
626 | bounded_ty.id, | |
627 | None, | |
628 | &Segment::from_path(type_param_path), | |
629 | Namespace::TypeNS, | |
630 | span, | |
631 | true, | |
632 | CrateLint::No, | |
633 | ) { | |
634 | partial_res | |
635 | } else { | |
636 | return false; | |
637 | }; | |
638 | if !(matches!( | |
639 | partial_res.base_res(), | |
640 | hir::def::Res::Def(hir::def::DefKind::TyParam, _) | |
641 | ) && partial_res.unresolved_segments() == 0) | |
642 | { | |
643 | return false; | |
644 | } | |
645 | if let ( | |
646 | [ast::PathSegment { ident: constrain_ident, args: None, .. }], | |
647 | [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)], | |
648 | ) = (&type_param_path.segments[..], &bounds[..]) | |
649 | { | |
650 | if let [ast::PathSegment { ident, args: None, .. }] = | |
651 | &poly_trait_ref.trait_ref.path.segments[..] | |
652 | { | |
653 | if ident.span == span { | |
654 | err.span_suggestion_verbose( | |
655 | *where_span, | |
656 | &format!("constrain the associated type to `{}`", ident), | |
657 | format!( | |
658 | "{}: {}<{} = {}>", | |
659 | self.r | |
660 | .session | |
661 | .source_map() | |
662 | .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`. | |
663 | .unwrap_or_else(|_| constrain_ident.to_string()), | |
664 | path.segments[..*position] | |
665 | .iter() | |
666 | .map(|segment| path_segment_to_string(segment)) | |
667 | .collect::<Vec<_>>() | |
668 | .join("::"), | |
669 | path.segments[*position..] | |
670 | .iter() | |
671 | .map(|segment| path_segment_to_string(segment)) | |
672 | .collect::<Vec<_>>() | |
673 | .join("::"), | |
674 | ident, | |
675 | ), | |
676 | Applicability::MaybeIncorrect, | |
677 | ); | |
678 | } | |
679 | return true; | |
680 | } | |
681 | } | |
682 | } | |
683 | false | |
684 | } | |
685 | ||
dfeec247 XL |
686 | /// Check if the source is call expression and the first argument is `self`. If true, |
687 | /// return the span of whole call and the span for all arguments expect the first one (`self`). | |
688 | fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> { | |
689 | let mut has_self_arg = None; | |
3dfed10e XL |
690 | if let PathSource::Expr(Some(parent)) = source { |
691 | match &parent.kind { | |
74b04a01 | 692 | ExprKind::Call(_, args) if !args.is_empty() => { |
dfeec247 XL |
693 | let mut expr_kind = &args[0].kind; |
694 | loop { | |
695 | match expr_kind { | |
696 | ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => { | |
697 | if arg_name.segments[0].ident.name == kw::SelfLower { | |
3dfed10e | 698 | let call_span = parent.span; |
dfeec247 XL |
699 | let tail_args_span = if args.len() > 1 { |
700 | Some(Span::new( | |
701 | args[1].span.lo(), | |
702 | args.last().unwrap().span.hi(), | |
703 | call_span.ctxt(), | |
704 | )) | |
705 | } else { | |
706 | None | |
707 | }; | |
708 | has_self_arg = Some((call_span, tail_args_span)); | |
709 | } | |
710 | break; | |
711 | } | |
712 | ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind, | |
713 | _ => break, | |
714 | } | |
715 | } | |
716 | } | |
717 | _ => (), | |
718 | } | |
719 | }; | |
ba9703b0 | 720 | has_self_arg |
dfeec247 XL |
721 | } |
722 | ||
f9f354fc | 723 | fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) { |
416331ca XL |
724 | // HACK(estebank): find a better way to figure out that this was a |
725 | // parser issue where a struct literal is being used on an expression | |
726 | // where a brace being opened means a block is being started. Look | |
727 | // ahead for the next text to see if `span` is followed by a `{`. | |
728 | let sm = self.r.session.source_map(); | |
729 | let mut sp = span; | |
730 | loop { | |
731 | sp = sm.next_point(sp); | |
732 | match sm.span_to_snippet(sp) { | |
733 | Ok(ref snippet) => { | |
dfeec247 | 734 | if snippet.chars().any(|c| !c.is_whitespace()) { |
416331ca XL |
735 | break; |
736 | } | |
737 | } | |
738 | _ => break, | |
739 | } | |
740 | } | |
29967ef6 | 741 | let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{"); |
416331ca | 742 | // In case this could be a struct literal that needs to be surrounded |
f9f354fc | 743 | // by parentheses, find the appropriate span. |
416331ca XL |
744 | let mut i = 0; |
745 | let mut closing_brace = None; | |
746 | loop { | |
747 | sp = sm.next_point(sp); | |
748 | match sm.span_to_snippet(sp) { | |
749 | Ok(ref snippet) => { | |
750 | if snippet == "}" { | |
f9f354fc | 751 | closing_brace = Some(span.to(sp)); |
416331ca XL |
752 | break; |
753 | } | |
754 | } | |
755 | _ => break, | |
756 | } | |
757 | i += 1; | |
758 | // The bigger the span, the more likely we're incorrect -- | |
759 | // bound it to 100 chars long. | |
760 | if i > 100 { | |
761 | break; | |
762 | } | |
763 | } | |
ba9703b0 | 764 | (followed_by_brace, closing_brace) |
416331ca XL |
765 | } |
766 | ||
767 | /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment` | |
768 | /// function. | |
769 | /// Returns `true` if able to provide context-dependent help. | |
770 | fn smart_resolve_context_dependent_help( | |
771 | &mut self, | |
772 | err: &mut DiagnosticBuilder<'a>, | |
773 | span: Span, | |
774 | source: PathSource<'_>, | |
775 | res: Res, | |
776 | path_str: &str, | |
777 | fallback_label: &str, | |
778 | ) -> bool { | |
779 | let ns = source.namespace(); | |
780 | let is_expected = &|res| source.is_expected(res); | |
781 | ||
e74abb32 | 782 | let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind { |
416331ca XL |
783 | ExprKind::Field(_, ident) => { |
784 | err.span_suggestion( | |
785 | expr.span, | |
786 | "use the path separator to refer to an item", | |
787 | format!("{}::{}", path_str, ident), | |
788 | Applicability::MaybeIncorrect, | |
789 | ); | |
790 | true | |
791 | } | |
792 | ExprKind::MethodCall(ref segment, ..) => { | |
793 | let span = expr.span.with_hi(segment.ident.span.hi()); | |
794 | err.span_suggestion( | |
795 | span, | |
796 | "use the path separator to refer to an item", | |
797 | format!("{}::{}", path_str, segment.ident), | |
798 | Applicability::MaybeIncorrect, | |
799 | ); | |
800 | true | |
801 | } | |
802 | _ => false, | |
803 | }; | |
804 | ||
e74abb32 | 805 | let mut bad_struct_syntax_suggestion = |def_id: DefId| { |
416331ca | 806 | let (followed_by_brace, closing_brace) = self.followed_by_brace(span); |
3dfed10e | 807 | |
416331ca | 808 | match source { |
3dfed10e XL |
809 | PathSource::Expr(Some( |
810 | parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. }, | |
811 | )) if path_sep(err, &parent) => {} | |
812 | PathSource::Expr( | |
813 | None | |
814 | | Some(Expr { | |
815 | kind: | |
816 | ExprKind::Path(..) | |
817 | | ExprKind::Binary(..) | |
818 | | ExprKind::Unary(..) | |
819 | | ExprKind::If(..) | |
820 | | ExprKind::While(..) | |
821 | | ExprKind::ForLoop(..) | |
822 | | ExprKind::Match(..), | |
823 | .. | |
824 | }), | |
825 | ) if followed_by_brace => { | |
f9f354fc | 826 | if let Some(sp) = closing_brace { |
3dfed10e | 827 | err.span_label(span, fallback_label); |
f9f354fc XL |
828 | err.multipart_suggestion( |
829 | "surround the struct literal with parentheses", | |
830 | vec![ | |
831 | (sp.shrink_to_lo(), "(".to_string()), | |
832 | (sp.shrink_to_hi(), ")".to_string()), | |
833 | ], | |
416331ca XL |
834 | Applicability::MaybeIncorrect, |
835 | ); | |
836 | } else { | |
837 | err.span_label( | |
f9f354fc XL |
838 | span, // Note the parentheses surrounding the suggestion below |
839 | format!( | |
840 | "you might want to surround a struct literal with parentheses: \ | |
841 | `({} {{ /* fields */ }})`?", | |
842 | path_str | |
843 | ), | |
416331ca XL |
844 | ); |
845 | } | |
dfeec247 | 846 | } |
1b1a35ee | 847 | PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => { |
3dfed10e XL |
848 | let span = match &source { |
849 | PathSource::Expr(Some(Expr { | |
850 | span, kind: ExprKind::Call(_, _), .. | |
851 | })) | |
1b1a35ee | 852 | | PathSource::TupleStruct(span, _) => { |
3dfed10e XL |
853 | // We want the main underline to cover the suggested code as well for |
854 | // cleaner output. | |
855 | err.set_span(*span); | |
856 | *span | |
857 | } | |
858 | _ => span, | |
859 | }; | |
860 | if let Some(span) = self.def_span(def_id) { | |
861 | err.span_label(span, &format!("`{}` defined here", path_str)); | |
862 | } | |
863 | let (tail, descr, applicability) = match source { | |
1b1a35ee | 864 | PathSource::Pat | PathSource::TupleStruct(..) => { |
3dfed10e XL |
865 | ("", "pattern", Applicability::MachineApplicable) |
866 | } | |
867 | _ => (": val", "literal", Applicability::HasPlaceholders), | |
868 | }; | |
869 | let (fields, applicability) = match self.r.field_names.get(&def_id) { | |
870 | Some(fields) => ( | |
871 | fields | |
872 | .iter() | |
873 | .map(|f| format!("{}{}", f.node, tail)) | |
874 | .collect::<Vec<String>>() | |
875 | .join(", "), | |
876 | applicability, | |
877 | ), | |
878 | None => ("/* fields */".to_string(), Applicability::HasPlaceholders), | |
879 | }; | |
880 | let pad = match self.r.field_names.get(&def_id) { | |
881 | Some(fields) if fields.is_empty() => "", | |
882 | _ => " ", | |
883 | }; | |
884 | err.span_suggestion( | |
885 | span, | |
886 | &format!("use struct {} syntax instead", descr), | |
29967ef6 | 887 | format!("{path_str} {{{pad}{fields}{pad}}}"), |
3dfed10e XL |
888 | applicability, |
889 | ); | |
890 | } | |
891 | _ => { | |
892 | err.span_label(span, fallback_label); | |
e74abb32 | 893 | } |
416331ca XL |
894 | } |
895 | }; | |
896 | ||
897 | match (res, source) { | |
898 | (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => { | |
3dfed10e | 899 | err.span_label(span, fallback_label); |
ba9703b0 XL |
900 | err.span_suggestion_verbose( |
901 | span.shrink_to_hi(), | |
416331ca | 902 | "use `!` to invoke the macro", |
ba9703b0 | 903 | "!".to_string(), |
416331ca XL |
904 | Applicability::MaybeIncorrect, |
905 | ); | |
906 | if path_str == "try" && span.rust_2015() { | |
907 | err.note("if you want the `try` keyword, you need to be in the 2018 edition"); | |
908 | } | |
909 | } | |
f9f354fc | 910 | (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => { |
416331ca | 911 | err.span_label(span, "type aliases cannot be used as traits"); |
fc512014 | 912 | if self.r.session.is_nightly_build() { |
f9f354fc XL |
913 | let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \ |
914 | `type` alias"; | |
3dfed10e | 915 | if let Some(span) = self.def_span(def_id) { |
f9f354fc XL |
916 | err.span_help(span, msg); |
917 | } else { | |
918 | err.help(msg); | |
919 | } | |
416331ca XL |
920 | } |
921 | } | |
922 | (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => { | |
923 | if !path_sep(err, &parent) { | |
924 | return false; | |
925 | } | |
926 | } | |
3dfed10e XL |
927 | ( |
928 | Res::Def(DefKind::Enum, def_id), | |
1b1a35ee | 929 | PathSource::TupleStruct(..) | PathSource::Expr(..), |
3dfed10e XL |
930 | ) => { |
931 | if self | |
932 | .diagnostic_metadata | |
933 | .current_type_ascription | |
934 | .last() | |
935 | .map(|sp| { | |
936 | self.r | |
937 | .session | |
938 | .parse_sess | |
939 | .type_ascription_path_suggestions | |
940 | .borrow() | |
941 | .contains(&sp) | |
942 | }) | |
943 | .unwrap_or(false) | |
944 | { | |
945 | err.delay_as_bug(); | |
946 | // We already suggested changing `:` into `::` during parsing. | |
947 | return false; | |
948 | } | |
416331ca | 949 | |
29967ef6 | 950 | self.suggest_using_enum_variant(err, source, def_id, span); |
e1599b0c | 951 | } |
416331ca | 952 | (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => { |
29967ef6 XL |
953 | let (ctor_def, ctor_vis, fields) = |
954 | if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() { | |
955 | struct_ctor | |
956 | } else { | |
957 | bad_struct_syntax_suggestion(def_id); | |
958 | return true; | |
959 | }; | |
1b1a35ee | 960 | |
29967ef6 XL |
961 | let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module); |
962 | if !is_expected(ctor_def) || is_accessible { | |
963 | return true; | |
964 | } | |
965 | ||
966 | let field_spans = match source { | |
967 | // e.g. `if let Enum::TupleVariant(field1, field2) = _` | |
968 | PathSource::TupleStruct(_, pattern_spans) => { | |
969 | err.set_primary_message( | |
970 | "cannot match against a tuple struct which contains private fields", | |
971 | ); | |
972 | ||
973 | // Use spans of the tuple struct pattern. | |
974 | Some(Vec::from(pattern_spans)) | |
416331ca | 975 | } |
29967ef6 XL |
976 | // e.g. `let _ = Enum::TupleVariant(field1, field2);` |
977 | _ if source.is_call() => { | |
978 | err.set_primary_message( | |
979 | "cannot initialize a tuple struct which contains private fields", | |
980 | ); | |
981 | ||
982 | // Use spans of the tuple struct definition. | |
983 | self.r | |
984 | .field_names | |
985 | .get(&def_id) | |
986 | .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>()) | |
987 | } | |
988 | _ => None, | |
989 | }; | |
990 | ||
991 | if let Some(spans) = | |
992 | field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len()) | |
993 | { | |
994 | let non_visible_spans: Vec<Span> = fields | |
995 | .iter() | |
996 | .zip(spans.iter()) | |
997 | .filter(|(vis, _)| { | |
998 | !self.r.is_accessible_from(**vis, self.parent_scope.module) | |
999 | }) | |
1000 | .map(|(_, span)| *span) | |
1001 | .collect(); | |
1002 | ||
1003 | if non_visible_spans.len() > 0 { | |
1004 | let mut m: rustc_span::MultiSpan = non_visible_spans.clone().into(); | |
1005 | non_visible_spans | |
1006 | .into_iter() | |
1007 | .for_each(|s| m.push_span_label(s, "private field".to_string())); | |
1008 | err.span_note(m, "constructor is not visible here due to private fields"); | |
1009 | } | |
1010 | ||
1011 | return true; | |
416331ca | 1012 | } |
29967ef6 XL |
1013 | |
1014 | err.span_label( | |
1015 | span, | |
1016 | "constructor is not visible here due to private fields".to_string(), | |
1017 | ); | |
416331ca | 1018 | } |
ba9703b0 XL |
1019 | ( |
1020 | Res::Def( | |
1021 | DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive), | |
1022 | def_id, | |
1023 | ), | |
1024 | _, | |
1025 | ) if ns == ValueNS => { | |
e74abb32 | 1026 | bad_struct_syntax_suggestion(def_id); |
416331ca | 1027 | } |
e74abb32 | 1028 | (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => { |
3dfed10e | 1029 | if let Some(span) = self.def_span(def_id) { |
e74abb32 XL |
1030 | err.span_label(span, &format!("`{}` defined here", path_str)); |
1031 | } | |
3dfed10e XL |
1032 | let fields = |
1033 | self.r.field_names.get(&def_id).map_or("/* fields */".to_string(), |fields| { | |
1034 | vec!["_"; fields.len()].join(", ") | |
1035 | }); | |
1036 | err.span_suggestion( | |
1037 | span, | |
1038 | "use the tuple variant pattern syntax instead", | |
1039 | format!("{}({})", path_str, fields), | |
1040 | Applicability::HasPlaceholders, | |
1041 | ); | |
e1599b0c | 1042 | } |
416331ca XL |
1043 | (Res::SelfTy(..), _) if ns == ValueNS => { |
1044 | err.span_label(span, fallback_label); | |
1045 | err.note("can't use `Self` as a constructor, you must use the implemented struct"); | |
1046 | } | |
ba9703b0 | 1047 | (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => { |
416331ca XL |
1048 | err.note("can't use a type alias as a constructor"); |
1049 | } | |
1050 | _ => return false, | |
1051 | } | |
1052 | true | |
1053 | } | |
1054 | ||
dfeec247 XL |
1055 | fn lookup_assoc_candidate<FilterFn>( |
1056 | &mut self, | |
1057 | ident: Ident, | |
1058 | ns: Namespace, | |
1059 | filter_fn: FilterFn, | |
1060 | ) -> Option<AssocSuggestion> | |
1061 | where | |
1062 | FilterFn: Fn(Res) -> bool, | |
416331ca XL |
1063 | { |
1064 | fn extract_node_id(t: &Ty) -> Option<NodeId> { | |
e74abb32 | 1065 | match t.kind { |
416331ca XL |
1066 | TyKind::Path(None, _) => Some(t.id), |
1067 | TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty), | |
1068 | // This doesn't handle the remaining `Ty` variants as they are not | |
1069 | // that commonly the self_type, it might be interesting to provide | |
1070 | // support for those in future. | |
1071 | _ => None, | |
1072 | } | |
1073 | } | |
1074 | ||
1075 | // Fields are generally expected in the same contexts as locals. | |
1076 | if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) { | |
dfeec247 XL |
1077 | if let Some(node_id) = |
1078 | self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id) | |
e74abb32 | 1079 | { |
416331ca XL |
1080 | // Look for a field with the same name in the current self_type. |
1081 | if let Some(resolution) = self.r.partial_res_map.get(&node_id) { | |
1082 | match resolution.base_res() { | |
ba9703b0 | 1083 | Res::Def(DefKind::Struct | DefKind::Union, did) |
dfeec247 XL |
1084 | if resolution.unresolved_segments() == 0 => |
1085 | { | |
416331ca | 1086 | if let Some(field_names) = self.r.field_names.get(&did) { |
dfeec247 XL |
1087 | if field_names |
1088 | .iter() | |
1089 | .any(|&field_name| ident.name == field_name.node) | |
1090 | { | |
416331ca XL |
1091 | return Some(AssocSuggestion::Field); |
1092 | } | |
1093 | } | |
1094 | } | |
1095 | _ => {} | |
1096 | } | |
1097 | } | |
1098 | } | |
1099 | } | |
1100 | ||
29967ef6 XL |
1101 | if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items { |
1102 | for assoc_item in &items[..] { | |
1103 | if assoc_item.ident == ident { | |
1104 | return Some(match &assoc_item.kind { | |
1105 | ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst, | |
1106 | ast::AssocItemKind::Fn(_, sig, ..) if sig.decl.has_self() => { | |
1107 | AssocSuggestion::MethodWithSelf | |
1108 | } | |
1109 | ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn, | |
1110 | ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType, | |
1111 | ast::AssocItemKind::MacCall(_) => continue, | |
1112 | }); | |
1113 | } | |
416331ca XL |
1114 | } |
1115 | } | |
1116 | ||
1117 | // Look for associated items in the current trait. | |
1118 | if let Some((module, _)) = self.current_trait_ref { | |
1119 | if let Ok(binding) = self.r.resolve_ident_in_module( | |
dfeec247 XL |
1120 | ModuleOrUniformRoot::Module(module), |
1121 | ident, | |
1122 | ns, | |
1123 | &self.parent_scope, | |
1124 | false, | |
1125 | module.span, | |
1126 | ) { | |
416331ca XL |
1127 | let res = binding.res(); |
1128 | if filter_fn(res) { | |
29967ef6 XL |
1129 | if self.r.has_self.contains(&res.def_id()) { |
1130 | return Some(AssocSuggestion::MethodWithSelf); | |
416331ca | 1131 | } else { |
29967ef6 XL |
1132 | match res { |
1133 | Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn), | |
1134 | Res::Def(DefKind::AssocConst, _) => { | |
1135 | return Some(AssocSuggestion::AssocConst); | |
1136 | } | |
1137 | Res::Def(DefKind::AssocTy, _) => { | |
1138 | return Some(AssocSuggestion::AssocType); | |
1139 | } | |
1140 | _ => {} | |
1141 | } | |
1142 | } | |
416331ca XL |
1143 | } |
1144 | } | |
1145 | } | |
1146 | ||
1147 | None | |
1148 | } | |
1149 | ||
1150 | fn lookup_typo_candidate( | |
1151 | &mut self, | |
1152 | path: &[Segment], | |
1153 | ns: Namespace, | |
1154 | filter_fn: &impl Fn(Res) -> bool, | |
1155 | span: Span, | |
1156 | ) -> Option<TypoSuggestion> { | |
1157 | let mut names = Vec::new(); | |
1158 | if path.len() == 1 { | |
1159 | // Search in lexical scope. | |
1160 | // Walk backwards up the ribs in scope and collect candidates. | |
1161 | for rib in self.ribs[ns].iter().rev() { | |
1162 | // Locals and type parameters | |
1163 | for (ident, &res) in &rib.bindings { | |
1164 | if filter_fn(res) { | |
1165 | names.push(TypoSuggestion::from_res(ident.name, res)); | |
1166 | } | |
1167 | } | |
1168 | // Items in scope | |
1169 | if let RibKind::ModuleRibKind(module) = rib.kind { | |
1170 | // Items from this module | |
e1599b0c | 1171 | self.r.add_module_candidates(module, &mut names, &filter_fn); |
416331ca XL |
1172 | |
1173 | if let ModuleKind::Block(..) = module.kind { | |
1174 | // We can see through blocks | |
1175 | } else { | |
1176 | // Items from the prelude | |
1177 | if !module.no_implicit_prelude { | |
1178 | let extern_prelude = self.r.extern_prelude.clone(); | |
1179 | names.extend(extern_prelude.iter().flat_map(|(ident, _)| { | |
3dfed10e XL |
1180 | self.r.crate_loader.maybe_process_path_extern(ident.name).and_then( |
1181 | |crate_id| { | |
416331ca XL |
1182 | let crate_mod = Res::Def( |
1183 | DefKind::Mod, | |
dfeec247 | 1184 | DefId { krate: crate_id, index: CRATE_DEF_INDEX }, |
416331ca XL |
1185 | ); |
1186 | ||
1187 | if filter_fn(crate_mod) { | |
1188 | Some(TypoSuggestion::from_res(ident.name, crate_mod)) | |
1189 | } else { | |
1190 | None | |
1191 | } | |
3dfed10e XL |
1192 | }, |
1193 | ) | |
416331ca XL |
1194 | })); |
1195 | ||
1196 | if let Some(prelude) = self.r.prelude { | |
e1599b0c | 1197 | self.r.add_module_candidates(prelude, &mut names, &filter_fn); |
416331ca XL |
1198 | } |
1199 | } | |
1200 | break; | |
1201 | } | |
1202 | } | |
1203 | } | |
1204 | // Add primitive types to the mix | |
1205 | if filter_fn(Res::PrimTy(PrimTy::Bool)) { | |
1206 | names.extend( | |
1207 | self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| { | |
1208 | TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty)) | |
dfeec247 | 1209 | }), |
416331ca XL |
1210 | ) |
1211 | } | |
1212 | } else { | |
1213 | // Search in module. | |
1214 | let mod_path = &path[..path.len() - 1]; | |
dfeec247 XL |
1215 | if let PathResult::Module(module) = |
1216 | self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) | |
1217 | { | |
416331ca | 1218 | if let ModuleOrUniformRoot::Module(module) = module { |
e1599b0c | 1219 | self.r.add_module_candidates(module, &mut names, &filter_fn); |
416331ca XL |
1220 | } |
1221 | } | |
1222 | } | |
1223 | ||
1224 | let name = path[path.len() - 1].ident.name; | |
1225 | // Make sure error reporting is deterministic. | |
1226 | names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str()); | |
1227 | ||
1228 | match find_best_match_for_name( | |
fc512014 | 1229 | &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(), |
3dfed10e | 1230 | name, |
416331ca XL |
1231 | None, |
1232 | ) { | |
dfeec247 XL |
1233 | Some(found) if found != name => { |
1234 | names.into_iter().find(|suggestion| suggestion.candidate == found) | |
1235 | } | |
416331ca XL |
1236 | _ => None, |
1237 | } | |
1238 | } | |
1239 | ||
1240 | /// Only used in a specific case of type ascription suggestions | |
1241 | fn get_colon_suggestion_span(&self, start: Span) -> Span { | |
74b04a01 XL |
1242 | let sm = self.r.session.source_map(); |
1243 | start.to(sm.next_point(start)) | |
416331ca XL |
1244 | } |
1245 | ||
3dfed10e | 1246 | fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) -> bool { |
74b04a01 XL |
1247 | let sm = self.r.session.source_map(); |
1248 | let base_snippet = sm.span_to_snippet(base_span); | |
3dfed10e XL |
1249 | if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() { |
1250 | if let Ok(snippet) = sm.span_to_snippet(sp) { | |
1251 | let len = snippet.trim_end().len() as u32; | |
1252 | if snippet.trim() == ":" { | |
1253 | let colon_sp = | |
1254 | sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len)); | |
1255 | let mut show_label = true; | |
1256 | if sm.is_multiline(sp) { | |
1257 | err.span_suggestion_short( | |
1258 | colon_sp, | |
1259 | "maybe you meant to write `;` here", | |
1260 | ";".to_string(), | |
1261 | Applicability::MaybeIncorrect, | |
1262 | ); | |
1263 | } else { | |
1264 | let after_colon_sp = | |
1265 | self.get_colon_suggestion_span(colon_sp.shrink_to_hi()); | |
1266 | if snippet.len() == 1 { | |
1267 | // `foo:bar` | |
1268 | err.span_suggestion( | |
1269 | colon_sp, | |
1270 | "maybe you meant to write a path separator here", | |
1271 | "::".to_string(), | |
416331ca XL |
1272 | Applicability::MaybeIncorrect, |
1273 | ); | |
3dfed10e XL |
1274 | show_label = false; |
1275 | if !self | |
1276 | .r | |
1277 | .session | |
1278 | .parse_sess | |
1279 | .type_ascription_path_suggestions | |
1280 | .borrow_mut() | |
1281 | .insert(colon_sp) | |
416331ca | 1282 | { |
3dfed10e | 1283 | err.delay_as_bug(); |
416331ca | 1284 | } |
3dfed10e XL |
1285 | } |
1286 | if let Ok(base_snippet) = base_snippet { | |
1287 | let mut sp = after_colon_sp; | |
1288 | for _ in 0..100 { | |
1289 | // Try to find an assignment | |
1290 | sp = sm.next_point(sp); | |
1291 | let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp))); | |
1292 | match snippet { | |
1293 | Ok(ref x) if x.as_str() == "=" => { | |
1294 | err.span_suggestion( | |
1295 | base_span, | |
1296 | "maybe you meant to write an assignment here", | |
1297 | format!("let {}", base_snippet), | |
1298 | Applicability::MaybeIncorrect, | |
1299 | ); | |
1300 | show_label = false; | |
1301 | break; | |
416331ca | 1302 | } |
3dfed10e XL |
1303 | Ok(ref x) if x.as_str() == "\n" => break, |
1304 | Err(_) => break, | |
1305 | Ok(_) => {} | |
416331ca XL |
1306 | } |
1307 | } | |
1308 | } | |
416331ca | 1309 | } |
3dfed10e XL |
1310 | if show_label { |
1311 | err.span_label( | |
1312 | base_span, | |
1313 | "expecting a type here because of type ascription", | |
1314 | ); | |
1315 | } | |
1316 | return show_label; | |
416331ca XL |
1317 | } |
1318 | } | |
1319 | } | |
3dfed10e | 1320 | false |
416331ca XL |
1321 | } |
1322 | ||
1323 | fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> { | |
1324 | let mut result = None; | |
1325 | let mut seen_modules = FxHashSet::default(); | |
1326 | let mut worklist = vec![(self.r.graph_root, Vec::new())]; | |
1327 | ||
1328 | while let Some((in_module, path_segments)) = worklist.pop() { | |
1329 | // abort if the module is already found | |
dfeec247 XL |
1330 | if result.is_some() { |
1331 | break; | |
1332 | } | |
416331ca | 1333 | |
e74abb32 | 1334 | in_module.for_each_child(self.r, |_, ident, _, name_binding| { |
416331ca XL |
1335 | // abort if the module is already found or if name_binding is private external |
1336 | if result.is_some() || !name_binding.vis.is_visible_locally() { | |
dfeec247 | 1337 | return; |
416331ca XL |
1338 | } |
1339 | if let Some(module) = name_binding.module() { | |
1340 | // form the path | |
1341 | let mut path_segments = path_segments.clone(); | |
1342 | path_segments.push(ast::PathSegment::from_ident(ident)); | |
1343 | let module_def_id = module.def_id().unwrap(); | |
1344 | if module_def_id == def_id { | |
1b1a35ee XL |
1345 | let path = |
1346 | Path { span: name_binding.span, segments: path_segments, tokens: None }; | |
f9f354fc XL |
1347 | result = Some(( |
1348 | module, | |
f035d41b XL |
1349 | ImportSuggestion { |
1350 | did: Some(def_id), | |
1351 | descr: "module", | |
1352 | path, | |
1353 | accessible: true, | |
1354 | }, | |
f9f354fc | 1355 | )); |
416331ca XL |
1356 | } else { |
1357 | // add the module to the lookup | |
1358 | if seen_modules.insert(module_def_id) { | |
1359 | worklist.push((module, path_segments)); | |
1360 | } | |
1361 | } | |
1362 | } | |
1363 | }); | |
1364 | } | |
1365 | ||
1366 | result | |
1367 | } | |
1368 | ||
29967ef6 | 1369 | fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> { |
416331ca | 1370 | self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| { |
416331ca | 1371 | let mut variants = Vec::new(); |
e74abb32 | 1372 | enum_module.for_each_child(self.r, |_, ident, _, name_binding| { |
29967ef6 | 1373 | if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() { |
416331ca XL |
1374 | let mut segms = enum_import_suggestion.path.segments.clone(); |
1375 | segms.push(ast::PathSegment::from_ident(ident)); | |
29967ef6 XL |
1376 | let path = Path { span: name_binding.span, segments: segms, tokens: None }; |
1377 | variants.push((path, def_id, kind)); | |
416331ca XL |
1378 | } |
1379 | }); | |
1380 | variants | |
1381 | }) | |
1382 | } | |
dfeec247 | 1383 | |
29967ef6 XL |
1384 | /// Adds a suggestion for using an enum's variant when an enum is used instead. |
1385 | fn suggest_using_enum_variant( | |
1386 | &mut self, | |
1387 | err: &mut DiagnosticBuilder<'a>, | |
1388 | source: PathSource<'_>, | |
1389 | def_id: DefId, | |
1390 | span: Span, | |
1391 | ) { | |
1392 | let variants = match self.collect_enum_ctors(def_id) { | |
1393 | Some(variants) => variants, | |
1394 | None => { | |
1395 | err.note("you might have meant to use one of the enum's variants"); | |
1396 | return; | |
1397 | } | |
1398 | }; | |
1399 | ||
1400 | let suggest_only_tuple_variants = | |
1401 | matches!(source, PathSource::TupleStruct(..)) || source.is_call(); | |
1402 | if suggest_only_tuple_variants { | |
1403 | // Suggest only tuple variants regardless of whether they have fields and do not | |
1404 | // suggest path with added parenthesis. | |
1405 | let mut suggestable_variants = variants | |
1406 | .iter() | |
1407 | .filter(|(.., kind)| *kind == CtorKind::Fn) | |
1408 | .map(|(variant, ..)| path_names_to_string(variant)) | |
1409 | .collect::<Vec<_>>(); | |
1410 | ||
1411 | let non_suggestable_variant_count = variants.len() - suggestable_variants.len(); | |
1412 | ||
1413 | let source_msg = if source.is_call() { | |
1414 | "to construct" | |
1415 | } else if matches!(source, PathSource::TupleStruct(..)) { | |
1416 | "to match against" | |
1417 | } else { | |
1418 | unreachable!() | |
1419 | }; | |
1420 | ||
1421 | if !suggestable_variants.is_empty() { | |
1422 | let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 { | |
1423 | format!("try {} the enum's variant", source_msg) | |
1424 | } else { | |
1425 | format!("try {} one of the enum's variants", source_msg) | |
1426 | }; | |
1427 | ||
1428 | err.span_suggestions( | |
1429 | span, | |
1430 | &msg, | |
1431 | suggestable_variants.drain(..), | |
1432 | Applicability::MaybeIncorrect, | |
1433 | ); | |
1434 | } | |
1435 | ||
1436 | // If the enum has no tuple variants.. | |
1437 | if non_suggestable_variant_count == variants.len() { | |
1438 | err.help(&format!("the enum has no tuple variants {}", source_msg)); | |
1439 | } | |
1440 | ||
1441 | // If there are also non-tuple variants.. | |
1442 | if non_suggestable_variant_count == 1 { | |
1443 | err.help(&format!( | |
1444 | "you might have meant {} the enum's non-tuple variant", | |
1445 | source_msg | |
1446 | )); | |
1447 | } else if non_suggestable_variant_count >= 1 { | |
1448 | err.help(&format!( | |
1449 | "you might have meant {} one of the enum's non-tuple variants", | |
1450 | source_msg | |
1451 | )); | |
1452 | } | |
1453 | } else { | |
1454 | let needs_placeholder = |def_id: DefId, kind: CtorKind| { | |
1455 | let has_no_fields = | |
1456 | self.r.field_names.get(&def_id).map(|f| f.is_empty()).unwrap_or(false); | |
1457 | match kind { | |
1458 | CtorKind::Const => false, | |
1459 | CtorKind::Fn | CtorKind::Fictive if has_no_fields => false, | |
1460 | _ => true, | |
1461 | } | |
1462 | }; | |
1463 | ||
1464 | let mut suggestable_variants = variants | |
1465 | .iter() | |
1466 | .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind)) | |
1467 | .map(|(variant, _, kind)| (path_names_to_string(variant), kind)) | |
1468 | .map(|(variant, kind)| match kind { | |
1469 | CtorKind::Const => variant, | |
1470 | CtorKind::Fn => format!("({}())", variant), | |
1471 | CtorKind::Fictive => format!("({} {{}})", variant), | |
1472 | }) | |
1473 | .collect::<Vec<_>>(); | |
1474 | ||
1475 | if !suggestable_variants.is_empty() { | |
1476 | let msg = if suggestable_variants.len() == 1 { | |
1477 | "you might have meant to use the following enum variant" | |
1478 | } else { | |
1479 | "you might have meant to use one of the following enum variants" | |
1480 | }; | |
1481 | ||
1482 | err.span_suggestions( | |
1483 | span, | |
1484 | msg, | |
1485 | suggestable_variants.drain(..), | |
1486 | Applicability::MaybeIncorrect, | |
1487 | ); | |
1488 | } | |
1489 | ||
1490 | let mut suggestable_variants_with_placeholders = variants | |
1491 | .iter() | |
1492 | .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind)) | |
1493 | .map(|(variant, _, kind)| (path_names_to_string(variant), kind)) | |
1494 | .filter_map(|(variant, kind)| match kind { | |
1495 | CtorKind::Fn => Some(format!("({}(/* fields */))", variant)), | |
1496 | CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)), | |
1497 | _ => None, | |
1498 | }) | |
1499 | .collect::<Vec<_>>(); | |
1500 | ||
1501 | if !suggestable_variants_with_placeholders.is_empty() { | |
1502 | let msg = match ( | |
1503 | suggestable_variants.is_empty(), | |
1504 | suggestable_variants_with_placeholders.len(), | |
1505 | ) { | |
1506 | (true, 1) => "the following enum variant is available", | |
1507 | (true, _) => "the following enum variants are available", | |
1508 | (false, 1) => "alternatively, the following enum variant is available", | |
1509 | (false, _) => "alternatively, the following enum variants are also available", | |
1510 | }; | |
1511 | ||
1512 | err.span_suggestions( | |
1513 | span, | |
1514 | msg, | |
1515 | suggestable_variants_with_placeholders.drain(..), | |
1516 | Applicability::HasPlaceholders, | |
1517 | ); | |
1518 | } | |
1519 | }; | |
1520 | ||
1521 | if def_id.is_local() { | |
1522 | if let Some(span) = self.def_span(def_id) { | |
1523 | err.span_note(span, "the enum is defined here"); | |
1524 | } | |
1525 | } | |
1526 | } | |
1527 | ||
dfeec247 XL |
1528 | crate fn report_missing_type_error( |
1529 | &self, | |
1530 | path: &[Segment], | |
1531 | ) -> Option<(Span, &'static str, String, Applicability)> { | |
f035d41b XL |
1532 | let (ident, span) = match path { |
1533 | [segment] if !segment.has_generic_args => { | |
1534 | (segment.ident.to_string(), segment.ident.span) | |
1535 | } | |
dfeec247 XL |
1536 | _ => return None, |
1537 | }; | |
f035d41b XL |
1538 | let mut iter = ident.chars().map(|c| c.is_uppercase()); |
1539 | let single_uppercase_char = | |
1540 | matches!(iter.next(), Some(true)) && matches!(iter.next(), None); | |
1541 | if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char { | |
1542 | return None; | |
1543 | } | |
1544 | match (self.diagnostic_metadata.current_item, single_uppercase_char) { | |
1545 | (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _) if ident.name == sym::main => { | |
dfeec247 XL |
1546 | // Ignore `fn main()` as we don't want to suggest `fn main<T>()` |
1547 | } | |
f035d41b XL |
1548 | ( |
1549 | Some(Item { | |
1550 | kind: | |
1551 | kind @ ItemKind::Fn(..) | |
1552 | | kind @ ItemKind::Enum(..) | |
1553 | | kind @ ItemKind::Struct(..) | |
1554 | | kind @ ItemKind::Union(..), | |
1555 | .. | |
1556 | }), | |
1557 | true, | |
1558 | ) | |
1559 | | (Some(Item { kind, .. }), false) => { | |
dfeec247 XL |
1560 | // Likely missing type parameter. |
1561 | if let Some(generics) = kind.generics() { | |
f035d41b XL |
1562 | if span.overlaps(generics.span) { |
1563 | // Avoid the following: | |
1564 | // error[E0405]: cannot find trait `A` in this scope | |
1565 | // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL | |
1566 | // | | |
1567 | // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore | |
1568 | // | ^- help: you might be missing a type parameter: `, A` | |
1569 | // | | | |
1570 | // | not found in this scope | |
1571 | return None; | |
1572 | } | |
dfeec247 XL |
1573 | let msg = "you might be missing a type parameter"; |
1574 | let (span, sugg) = if let [.., param] = &generics.params[..] { | |
1575 | let span = if let [.., bound] = ¶m.bounds[..] { | |
1576 | bound.span() | |
1577 | } else { | |
1578 | param.ident.span | |
1579 | }; | |
1580 | (span, format!(", {}", ident)) | |
1581 | } else { | |
1582 | (generics.span, format!("<{}>", ident)) | |
1583 | }; | |
1584 | // Do not suggest if this is coming from macro expansion. | |
1585 | if !span.from_expansion() { | |
1586 | return Some(( | |
1587 | span.shrink_to_hi(), | |
1588 | msg, | |
1589 | sugg, | |
1590 | Applicability::MaybeIncorrect, | |
1591 | )); | |
1592 | } | |
1593 | } | |
1594 | } | |
1595 | _ => {} | |
1596 | } | |
1597 | None | |
1598 | } | |
f035d41b XL |
1599 | |
1600 | /// Given the target `label`, search the `rib_index`th label rib for similarly named labels, | |
1601 | /// optionally returning the closest match and whether it is reachable. | |
1602 | crate fn suggestion_for_label_in_rib( | |
1603 | &self, | |
1604 | rib_index: usize, | |
1605 | label: Ident, | |
1606 | ) -> Option<LabelSuggestion> { | |
1607 | // Are ribs from this `rib_index` within scope? | |
1608 | let within_scope = self.is_label_valid_from_rib(rib_index); | |
1609 | ||
1610 | let rib = &self.label_ribs[rib_index]; | |
1611 | let names = rib | |
1612 | .bindings | |
1613 | .iter() | |
1614 | .filter(|(id, _)| id.span.ctxt() == label.span.ctxt()) | |
fc512014 XL |
1615 | .map(|(id, _)| id.name) |
1616 | .collect::<Vec<Symbol>>(); | |
f035d41b | 1617 | |
fc512014 | 1618 | find_best_match_for_name(&names, label.name, None).map(|symbol| { |
f035d41b XL |
1619 | // Upon finding a similar name, get the ident that it was from - the span |
1620 | // contained within helps make a useful diagnostic. In addition, determine | |
1621 | // whether this candidate is within scope. | |
1622 | let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap(); | |
1623 | (*ident, within_scope) | |
1624 | }) | |
1625 | } | |
416331ca | 1626 | } |
74b04a01 XL |
1627 | |
1628 | impl<'tcx> LifetimeContext<'_, 'tcx> { | |
1629 | crate fn report_missing_lifetime_specifiers( | |
1630 | &self, | |
1631 | span: Span, | |
1632 | count: usize, | |
1633 | ) -> DiagnosticBuilder<'tcx> { | |
1634 | struct_span_err!( | |
1635 | self.tcx.sess, | |
1636 | span, | |
1637 | E0106, | |
1638 | "missing lifetime specifier{}", | |
1639 | pluralize!(count) | |
1640 | ) | |
1641 | } | |
1642 | ||
1643 | crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) { | |
1644 | let mut err = struct_span_err!( | |
1645 | self.tcx.sess, | |
1646 | lifetime_ref.span, | |
1647 | E0261, | |
1648 | "use of undeclared lifetime name `{}`", | |
1649 | lifetime_ref | |
1650 | ); | |
1651 | err.span_label(lifetime_ref.span, "undeclared lifetime"); | |
f035d41b | 1652 | let mut suggests_in_band = false; |
74b04a01 XL |
1653 | for missing in &self.missing_named_lifetime_spots { |
1654 | match missing { | |
1655 | MissingLifetimeSpot::Generics(generics) => { | |
1656 | let (span, sugg) = if let Some(param) = | |
1657 | generics.params.iter().find(|p| match p.kind { | |
1658 | hir::GenericParamKind::Type { | |
1659 | synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), | |
1660 | .. | |
1661 | } => false, | |
6c58768f XL |
1662 | hir::GenericParamKind::Lifetime { |
1663 | kind: hir::LifetimeParamKind::Elided, | |
1664 | } => false, | |
74b04a01 XL |
1665 | _ => true, |
1666 | }) { | |
1667 | (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref)) | |
1668 | } else { | |
f035d41b | 1669 | suggests_in_band = true; |
74b04a01 XL |
1670 | (generics.span, format!("<{}>", lifetime_ref)) |
1671 | }; | |
1672 | err.span_suggestion( | |
1673 | span, | |
1674 | &format!("consider introducing lifetime `{}` here", lifetime_ref), | |
1675 | sugg, | |
1676 | Applicability::MaybeIncorrect, | |
1677 | ); | |
1678 | } | |
1679 | MissingLifetimeSpot::HigherRanked { span, span_type } => { | |
1680 | err.span_suggestion( | |
1681 | *span, | |
1682 | &format!( | |
1683 | "consider making the {} lifetime-generic with a new `{}` lifetime", | |
1684 | span_type.descr(), | |
1685 | lifetime_ref | |
1686 | ), | |
1687 | span_type.suggestion(&lifetime_ref.to_string()), | |
1688 | Applicability::MaybeIncorrect, | |
1689 | ); | |
1690 | err.note( | |
1691 | "for more information on higher-ranked polymorphism, visit \ | |
1692 | https://doc.rust-lang.org/nomicon/hrtb.html", | |
1693 | ); | |
1694 | } | |
3dfed10e | 1695 | _ => {} |
74b04a01 XL |
1696 | } |
1697 | } | |
fc512014 | 1698 | if self.tcx.sess.is_nightly_build() |
f035d41b XL |
1699 | && !self.tcx.features().in_band_lifetimes |
1700 | && suggests_in_band | |
1701 | { | |
1702 | err.help( | |
1703 | "if you want to experiment with in-band lifetime bindings, \ | |
1704 | add `#![feature(in_band_lifetimes)]` to the crate attributes", | |
1705 | ); | |
1706 | } | |
74b04a01 XL |
1707 | err.emit(); |
1708 | } | |
1709 | ||
3dfed10e XL |
1710 | // FIXME(const_generics): This patches over a ICE caused by non-'static lifetimes in const |
1711 | // generics. We are disallowing this until we can decide on how we want to handle non-'static | |
1712 | // lifetimes in const generics. See issue #74052 for discussion. | |
1713 | crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) { | |
1714 | let mut err = struct_span_err!( | |
1715 | self.tcx.sess, | |
1716 | lifetime_ref.span, | |
1717 | E0771, | |
1718 | "use of non-static lifetime `{}` in const generic", | |
1719 | lifetime_ref | |
1720 | ); | |
1721 | err.note( | |
1722 | "for more information, see issue #74052 \ | |
1723 | <https://github.com/rust-lang/rust/issues/74052>", | |
1724 | ); | |
1725 | err.emit(); | |
1726 | } | |
1727 | ||
74b04a01 XL |
1728 | crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool { |
1729 | if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res { | |
1730 | if [ | |
1731 | self.tcx.lang_items().fn_once_trait(), | |
1732 | self.tcx.lang_items().fn_trait(), | |
1733 | self.tcx.lang_items().fn_mut_trait(), | |
1734 | ] | |
1735 | .contains(&Some(did)) | |
1736 | { | |
1737 | let (span, span_type) = match &trait_ref.bound_generic_params { | |
1738 | [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty), | |
1739 | [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail), | |
1740 | }; | |
1741 | self.missing_named_lifetime_spots | |
1742 | .push(MissingLifetimeSpot::HigherRanked { span, span_type }); | |
1743 | return true; | |
1744 | } | |
1745 | }; | |
1746 | false | |
1747 | } | |
1748 | ||
1749 | crate fn add_missing_lifetime_specifiers_label( | |
1750 | &self, | |
1751 | err: &mut DiagnosticBuilder<'_>, | |
1752 | span: Span, | |
1753 | count: usize, | |
3dfed10e XL |
1754 | lifetime_names: &FxHashSet<Symbol>, |
1755 | lifetime_spans: Vec<Span>, | |
74b04a01 XL |
1756 | params: &[ElisionFailureInfo], |
1757 | ) { | |
f9f354fc | 1758 | let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok(); |
74b04a01 | 1759 | |
f9f354fc XL |
1760 | err.span_label( |
1761 | span, | |
1762 | &format!( | |
1763 | "expected {} lifetime parameter{}", | |
1764 | if count == 1 { "named".to_string() } else { count.to_string() }, | |
1765 | pluralize!(count) | |
1766 | ), | |
1767 | ); | |
1768 | ||
3dfed10e XL |
1769 | let suggest_existing = |err: &mut DiagnosticBuilder<'_>, |
1770 | name: &str, | |
1771 | formatter: &dyn Fn(&str) -> String| { | |
1772 | if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) = | |
1773 | self.missing_named_lifetime_spots.iter().rev().next() | |
1774 | { | |
1775 | // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest | |
1776 | // using `'a`, but also introduce the concept of HRLTs by suggesting | |
1777 | // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404) | |
1778 | let mut introduce_suggestion = vec![]; | |
1779 | ||
1780 | let a_to_z_repeat_n = |n| { | |
1781 | (b'a'..=b'z').map(move |c| { | |
1782 | let mut s = '\''.to_string(); | |
1783 | s.extend(std::iter::repeat(char::from(c)).take(n)); | |
1784 | s | |
1785 | }) | |
1786 | }; | |
1787 | ||
1788 | // If all single char lifetime names are present, we wrap around and double the chars. | |
1789 | let lt_name = (1..) | |
1790 | .flat_map(a_to_z_repeat_n) | |
1791 | .find(|lt| !lifetime_names.contains(&Symbol::intern(<))) | |
1792 | .unwrap(); | |
1793 | let msg = format!( | |
1794 | "consider making the {} lifetime-generic with a new `{}` lifetime", | |
1795 | span_type.descr(), | |
1796 | lt_name, | |
1797 | ); | |
1798 | err.note( | |
1799 | "for more information on higher-ranked polymorphism, visit \ | |
1800 | https://doc.rust-lang.org/nomicon/hrtb.html", | |
1801 | ); | |
1802 | let for_sugg = span_type.suggestion(<_name); | |
1803 | for param in params { | |
1804 | if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) { | |
1805 | if snippet.starts_with('&') && !snippet.starts_with("&'") { | |
1806 | introduce_suggestion | |
1807 | .push((param.span, format!("&{} {}", lt_name, &snippet[1..]))); | |
1b1a35ee | 1808 | } else if let Some(stripped) = snippet.strip_prefix("&'_ ") { |
3dfed10e | 1809 | introduce_suggestion |
1b1a35ee | 1810 | .push((param.span, format!("&{} {}", lt_name, stripped))); |
3dfed10e XL |
1811 | } |
1812 | } | |
1813 | } | |
1b1a35ee | 1814 | introduce_suggestion.push((*for_span, for_sugg)); |
3dfed10e XL |
1815 | introduce_suggestion.push((span, formatter(<_name))); |
1816 | err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect); | |
1817 | } | |
1818 | ||
f9f354fc XL |
1819 | err.span_suggestion_verbose( |
1820 | span, | |
1821 | &format!("consider using the `{}` lifetime", lifetime_names.iter().next().unwrap()), | |
3dfed10e | 1822 | formatter(name), |
f9f354fc XL |
1823 | Applicability::MaybeIncorrect, |
1824 | ); | |
1825 | }; | |
1826 | let suggest_new = |err: &mut DiagnosticBuilder<'_>, sugg: &str| { | |
1827 | for missing in self.missing_named_lifetime_spots.iter().rev() { | |
1828 | let mut introduce_suggestion = vec![]; | |
1829 | let msg; | |
1830 | let should_break; | |
1831 | introduce_suggestion.push(match missing { | |
1832 | MissingLifetimeSpot::Generics(generics) => { | |
3dfed10e XL |
1833 | if generics.span == DUMMY_SP { |
1834 | // Account for malformed generics in the HIR. This shouldn't happen, | |
1835 | // but if we make a mistake elsewhere, mainly by keeping something in | |
1836 | // `missing_named_lifetime_spots` that we shouldn't, like associated | |
1837 | // `const`s or making a mistake in the AST lowering we would provide | |
1838 | // non-sensical suggestions. Guard against that by skipping these. | |
1839 | // (#74264) | |
1840 | continue; | |
1841 | } | |
f9f354fc XL |
1842 | msg = "consider introducing a named lifetime parameter".to_string(); |
1843 | should_break = true; | |
29967ef6 XL |
1844 | if let Some(param) = generics.params.iter().find(|p| { |
1845 | !matches!(p.kind, hir::GenericParamKind::Type { | |
f9f354fc XL |
1846 | synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), |
1847 | .. | |
29967ef6 | 1848 | }) |
f9f354fc XL |
1849 | }) { |
1850 | (param.span.shrink_to_lo(), "'a, ".to_string()) | |
1851 | } else { | |
1852 | (generics.span, "<'a>".to_string()) | |
74b04a01 XL |
1853 | } |
1854 | } | |
f9f354fc XL |
1855 | MissingLifetimeSpot::HigherRanked { span, span_type } => { |
1856 | msg = format!( | |
1857 | "consider making the {} lifetime-generic with a new `'a` lifetime", | |
1858 | span_type.descr(), | |
1859 | ); | |
1860 | should_break = false; | |
1861 | err.note( | |
1862 | "for more information on higher-ranked polymorphism, visit \ | |
1863 | https://doc.rust-lang.org/nomicon/hrtb.html", | |
1864 | ); | |
1865 | (*span, span_type.suggestion("'a")) | |
1866 | } | |
3dfed10e XL |
1867 | MissingLifetimeSpot::Static => { |
1868 | let (span, sugg) = match snippet.as_deref() { | |
1869 | Some("&") => (span.shrink_to_hi(), "'static ".to_owned()), | |
1870 | Some("'_") => (span, "'static".to_owned()), | |
1871 | Some(snippet) if !snippet.ends_with('>') => { | |
1872 | if snippet == "" { | |
1873 | ( | |
1874 | span, | |
1875 | std::iter::repeat("'static") | |
1876 | .take(count) | |
1877 | .collect::<Vec<_>>() | |
1878 | .join(", "), | |
1879 | ) | |
1880 | } else { | |
1881 | ( | |
1882 | span.shrink_to_hi(), | |
1883 | format!( | |
1884 | "<{}>", | |
1885 | std::iter::repeat("'static") | |
1886 | .take(count) | |
1887 | .collect::<Vec<_>>() | |
1888 | .join(", ") | |
1889 | ), | |
1890 | ) | |
1891 | } | |
1892 | } | |
1893 | _ => continue, | |
1894 | }; | |
1895 | err.span_suggestion_verbose( | |
1896 | span, | |
1897 | "consider using the `'static` lifetime", | |
1898 | sugg.to_string(), | |
1899 | Applicability::MaybeIncorrect, | |
1900 | ); | |
1901 | continue; | |
1902 | } | |
f9f354fc XL |
1903 | }); |
1904 | for param in params { | |
1905 | if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) { | |
1906 | if snippet.starts_with('&') && !snippet.starts_with("&'") { | |
1907 | introduce_suggestion | |
1908 | .push((param.span, format!("&'a {}", &snippet[1..]))); | |
29967ef6 XL |
1909 | } else if let Some(stripped) = snippet.strip_prefix("&'_ ") { |
1910 | introduce_suggestion.push((param.span, format!("&'a {}", &stripped))); | |
f9f354fc | 1911 | } |
74b04a01 XL |
1912 | } |
1913 | } | |
f9f354fc XL |
1914 | introduce_suggestion.push((span, sugg.to_string())); |
1915 | err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect); | |
1916 | if should_break { | |
1917 | break; | |
74b04a01 | 1918 | } |
f9f354fc XL |
1919 | } |
1920 | }; | |
1921 | ||
1b1a35ee | 1922 | let lifetime_names: Vec<_> = lifetime_names.iter().collect(); |
3dfed10e XL |
1923 | match (&lifetime_names[..], snippet.as_deref()) { |
1924 | ([name], Some("&")) => { | |
1925 | suggest_existing(err, &name.as_str()[..], &|name| format!("&{} ", name)); | |
f9f354fc | 1926 | } |
3dfed10e XL |
1927 | ([name], Some("'_")) => { |
1928 | suggest_existing(err, &name.as_str()[..], &|n| n.to_string()); | |
f9f354fc | 1929 | } |
3dfed10e XL |
1930 | ([name], Some("")) => { |
1931 | suggest_existing(err, &name.as_str()[..], &|n| format!("{}, ", n).repeat(count)); | |
f9f354fc | 1932 | } |
3dfed10e XL |
1933 | ([name], Some(snippet)) if !snippet.ends_with('>') => { |
1934 | let f = |name: &str| { | |
f9f354fc XL |
1935 | format!( |
1936 | "{}<{}>", | |
1937 | snippet, | |
1938 | std::iter::repeat(name.to_string()) | |
1939 | .take(count) | |
1940 | .collect::<Vec<_>>() | |
1941 | .join(", ") | |
3dfed10e XL |
1942 | ) |
1943 | }; | |
1944 | suggest_existing(err, &name.as_str()[..], &f); | |
f9f354fc | 1945 | } |
3dfed10e | 1946 | ([], Some("&")) if count == 1 => { |
f9f354fc XL |
1947 | suggest_new(err, "&'a "); |
1948 | } | |
3dfed10e | 1949 | ([], Some("'_")) if count == 1 => { |
f9f354fc XL |
1950 | suggest_new(err, "'a"); |
1951 | } | |
3dfed10e XL |
1952 | ([], Some(snippet)) if !snippet.ends_with('>') => { |
1953 | if snippet == "" { | |
1954 | // This happens when we have `type Bar<'a> = Foo<T>` where we point at the space | |
1955 | // before `T`. We will suggest `type Bar<'a> = Foo<'a, T>`. | |
1956 | suggest_new( | |
1957 | err, | |
1958 | &std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""), | |
1959 | ); | |
1960 | } else { | |
1961 | suggest_new( | |
1962 | err, | |
1963 | &format!( | |
1964 | "{}<{}>", | |
1965 | snippet, | |
1966 | std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", ") | |
1967 | ), | |
1968 | ); | |
1969 | } | |
f9f354fc | 1970 | } |
3dfed10e XL |
1971 | (lts, ..) if lts.len() > 1 => { |
1972 | err.span_note(lifetime_spans, "these named lifetimes are available to use"); | |
f9f354fc XL |
1973 | if Some("") == snippet.as_deref() { |
1974 | // This happens when we have `Foo<T>` where we point at the space before `T`, | |
1975 | // but this can be confusing so we give a suggestion with placeholders. | |
1976 | err.span_suggestion_verbose( | |
1977 | span, | |
1978 | "consider using one of the available lifetimes here", | |
1979 | "'lifetime, ".repeat(count), | |
1980 | Applicability::HasPlaceholders, | |
1981 | ); | |
74b04a01 XL |
1982 | } |
1983 | } | |
f9f354fc | 1984 | _ => {} |
74b04a01 XL |
1985 | } |
1986 | } | |
1b1a35ee XL |
1987 | |
1988 | /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics` so | |
1989 | /// this function will emit an error if `min_const_generics` is enabled, the body identified by | |
1990 | /// `body_id` is an anonymous constant and `lifetime_ref` is non-static. | |
1991 | crate fn maybe_emit_forbidden_non_static_lifetime_error( | |
1992 | &self, | |
1993 | body_id: hir::BodyId, | |
1994 | lifetime_ref: &'tcx hir::Lifetime, | |
1995 | ) { | |
1996 | let is_anon_const = matches!( | |
1997 | self.tcx.def_kind(self.tcx.hir().body_owner_def_id(body_id)), | |
1998 | hir::def::DefKind::AnonConst | |
1999 | ); | |
2000 | let is_allowed_lifetime = matches!( | |
2001 | lifetime_ref.name, | |
2002 | hir::LifetimeName::Implicit | hir::LifetimeName::Static | hir::LifetimeName::Underscore | |
2003 | ); | |
2004 | ||
2005 | if self.tcx.features().min_const_generics && is_anon_const && !is_allowed_lifetime { | |
2006 | feature_err( | |
2007 | &self.tcx.sess.parse_sess, | |
2008 | sym::const_generics, | |
2009 | lifetime_ref.span, | |
2010 | "a non-static lifetime is not allowed in a `const`", | |
2011 | ) | |
2012 | .emit(); | |
2013 | } | |
2014 | } | |
74b04a01 | 2015 | } |