1 use rustc_ast::expand::StrippedCfgItem;
2 use rustc_ast::ptr::P;
3 use rustc_ast::visit::{self, Visitor};
4 use rustc_ast::{self as ast, Crate, ItemKind, ModKind, NodeId, Path, CRATE_NODE_ID};
5 use rustc_ast::{MetaItemKind, NestedMetaItem};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_errors::{
9 pluralize, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan,
10 };
11 use rustc_errors::{struct_span_err, SuggestionStyle};
12 use rustc_feature::BUILTIN_ATTRIBUTES;
13 use rustc_hir::def::Namespace::{self, *};
14 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS};
15 use rustc_hir::def_id::{DefId, CRATE_DEF_ID};
16 use rustc_hir::PrimTy;
17 use rustc_middle::bug;
18 use rustc_middle::ty::TyCtxt;
19 use rustc_session::lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE;
20 use rustc_session::lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS;
21 use rustc_session::lint::BuiltinLintDiagnostics;
22 use rustc_session::Session;
23 use rustc_span::edit_distance::find_best_match_for_name;
24 use rustc_span::edition::Edition;
25 use rustc_span::hygiene::MacroKind;
26 use rustc_span::source_map::SourceMap;
27 use rustc_span::symbol::{kw, sym, Ident, Symbol};
28 use rustc_span::{BytePos, Span, SyntaxContext};
29 use thin_vec::ThinVec;
30
31 use crate::errors::{
32 AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion, ConsiderAddingADerive,
33 ExplicitUnsafeTraits,
34 };
35 use crate::imports::{Import, ImportKind};
36 use crate::late::{PatternSource, Rib};
37 use crate::path_names_to_string;
38 use crate::{errors as errs, BindingKey};
39 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize};
40 use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot};
41 use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
42 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet};
43 use crate::{Segment, UseError};
44
45 #[cfg(test)]
46 mod tests;
47
48 type Res = def::Res<ast::NodeId>;
49
50 /// A vector of spans and replacements, a message and applicability.
51 pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
52
53 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
54 /// similarly named label and whether or not it is reachable.
55 pub(crate) type LabelSuggestion = (Ident, bool);
56
57 #[derive(Debug)]
58 pub(crate) enum SuggestionTarget {
59 /// The target has a similar name as the name used by the programmer (probably a typo)
60 SimilarlyNamed,
61 /// The target is the only valid item that can be used in the corresponding context
62 SingleItem,
63 }
64
65 #[derive(Debug)]
66 pub(crate) struct TypoSuggestion {
67 pub candidate: Symbol,
68 /// The source location where the name is defined; None if the name is not defined
69 /// in source e.g. primitives
70 pub span: Option<Span>,
71 pub res: Res,
72 pub target: SuggestionTarget,
73 }
74
75 impl TypoSuggestion {
typo_from_ident(ident: Ident, res: Res) -> TypoSuggestion76 pub(crate) fn typo_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
77 Self {
78 candidate: ident.name,
79 span: Some(ident.span),
80 res,
81 target: SuggestionTarget::SimilarlyNamed,
82 }
83 }
typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion84 pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
85 Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
86 }
single_item_from_ident(ident: Ident, res: Res) -> TypoSuggestion87 pub(crate) fn single_item_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
88 Self {
89 candidate: ident.name,
90 span: Some(ident.span),
91 res,
92 target: SuggestionTarget::SingleItem,
93 }
94 }
95 }
96
97 /// A free importable items suggested in case of resolution failure.
98 #[derive(Debug, Clone)]
99 pub(crate) struct ImportSuggestion {
100 pub did: Option<DefId>,
101 pub descr: &'static str,
102 pub path: Path,
103 pub accessible: bool,
104 pub via_import: bool,
105 /// An extra note that should be issued if this item is suggested
106 pub note: Option<String>,
107 }
108
109 /// Adjust the impl span so that just the `impl` keyword is taken by removing
110 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
111 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
112 ///
113 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
114 /// parser. If you need to use this function or something similar, please consider updating the
115 /// `source_map` functions and this function to something more robust.
reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span116 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
117 let impl_span = sm.span_until_char(impl_span, '<');
118 sm.span_until_whitespace(impl_span)
119 }
120
121 impl<'a, 'tcx> Resolver<'a, 'tcx> {
report_errors(&mut self, krate: &Crate)122 pub(crate) fn report_errors(&mut self, krate: &Crate) {
123 self.report_with_use_injections(krate);
124
125 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
126 let msg = "macro-expanded `macro_export` macros from the current crate \
127 cannot be referred to by absolute paths";
128 self.lint_buffer.buffer_lint_with_diagnostic(
129 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
130 CRATE_NODE_ID,
131 span_use,
132 msg,
133 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
134 );
135 }
136
137 for ambiguity_error in &self.ambiguity_errors {
138 self.report_ambiguity_error(ambiguity_error);
139 }
140
141 let mut reported_spans = FxHashSet::default();
142 for error in std::mem::take(&mut self.privacy_errors) {
143 if reported_spans.insert(error.dedup_span) {
144 self.report_privacy_error(&error);
145 }
146 }
147 }
148
report_with_use_injections(&mut self, krate: &Crate)149 fn report_with_use_injections(&mut self, krate: &Crate) {
150 for UseError { mut err, candidates, def_id, instead, suggestion, path, is_call } in
151 self.use_injections.drain(..)
152 {
153 let (span, found_use) = if let Some(def_id) = def_id.as_local() {
154 UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id])
155 } else {
156 (None, FoundUse::No)
157 };
158
159 if !candidates.is_empty() {
160 show_candidates(
161 self.tcx,
162 &mut err,
163 span,
164 &candidates,
165 if instead { Instead::Yes } else { Instead::No },
166 found_use,
167 DiagnosticMode::Normal,
168 path,
169 "",
170 );
171 err.emit();
172 } else if let Some((span, msg, sugg, appl)) = suggestion {
173 err.span_suggestion_verbose(span, msg, sugg, appl);
174 err.emit();
175 } else if let [segment] = path.as_slice() && is_call {
176 err.stash(segment.ident.span, rustc_errors::StashKey::CallIntoMethod);
177 } else {
178 err.emit();
179 }
180 }
181 }
182
report_conflict( &mut self, parent: Module<'_>, ident: Ident, ns: Namespace, new_binding: NameBinding<'a>, old_binding: NameBinding<'a>, )183 pub(crate) fn report_conflict(
184 &mut self,
185 parent: Module<'_>,
186 ident: Ident,
187 ns: Namespace,
188 new_binding: NameBinding<'a>,
189 old_binding: NameBinding<'a>,
190 ) {
191 // Error on the second of two conflicting names
192 if old_binding.span.lo() > new_binding.span.lo() {
193 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
194 }
195
196 let container = match parent.kind {
197 // Avoid using TyCtxt::def_kind_descr in the resolver, because it
198 // indirectly *calls* the resolver, and would cause a query cycle.
199 ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
200 ModuleKind::Block => "block",
201 };
202
203 let old_noun = match old_binding.is_import_user_facing() {
204 true => "import",
205 false => "definition",
206 };
207
208 let new_participle = match new_binding.is_import_user_facing() {
209 true => "imported",
210 false => "defined",
211 };
212
213 let (name, span) =
214 (ident.name, self.tcx.sess.source_map().guess_head_span(new_binding.span));
215
216 if let Some(s) = self.name_already_seen.get(&name) {
217 if s == &span {
218 return;
219 }
220 }
221
222 let old_kind = match (ns, old_binding.module()) {
223 (ValueNS, _) => "value",
224 (MacroNS, _) => "macro",
225 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
226 (TypeNS, Some(module)) if module.is_normal() => "module",
227 (TypeNS, Some(module)) if module.is_trait() => "trait",
228 (TypeNS, _) => "type",
229 };
230
231 let msg = format!("the name `{}` is defined multiple times", name);
232
233 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
234 (true, true) => struct_span_err!(self.tcx.sess, span, E0259, "{}", msg),
235 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
236 true => struct_span_err!(self.tcx.sess, span, E0254, "{}", msg),
237 false => struct_span_err!(self.tcx.sess, span, E0260, "{}", msg),
238 },
239 _ => match (old_binding.is_import_user_facing(), new_binding.is_import_user_facing()) {
240 (false, false) => struct_span_err!(self.tcx.sess, span, E0428, "{}", msg),
241 (true, true) => struct_span_err!(self.tcx.sess, span, E0252, "{}", msg),
242 _ => struct_span_err!(self.tcx.sess, span, E0255, "{}", msg),
243 },
244 };
245
246 err.note(format!(
247 "`{}` must be defined only once in the {} namespace of this {}",
248 name,
249 ns.descr(),
250 container
251 ));
252
253 err.span_label(span, format!("`{}` re{} here", name, new_participle));
254 if !old_binding.span.is_dummy() && old_binding.span != span {
255 err.span_label(
256 self.tcx.sess.source_map().guess_head_span(old_binding.span),
257 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
258 );
259 }
260
261 // See https://github.com/rust-lang/rust/issues/32354
262 use NameBindingKind::Import;
263 let can_suggest = |binding: NameBinding<'_>, import: self::Import<'_>| {
264 !binding.span.is_dummy()
265 && !matches!(import.kind, ImportKind::MacroUse | ImportKind::MacroExport)
266 };
267 let import = match (&new_binding.kind, &old_binding.kind) {
268 // If there are two imports where one or both have attributes then prefer removing the
269 // import without attributes.
270 (Import { import: new, .. }, Import { import: old, .. })
271 if {
272 (new.has_attributes || old.has_attributes)
273 && can_suggest(old_binding, *old)
274 && can_suggest(new_binding, *new)
275 } =>
276 {
277 if old.has_attributes {
278 Some((*new, new_binding.span, true))
279 } else {
280 Some((*old, old_binding.span, true))
281 }
282 }
283 // Otherwise prioritize the new binding.
284 (Import { import, .. }, other) if can_suggest(new_binding, *import) => {
285 Some((*import, new_binding.span, other.is_import()))
286 }
287 (other, Import { import, .. }) if can_suggest(old_binding, *import) => {
288 Some((*import, old_binding.span, other.is_import()))
289 }
290 _ => None,
291 };
292
293 // Check if the target of the use for both bindings is the same.
294 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
295 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
296 let from_item =
297 self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item);
298 // Only suggest removing an import if both bindings are to the same def, if both spans
299 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
300 // been introduced by an item.
301 let should_remove_import = duplicate
302 && !has_dummy_span
303 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
304
305 match import {
306 Some((import, span, true)) if should_remove_import && import.is_nested() => {
307 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span)
308 }
309 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
310 // Simple case - remove the entire import. Due to the above match arm, this can
311 // only be a single use so just remove it entirely.
312 err.tool_only_span_suggestion(
313 import.use_span_with_attributes,
314 "remove unnecessary import",
315 "",
316 Applicability::MaybeIncorrect,
317 );
318 }
319 Some((import, span, _)) => {
320 self.add_suggestion_for_rename_of_use(&mut err, name, import, span)
321 }
322 _ => {}
323 }
324
325 err.emit();
326 self.name_already_seen.insert(name, span);
327 }
328
329 /// This function adds a suggestion to change the binding name of a new import that conflicts
330 /// with an existing import.
331 ///
332 /// ```text,ignore (diagnostic)
333 /// help: you can use `as` to change the binding name of the import
334 /// |
335 /// LL | use foo::bar as other_bar;
336 /// | ^^^^^^^^^^^^^^^^^^^^^
337 /// ```
add_suggestion_for_rename_of_use( &self, err: &mut Diagnostic, name: Symbol, import: Import<'_>, binding_span: Span, )338 fn add_suggestion_for_rename_of_use(
339 &self,
340 err: &mut Diagnostic,
341 name: Symbol,
342 import: Import<'_>,
343 binding_span: Span,
344 ) {
345 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
346 format!("Other{}", name)
347 } else {
348 format!("other_{}", name)
349 };
350
351 let mut suggestion = None;
352 match import.kind {
353 ImportKind::Single { type_ns_only: true, .. } => {
354 suggestion = Some(format!("self as {}", suggested_name))
355 }
356 ImportKind::Single { source, .. } => {
357 if let Some(pos) =
358 source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
359 {
360 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(binding_span) {
361 if pos <= snippet.len() {
362 suggestion = Some(format!(
363 "{} as {}{}",
364 &snippet[..pos],
365 suggested_name,
366 if snippet.ends_with(';') { ";" } else { "" }
367 ))
368 }
369 }
370 }
371 }
372 ImportKind::ExternCrate { source, target, .. } => {
373 suggestion = Some(format!(
374 "extern crate {} as {};",
375 source.unwrap_or(target.name),
376 suggested_name,
377 ))
378 }
379 _ => unreachable!(),
380 }
381
382 if let Some(suggestion) = suggestion {
383 err.subdiagnostic(ChangeImportBindingSuggestion { span: binding_span, suggestion });
384 } else {
385 err.subdiagnostic(ChangeImportBinding { span: binding_span });
386 }
387 }
388
389 /// This function adds a suggestion to remove an unnecessary binding from an import that is
390 /// nested. In the following example, this function will be invoked to remove the `a` binding
391 /// in the second use statement:
392 ///
393 /// ```ignore (diagnostic)
394 /// use issue_52891::a;
395 /// use issue_52891::{d, a, e};
396 /// ```
397 ///
398 /// The following suggestion will be added:
399 ///
400 /// ```ignore (diagnostic)
401 /// use issue_52891::{d, a, e};
402 /// ^-- help: remove unnecessary import
403 /// ```
404 ///
405 /// If the nested use contains only one import then the suggestion will remove the entire
406 /// line.
407 ///
408 /// It is expected that the provided import is nested - this isn't checked by the
409 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
410 /// as characters expected by span manipulations won't be present.
add_suggestion_for_duplicate_nested_use( &self, err: &mut Diagnostic, import: Import<'_>, binding_span: Span, )411 fn add_suggestion_for_duplicate_nested_use(
412 &self,
413 err: &mut Diagnostic,
414 import: Import<'_>,
415 binding_span: Span,
416 ) {
417 assert!(import.is_nested());
418 let message = "remove unnecessary import";
419
420 // Two examples will be used to illustrate the span manipulations we're doing:
421 //
422 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
423 // `a` and `import.use_span` is `issue_52891::{d, a, e};`.
424 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
425 // `a` and `import.use_span` is `issue_52891::{d, e, a};`.
426
427 let (found_closing_brace, span) =
428 find_span_of_binding_until_next_binding(self.tcx.sess, binding_span, import.use_span);
429
430 // If there was a closing brace then identify the span to remove any trailing commas from
431 // previous imports.
432 if found_closing_brace {
433 if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) {
434 err.tool_only_span_suggestion(span, message, "", Applicability::MaybeIncorrect);
435 } else {
436 // Remove the entire line if we cannot extend the span back, this indicates an
437 // `issue_52891::{self}` case.
438 err.span_suggestion(
439 import.use_span_with_attributes,
440 message,
441 "",
442 Applicability::MaybeIncorrect,
443 );
444 }
445
446 return;
447 }
448
449 err.span_suggestion(span, message, "", Applicability::MachineApplicable);
450 }
451
lint_if_path_starts_with_module( &mut self, finalize: Option<Finalize>, path: &[Segment], second_binding: Option<NameBinding<'_>>, )452 pub(crate) fn lint_if_path_starts_with_module(
453 &mut self,
454 finalize: Option<Finalize>,
455 path: &[Segment],
456 second_binding: Option<NameBinding<'_>>,
457 ) {
458 let Some(Finalize { node_id, root_span, .. }) = finalize else {
459 return;
460 };
461
462 let first_name = match path.get(0) {
463 // In the 2018 edition this lint is a hard error, so nothing to do
464 Some(seg) if seg.ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015() => {
465 seg.ident.name
466 }
467 _ => return,
468 };
469
470 // We're only interested in `use` paths which should start with
471 // `{{root}}` currently.
472 if first_name != kw::PathRoot {
473 return;
474 }
475
476 match path.get(1) {
477 // If this import looks like `crate::...` it's already good
478 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
479 // Otherwise go below to see if it's an extern crate
480 Some(_) => {}
481 // If the path has length one (and it's `PathRoot` most likely)
482 // then we don't know whether we're gonna be importing a crate or an
483 // item in our crate. Defer this lint to elsewhere
484 None => return,
485 }
486
487 // If the first element of our path was actually resolved to an
488 // `ExternCrate` (also used for `crate::...`) then no need to issue a
489 // warning, this looks all good!
490 if let Some(binding) = second_binding {
491 if let NameBindingKind::Import { import, .. } = binding.kind {
492 // Careful: we still want to rewrite paths from renamed extern crates.
493 if let ImportKind::ExternCrate { source: None, .. } = import.kind {
494 return;
495 }
496 }
497 }
498
499 let diag = BuiltinLintDiagnostics::AbsPathWithModule(root_span);
500 self.lint_buffer.buffer_lint_with_diagnostic(
501 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
502 node_id,
503 root_span,
504 "absolute paths must start with `self`, `super`, \
505 `crate`, or an external crate name in the 2018 edition",
506 diag,
507 );
508 }
509
add_module_candidates( &mut self, module: Module<'a>, names: &mut Vec<TypoSuggestion>, filter_fn: &impl Fn(Res) -> bool, ctxt: Option<SyntaxContext>, )510 pub(crate) fn add_module_candidates(
511 &mut self,
512 module: Module<'a>,
513 names: &mut Vec<TypoSuggestion>,
514 filter_fn: &impl Fn(Res) -> bool,
515 ctxt: Option<SyntaxContext>,
516 ) {
517 for (key, resolution) in self.resolutions(module).borrow().iter() {
518 if let Some(binding) = resolution.borrow().binding {
519 let res = binding.res();
520 if filter_fn(res) && ctxt.map_or(true, |ctxt| ctxt == key.ident.span.ctxt()) {
521 names.push(TypoSuggestion::typo_from_ident(key.ident, res));
522 }
523 }
524 }
525 }
526
527 /// Combines an error with provided span and emits it.
528 ///
529 /// This takes the error provided, combines it with the span and any additional spans inside the
530 /// error and emits it.
report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>)531 pub(crate) fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
532 self.into_struct_error(span, resolution_error).emit();
533 }
534
into_struct_error( &mut self, span: Span, resolution_error: ResolutionError<'a>, ) -> DiagnosticBuilder<'_, ErrorGuaranteed>535 pub(crate) fn into_struct_error(
536 &mut self,
537 span: Span,
538 resolution_error: ResolutionError<'a>,
539 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
540 match resolution_error {
541 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
542 let mut err = struct_span_err!(
543 self.tcx.sess,
544 span,
545 E0401,
546 "can't use generic parameters from outer function",
547 );
548 err.span_label(span, "use of generic parameter from outer function");
549
550 let sm = self.tcx.sess.source_map();
551 let def_id = match outer_res {
552 Res::SelfTyParam { .. } => {
553 err.span_label(span, "can't use `Self` here");
554 return err;
555 }
556 Res::SelfTyAlias { alias_to: def_id, .. } => {
557 err.span_label(
558 reduce_impl_span_to_impl_keyword(sm, self.def_span(def_id)),
559 "`Self` type implicitly declared here, by this `impl`",
560 );
561 err.span_label(span, "use a type here instead");
562 return err;
563 }
564 Res::Def(DefKind::TyParam, def_id) => {
565 err.span_label(self.def_span(def_id), "type parameter from outer function");
566 def_id
567 }
568 Res::Def(DefKind::ConstParam, def_id) => {
569 err.span_label(
570 self.def_span(def_id),
571 "const parameter from outer function",
572 );
573 def_id
574 }
575 _ => {
576 bug!(
577 "GenericParamsFromOuterFunction should only be used with \
578 Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
579 DefKind::ConstParam"
580 );
581 }
582 };
583
584 if let HasGenericParams::Yes(span) = has_generic_params {
585 // Try to retrieve the span of the function signature and generate a new
586 // message with a local type or const parameter.
587 let sugg_msg = "try using a local generic parameter instead";
588 let name = self.tcx.item_name(def_id);
589 let (span, snippet) = if span.is_empty() {
590 let snippet = format!("<{}>", name);
591 (span, snippet)
592 } else {
593 let span = sm.span_through_char(span, '<').shrink_to_hi();
594 let snippet = format!("{}, ", name);
595 (span, snippet)
596 };
597 // Suggest the modification to the user
598 err.span_suggestion(span, sugg_msg, snippet, Applicability::MaybeIncorrect);
599 }
600
601 err
602 }
603 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
604 .tcx
605 .sess
606 .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
607 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
608 self.tcx.sess.create_err(errs::MethodNotMemberOfTrait {
609 span,
610 method,
611 trait_,
612 sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
613 span: method.span,
614 candidate: c,
615 }),
616 })
617 }
618 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
619 self.tcx.sess.create_err(errs::TypeNotMemberOfTrait {
620 span,
621 type_,
622 trait_,
623 sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
624 span: type_.span,
625 candidate: c,
626 }),
627 })
628 }
629 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
630 self.tcx.sess.create_err(errs::ConstNotMemberOfTrait {
631 span,
632 const_,
633 trait_,
634 sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
635 span: const_.span,
636 candidate: c,
637 }),
638 })
639 }
640 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
641 let BindingError { name, target, origin, could_be_path } = binding_error;
642
643 let target_sp = target.iter().copied().collect::<Vec<_>>();
644 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
645
646 let msp = MultiSpan::from_spans(target_sp.clone());
647 let mut err = struct_span_err!(
648 self.tcx.sess,
649 msp,
650 E0408,
651 "variable `{}` is not bound in all patterns",
652 name,
653 );
654 for sp in target_sp {
655 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
656 }
657 for sp in origin_sp {
658 err.span_label(sp, "variable not in all patterns");
659 }
660 if could_be_path {
661 let import_suggestions = self.lookup_import_candidates(
662 Ident::with_dummy_span(name),
663 Namespace::ValueNS,
664 &parent_scope,
665 &|res: Res| {
666 matches!(
667 res,
668 Res::Def(
669 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
670 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
671 | DefKind::Const
672 | DefKind::AssocConst,
673 _,
674 )
675 )
676 },
677 );
678
679 if import_suggestions.is_empty() {
680 let help_msg = format!(
681 "if you meant to match on a variant or a `const` item, consider \
682 making the path in the pattern qualified: `path::to::ModOrType::{}`",
683 name,
684 );
685 err.span_help(span, help_msg);
686 }
687 show_candidates(
688 self.tcx,
689 &mut err,
690 Some(span),
691 &import_suggestions,
692 Instead::No,
693 FoundUse::Yes,
694 DiagnosticMode::Pattern,
695 vec![],
696 "",
697 );
698 }
699 err
700 }
701 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
702 self.tcx.sess.create_err(errs::VariableBoundWithDifferentMode {
703 span,
704 first_binding_span,
705 variable_name,
706 })
707 }
708 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
709 .tcx
710 .sess
711 .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
712 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
713 .tcx
714 .sess
715 .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
716 ResolutionError::UndeclaredLabel { name, suggestion } => {
717 let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
718 {
719 // A reachable label with a similar name exists.
720 Some((ident, true)) => (
721 (
722 Some(errs::LabelWithSimilarNameReachable(ident.span)),
723 Some(errs::TryUsingSimilarlyNamedLabel {
724 span,
725 ident_name: ident.name,
726 }),
727 ),
728 None,
729 ),
730 // An unreachable label with a similar name exists.
731 Some((ident, false)) => (
732 (None, None),
733 Some(errs::UnreachableLabelWithSimilarNameExists {
734 ident_span: ident.span,
735 }),
736 ),
737 // No similarly-named labels exist.
738 None => ((None, None), None),
739 };
740 self.tcx.sess.create_err(errs::UndeclaredLabel {
741 span,
742 name,
743 sub_reachable,
744 sub_reachable_suggestion,
745 sub_unreachable,
746 })
747 }
748 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
749 // None of the suggestions below would help with a case like `use self`.
750 let (suggestion, mpart_suggestion) = if root {
751 (None, None)
752 } else {
753 // use foo::bar::self -> foo::bar
754 // use foo::bar::self as abc -> foo::bar as abc
755 let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
756
757 // use foo::bar::self -> foo::bar::{self}
758 // use foo::bar::self as abc -> foo::bar::{self as abc}
759 let mpart_suggestion = errs::SelfImportsOnlyAllowedWithinMultipartSuggestion {
760 multipart_start: span_with_rename.shrink_to_lo(),
761 multipart_end: span_with_rename.shrink_to_hi(),
762 };
763 (Some(suggestion), Some(mpart_suggestion))
764 };
765 self.tcx.sess.create_err(errs::SelfImportsOnlyAllowedWithin {
766 span,
767 suggestion,
768 mpart_suggestion,
769 })
770 }
771 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
772 self.tcx.sess.create_err(errs::SelfImportCanOnlyAppearOnceInTheList { span })
773 }
774 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => self
775 .tcx
776 .sess
777 .create_err(errs::SelfImportOnlyInImportListWithNonEmptyPrefix { span }),
778 ResolutionError::FailedToResolve { last_segment, label, suggestion, module } => {
779 let mut err =
780 struct_span_err!(self.tcx.sess, span, E0433, "failed to resolve: {}", &label);
781 err.span_label(span, label);
782
783 if let Some((suggestions, msg, applicability)) = suggestion {
784 if suggestions.is_empty() {
785 err.help(msg);
786 return err;
787 }
788 err.multipart_suggestion(msg, suggestions, applicability);
789 }
790
791 if let Some(ModuleOrUniformRoot::Module(module)) = module
792 && let Some(module) = module.opt_def_id()
793 && let Some(last_segment) = last_segment
794 {
795 self.find_cfg_stripped(&mut err, &last_segment, module);
796 }
797
798 err
799 }
800 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
801 self.tcx.sess.create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
802 }
803 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, suggestion, current) => {
804 // let foo =...
805 // ^^^ given this Span
806 // ------- get this Span to have an applicable suggestion
807
808 // edit:
809 // only do this if the const and usage of the non-constant value are on the same line
810 // the further the two are apart, the higher the chance of the suggestion being wrong
811
812 let sp = self
813 .tcx
814 .sess
815 .source_map()
816 .span_extend_to_prev_str(ident.span, current, true, false);
817
818 let ((with, with_label), without) = match sp {
819 Some(sp) if !self.tcx.sess.source_map().is_multiline(sp) => {
820 let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
821 (
822 (Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
823 span: sp,
824 ident,
825 suggestion,
826 current,
827 }), Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion {span})),
828 None,
829 )
830 }
831 _ => (
832 (None, None),
833 Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
834 ident_span: ident.span,
835 suggestion,
836 }),
837 ),
838 };
839
840 self.tcx.sess.create_err(errs::AttemptToUseNonConstantValueInConstant {
841 span,
842 with,
843 with_label,
844 without,
845 })
846 }
847 ResolutionError::BindingShadowsSomethingUnacceptable {
848 shadowing_binding,
849 name,
850 participle,
851 article,
852 shadowed_binding,
853 shadowed_binding_span,
854 } => self.tcx.sess.create_err(errs::BindingShadowsSomethingUnacceptable {
855 span,
856 shadowing_binding,
857 shadowed_binding,
858 article,
859 sub_suggestion: match (shadowing_binding, shadowed_binding) {
860 (
861 PatternSource::Match,
862 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
863 ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
864 _ => None,
865 },
866 shadowed_binding_span,
867 participle,
868 name,
869 }),
870 ResolutionError::ForwardDeclaredGenericParam => {
871 self.tcx.sess.create_err(errs::ForwardDeclaredGenericParam { span })
872 }
873 ResolutionError::ParamInTyOfConstParam { name, param_kind: is_type } => self
874 .tcx
875 .sess
876 .create_err(errs::ParamInTyOfConstParam { span, name, param_kind: is_type }),
877 ResolutionError::ParamInNonTrivialAnonConst { name, param_kind: is_type } => {
878 self.tcx.sess.create_err(errs::ParamInNonTrivialAnonConst {
879 span,
880 name,
881 param_kind: is_type,
882 help: self
883 .tcx
884 .sess
885 .is_nightly_build()
886 .then_some(errs::ParamInNonTrivialAnonConstHelp),
887 })
888 }
889 ResolutionError::ParamInEnumDiscriminant { name, param_kind: is_type } => self
890 .tcx
891 .sess
892 .create_err(errs::ParamInEnumDiscriminant { span, name, param_kind: is_type }),
893 ResolutionError::SelfInGenericParamDefault => {
894 self.tcx.sess.create_err(errs::SelfInGenericParamDefault { span })
895 }
896 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
897 let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
898 match suggestion {
899 // A reachable label with a similar name exists.
900 Some((ident, true)) => (
901 (
902 Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
903 Some(errs::UnreachableLabelSubSuggestion {
904 span,
905 // intentionally taking 'ident.name' instead of 'ident' itself, as this
906 // could be used in suggestion context
907 ident_name: ident.name,
908 }),
909 ),
910 None,
911 ),
912 // An unreachable label with a similar name exists.
913 Some((ident, false)) => (
914 (None, None),
915 Some(errs::UnreachableLabelSubLabelUnreachable {
916 ident_span: ident.span,
917 }),
918 ),
919 // No similarly-named labels exist.
920 None => ((None, None), None),
921 };
922 self.tcx.sess.create_err(errs::UnreachableLabel {
923 span,
924 name,
925 definition_span,
926 sub_suggestion,
927 sub_suggestion_label,
928 sub_unreachable_label,
929 })
930 }
931 ResolutionError::TraitImplMismatch {
932 name,
933 kind,
934 code,
935 trait_item_span,
936 trait_path,
937 } => {
938 let mut err = self.tcx.sess.struct_span_err_with_code(
939 span,
940 format!(
941 "item `{}` is an associated {}, which doesn't match its trait `{}`",
942 name, kind, trait_path,
943 ),
944 code,
945 );
946 err.span_label(span, "does not match trait");
947 err.span_label(trait_item_span, "item in trait");
948 err
949 }
950 ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
951 .tcx
952 .sess
953 .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
954 ResolutionError::InvalidAsmSym => {
955 self.tcx.sess.create_err(errs::InvalidAsmSym { span })
956 }
957 ResolutionError::LowercaseSelf => {
958 self.tcx.sess.create_err(errs::LowercaseSelf { span })
959 }
960 }
961 }
962
report_vis_error( &mut self, vis_resolution_error: VisResolutionError<'_>, ) -> ErrorGuaranteed963 pub(crate) fn report_vis_error(
964 &mut self,
965 vis_resolution_error: VisResolutionError<'_>,
966 ) -> ErrorGuaranteed {
967 match vis_resolution_error {
968 VisResolutionError::Relative2018(span, path) => {
969 self.tcx.sess.create_err(errs::Relative2018 {
970 span,
971 path_span: path.span,
972 // intentionally converting to String, as the text would also be used as
973 // in suggestion context
974 path_str: pprust::path_to_string(&path),
975 })
976 }
977 VisResolutionError::AncestorOnly(span) => {
978 self.tcx.sess.create_err(errs::AncestorOnly(span))
979 }
980 VisResolutionError::FailedToResolve(span, label, suggestion) => self.into_struct_error(
981 span,
982 ResolutionError::FailedToResolve {
983 last_segment: None,
984 label,
985 suggestion,
986 module: None,
987 },
988 ),
989 VisResolutionError::ExpectedFound(span, path_str, res) => {
990 self.tcx.sess.create_err(errs::ExpectedFound { span, res, path_str })
991 }
992 VisResolutionError::Indeterminate(span) => {
993 self.tcx.sess.create_err(errs::Indeterminate(span))
994 }
995 VisResolutionError::ModuleOnly(span) => {
996 self.tcx.sess.create_err(errs::ModuleOnly(span))
997 }
998 }
999 .emit()
1000 }
1001
1002 /// Lookup typo candidate in scope for a macro or import.
early_lookup_typo_candidate( &mut self, scope_set: ScopeSet<'a>, parent_scope: &ParentScope<'a>, ident: Ident, filter_fn: &impl Fn(Res) -> bool, ) -> Option<TypoSuggestion>1003 fn early_lookup_typo_candidate(
1004 &mut self,
1005 scope_set: ScopeSet<'a>,
1006 parent_scope: &ParentScope<'a>,
1007 ident: Ident,
1008 filter_fn: &impl Fn(Res) -> bool,
1009 ) -> Option<TypoSuggestion> {
1010 let mut suggestions = Vec::new();
1011 let ctxt = ident.span.ctxt();
1012 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
1013 match scope {
1014 Scope::DeriveHelpers(expn_id) => {
1015 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1016 if filter_fn(res) {
1017 suggestions.extend(
1018 this.helper_attrs
1019 .get(&expn_id)
1020 .into_iter()
1021 .flatten()
1022 .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
1023 );
1024 }
1025 }
1026 Scope::DeriveHelpersCompat => {
1027 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1028 if filter_fn(res) {
1029 for derive in parent_scope.derives {
1030 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1031 if let Ok((Some(ext), _)) = this.resolve_macro_path(
1032 derive,
1033 Some(MacroKind::Derive),
1034 parent_scope,
1035 false,
1036 false,
1037 ) {
1038 suggestions.extend(
1039 ext.helper_attrs
1040 .iter()
1041 .map(|name| TypoSuggestion::typo_from_name(*name, res)),
1042 );
1043 }
1044 }
1045 }
1046 }
1047 Scope::MacroRules(macro_rules_scope) => {
1048 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1049 let res = macro_rules_binding.binding.res();
1050 if filter_fn(res) {
1051 suggestions.push(TypoSuggestion::typo_from_ident(
1052 macro_rules_binding.ident,
1053 res,
1054 ))
1055 }
1056 }
1057 }
1058 Scope::CrateRoot => {
1059 let root_ident = Ident::new(kw::PathRoot, ident.span);
1060 let root_module = this.resolve_crate_root(root_ident);
1061 this.add_module_candidates(root_module, &mut suggestions, filter_fn, None);
1062 }
1063 Scope::Module(module, _) => {
1064 this.add_module_candidates(module, &mut suggestions, filter_fn, None);
1065 }
1066 Scope::MacroUsePrelude => {
1067 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1068 |(name, binding)| {
1069 let res = binding.res();
1070 filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1071 },
1072 ));
1073 }
1074 Scope::BuiltinAttrs => {
1075 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1076 if filter_fn(res) {
1077 suggestions.extend(
1078 BUILTIN_ATTRIBUTES
1079 .iter()
1080 .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1081 );
1082 }
1083 }
1084 Scope::ExternPrelude => {
1085 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1086 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1087 filter_fn(res).then_some(TypoSuggestion::typo_from_ident(*ident, res))
1088 }));
1089 }
1090 Scope::ToolPrelude => {
1091 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1092 suggestions.extend(
1093 this.registered_tools
1094 .iter()
1095 .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
1096 );
1097 }
1098 Scope::StdLibPrelude => {
1099 if let Some(prelude) = this.prelude {
1100 let mut tmp_suggestions = Vec::new();
1101 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1102 suggestions.extend(
1103 tmp_suggestions
1104 .into_iter()
1105 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
1106 );
1107 }
1108 }
1109 Scope::BuiltinTypes => {
1110 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1111 let res = Res::PrimTy(*prim_ty);
1112 filter_fn(res)
1113 .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1114 }))
1115 }
1116 }
1117
1118 None::<()>
1119 });
1120
1121 // Make sure error reporting is deterministic.
1122 suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1123
1124 match find_best_match_for_name(
1125 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1126 ident.name,
1127 None,
1128 ) {
1129 Some(found) if found != ident.name => {
1130 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1131 }
1132 _ => None,
1133 }
1134 }
1135
lookup_import_candidates_from_module<FilterFn>( &mut self, lookup_ident: Ident, namespace: Namespace, parent_scope: &ParentScope<'a>, start_module: Module<'a>, crate_name: Ident, filter_fn: FilterFn, ) -> Vec<ImportSuggestion> where FilterFn: Fn(Res) -> bool,1136 fn lookup_import_candidates_from_module<FilterFn>(
1137 &mut self,
1138 lookup_ident: Ident,
1139 namespace: Namespace,
1140 parent_scope: &ParentScope<'a>,
1141 start_module: Module<'a>,
1142 crate_name: Ident,
1143 filter_fn: FilterFn,
1144 ) -> Vec<ImportSuggestion>
1145 where
1146 FilterFn: Fn(Res) -> bool,
1147 {
1148 let mut candidates = Vec::new();
1149 let mut seen_modules = FxHashSet::default();
1150 let mut worklist = vec![(start_module, ThinVec::<ast::PathSegment>::new(), true)];
1151 let mut worklist_via_import = vec![];
1152
1153 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
1154 None => worklist_via_import.pop(),
1155 Some(x) => Some(x),
1156 } {
1157 let in_module_is_extern = !in_module.def_id().is_local();
1158 // We have to visit module children in deterministic order to avoid
1159 // instabilities in reported imports (#43552).
1160 in_module.for_each_child(self, |this, ident, ns, name_binding| {
1161 // avoid non-importable candidates
1162 if !name_binding.is_importable() {
1163 return;
1164 }
1165
1166 let child_accessible =
1167 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1168
1169 // do not venture inside inaccessible items of other crates
1170 if in_module_is_extern && !child_accessible {
1171 return;
1172 }
1173
1174 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1175
1176 // There is an assumption elsewhere that paths of variants are in the enum's
1177 // declaration and not imported. With this assumption, the variant component is
1178 // chopped and the rest of the path is assumed to be the enum's own path. For
1179 // errors where a variant is used as the type instead of the enum, this causes
1180 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1181 if via_import && name_binding.is_possibly_imported_variant() {
1182 return;
1183 }
1184
1185 // #90113: Do not count an inaccessible reexported item as a candidate.
1186 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
1187 if this.is_accessible_from(binding.vis, parent_scope.module)
1188 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1189 {
1190 return;
1191 }
1192 }
1193
1194 // collect results based on the filter function
1195 // avoid suggesting anything from the same module in which we are resolving
1196 // avoid suggesting anything with a hygienic name
1197 if ident.name == lookup_ident.name
1198 && ns == namespace
1199 && in_module != parent_scope.module
1200 && !ident.span.normalize_to_macros_2_0().from_expansion()
1201 {
1202 let res = name_binding.res();
1203 if filter_fn(res) {
1204 // create the path
1205 let mut segms = path_segments.clone();
1206 if lookup_ident.span.rust_2018() {
1207 // crate-local absolute paths start with `crate::` in edition 2018
1208 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1209 segms.insert(0, ast::PathSegment::from_ident(crate_name));
1210 }
1211
1212 segms.push(ast::PathSegment::from_ident(ident));
1213 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1214 let did = match res {
1215 Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1216 _ => res.opt_def_id(),
1217 };
1218
1219 if child_accessible {
1220 // Remove invisible match if exists
1221 if let Some(idx) = candidates
1222 .iter()
1223 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1224 {
1225 candidates.remove(idx);
1226 }
1227 }
1228
1229 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1230 // See if we're recommending TryFrom, TryInto, or FromIterator and add
1231 // a note about editions
1232 let note = if let Some(did) = did {
1233 let requires_note = !did.is_local()
1234 && this.tcx.get_attrs(did, sym::rustc_diagnostic_item).any(
1235 |attr| {
1236 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1237 .map(|x| Some(x))
1238 .contains(&attr.value_str())
1239 },
1240 );
1241
1242 requires_note.then(|| {
1243 format!(
1244 "'{}' is included in the prelude starting in Edition 2021",
1245 path_names_to_string(&path)
1246 )
1247 })
1248 } else {
1249 None
1250 };
1251
1252 candidates.push(ImportSuggestion {
1253 did,
1254 descr: res.descr(),
1255 path,
1256 accessible: child_accessible,
1257 note,
1258 via_import,
1259 });
1260 }
1261 }
1262 }
1263
1264 // collect submodules to explore
1265 if let Some(module) = name_binding.module() {
1266 // form the path
1267 let mut path_segments = path_segments.clone();
1268 path_segments.push(ast::PathSegment::from_ident(ident));
1269
1270 let is_extern_crate_that_also_appears_in_prelude =
1271 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
1272
1273 if !is_extern_crate_that_also_appears_in_prelude {
1274 // add the module to the lookup
1275 if seen_modules.insert(module.def_id()) {
1276 if via_import { &mut worklist_via_import } else { &mut worklist }
1277 .push((module, path_segments, child_accessible));
1278 }
1279 }
1280 }
1281 })
1282 }
1283
1284 // If only some candidates are accessible, take just them
1285 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1286 candidates.retain(|x| x.accessible)
1287 }
1288
1289 candidates
1290 }
1291
1292 /// When name resolution fails, this method can be used to look up candidate
1293 /// entities with the expected name. It allows filtering them using the
1294 /// supplied predicate (which should be used to only accept the types of
1295 /// definitions expected, e.g., traits). The lookup spans across all crates.
1296 ///
1297 /// N.B., the method does not look into imports, but this is not a problem,
1298 /// since we report the definitions (thus, the de-aliased imports).
lookup_import_candidates<FilterFn>( &mut self, lookup_ident: Ident, namespace: Namespace, parent_scope: &ParentScope<'a>, filter_fn: FilterFn, ) -> Vec<ImportSuggestion> where FilterFn: Fn(Res) -> bool,1299 pub(crate) fn lookup_import_candidates<FilterFn>(
1300 &mut self,
1301 lookup_ident: Ident,
1302 namespace: Namespace,
1303 parent_scope: &ParentScope<'a>,
1304 filter_fn: FilterFn,
1305 ) -> Vec<ImportSuggestion>
1306 where
1307 FilterFn: Fn(Res) -> bool,
1308 {
1309 let mut suggestions = self.lookup_import_candidates_from_module(
1310 lookup_ident,
1311 namespace,
1312 parent_scope,
1313 self.graph_root,
1314 Ident::with_dummy_span(kw::Crate),
1315 &filter_fn,
1316 );
1317
1318 if lookup_ident.span.rust_2018() {
1319 let extern_prelude_names = self.extern_prelude.clone();
1320 for (ident, _) in extern_prelude_names.into_iter() {
1321 if ident.span.from_expansion() {
1322 // Idents are adjusted to the root context before being
1323 // resolved in the extern prelude, so reporting this to the
1324 // user is no help. This skips the injected
1325 // `extern crate std` in the 2018 edition, which would
1326 // otherwise cause duplicate suggestions.
1327 continue;
1328 }
1329 let crate_id = self.crate_loader(|c| c.maybe_process_path_extern(ident.name));
1330 if let Some(crate_id) = crate_id {
1331 let crate_root = self.expect_module(crate_id.as_def_id());
1332 suggestions.extend(self.lookup_import_candidates_from_module(
1333 lookup_ident,
1334 namespace,
1335 parent_scope,
1336 crate_root,
1337 ident,
1338 &filter_fn,
1339 ));
1340 }
1341 }
1342 }
1343
1344 suggestions
1345 }
1346
unresolved_macro_suggestions( &mut self, err: &mut Diagnostic, macro_kind: MacroKind, parent_scope: &ParentScope<'a>, ident: Ident, krate: &Crate, )1347 pub(crate) fn unresolved_macro_suggestions(
1348 &mut self,
1349 err: &mut Diagnostic,
1350 macro_kind: MacroKind,
1351 parent_scope: &ParentScope<'a>,
1352 ident: Ident,
1353 krate: &Crate,
1354 ) {
1355 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1356 let suggestion = self.early_lookup_typo_candidate(
1357 ScopeSet::Macro(macro_kind),
1358 parent_scope,
1359 ident,
1360 is_expected,
1361 );
1362 self.add_typo_suggestion(err, suggestion, ident.span);
1363
1364 let import_suggestions =
1365 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1366 let (span, found_use) = match parent_scope.module.nearest_parent_mod().as_local() {
1367 Some(def_id) => UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id]),
1368 None => (None, FoundUse::No),
1369 };
1370 show_candidates(
1371 self.tcx,
1372 err,
1373 span,
1374 &import_suggestions,
1375 Instead::No,
1376 found_use,
1377 DiagnosticMode::Normal,
1378 vec![],
1379 "",
1380 );
1381
1382 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1383 err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1384 return;
1385 }
1386 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1387 err.subdiagnostic(AddedMacroUse);
1388 return;
1389 }
1390 if ident.name == kw::Default
1391 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1392 {
1393 let span = self.def_span(def_id);
1394 let source_map = self.tcx.sess.source_map();
1395 let head_span = source_map.guess_head_span(span);
1396 err.subdiagnostic(ConsiderAddingADerive {
1397 span: head_span.shrink_to_lo(),
1398 suggestion: format!("#[derive(Default)]\n")
1399 });
1400 }
1401 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1402 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1403 ident,
1404 ScopeSet::All(ns),
1405 &parent_scope,
1406 None,
1407 false,
1408 None,
1409 ) {
1410 let desc = match binding.res() {
1411 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1412 "a function-like macro".to_string()
1413 }
1414 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1415 format!("an attribute: `#[{}]`", ident)
1416 }
1417 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1418 format!("a derive macro: `#[derive({})]`", ident)
1419 }
1420 Res::ToolMod => {
1421 // Don't confuse the user with tool modules.
1422 continue;
1423 }
1424 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1425 "only a trait, without a derive macro".to_string()
1426 }
1427 res => format!(
1428 "{} {}, not {} {}",
1429 res.article(),
1430 res.descr(),
1431 macro_kind.article(),
1432 macro_kind.descr_expected(),
1433 ),
1434 };
1435 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1436 if !import.span.is_dummy() {
1437 err.span_note(
1438 import.span,
1439 format!("`{}` is imported here, but it is {}", ident, desc),
1440 );
1441 // Silence the 'unused import' warning we might get,
1442 // since this diagnostic already covers that import.
1443 self.record_use(ident, binding, false);
1444 return;
1445 }
1446 }
1447 err.note(format!("`{}` is in scope, but it is {}", ident, desc));
1448 return;
1449 }
1450 }
1451 }
1452
add_typo_suggestion( &self, err: &mut Diagnostic, suggestion: Option<TypoSuggestion>, span: Span, ) -> bool1453 pub(crate) fn add_typo_suggestion(
1454 &self,
1455 err: &mut Diagnostic,
1456 suggestion: Option<TypoSuggestion>,
1457 span: Span,
1458 ) -> bool {
1459 let suggestion = match suggestion {
1460 None => return false,
1461 // We shouldn't suggest underscore.
1462 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1463 Some(suggestion) => suggestion,
1464 };
1465 if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1466 if span.overlaps(def_span) {
1467 // Don't suggest typo suggestion for itself like in the following:
1468 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1469 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1470 // |
1471 // LL | struct X {}
1472 // | ----------- `X` defined here
1473 // LL |
1474 // LL | const Y: X = X("ö");
1475 // | -------------^^^^^^- similarly named constant `Y` defined here
1476 // |
1477 // help: use struct literal syntax instead
1478 // |
1479 // LL | const Y: X = X {};
1480 // | ^^^^
1481 // help: a constant with a similar name exists
1482 // |
1483 // LL | const Y: X = Y("ö");
1484 // | ^
1485 return false;
1486 }
1487 let prefix = match suggestion.target {
1488 SuggestionTarget::SimilarlyNamed => "similarly named ",
1489 SuggestionTarget::SingleItem => "",
1490 };
1491
1492 err.span_label(
1493 self.tcx.sess.source_map().guess_head_span(def_span),
1494 format!(
1495 "{}{} `{}` defined here",
1496 prefix,
1497 suggestion.res.descr(),
1498 suggestion.candidate,
1499 ),
1500 );
1501 }
1502 let msg = match suggestion.target {
1503 SuggestionTarget::SimilarlyNamed => format!(
1504 "{} {} with a similar name exists",
1505 suggestion.res.article(),
1506 suggestion.res.descr()
1507 ),
1508 SuggestionTarget::SingleItem => {
1509 format!("maybe you meant this {}", suggestion.res.descr())
1510 }
1511 };
1512 err.span_suggestion(span, msg, suggestion.candidate, Applicability::MaybeIncorrect);
1513 true
1514 }
1515
binding_description(&self, b: NameBinding<'_>, ident: Ident, from_prelude: bool) -> String1516 fn binding_description(&self, b: NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1517 let res = b.res();
1518 if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
1519 // These already contain the "built-in" prefix or look bad with it.
1520 let add_built_in =
1521 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1522 let (built_in, from) = if from_prelude {
1523 ("", " from prelude")
1524 } else if b.is_extern_crate()
1525 && !b.is_import()
1526 && self.tcx.sess.opts.externs.get(ident.as_str()).is_some()
1527 {
1528 ("", " passed with `--extern`")
1529 } else if add_built_in {
1530 (" built-in", "")
1531 } else {
1532 ("", "")
1533 };
1534
1535 let a = if built_in.is_empty() { res.article() } else { "a" };
1536 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1537 } else {
1538 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1539 format!("the {thing} {introduced} here", thing = res.descr())
1540 }
1541 }
1542
report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>)1543 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1544 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1545 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1546 // We have to print the span-less alternative first, otherwise formatting looks bad.
1547 (b2, b1, misc2, misc1, true)
1548 } else {
1549 (b1, b2, misc1, misc2, false)
1550 };
1551
1552 let mut err = struct_span_err!(self.tcx.sess, ident.span, E0659, "`{ident}` is ambiguous");
1553 err.span_label(ident.span, "ambiguous name");
1554 err.note(format!("ambiguous because of {}", kind.descr()));
1555
1556 let mut could_refer_to = |b: NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1557 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1558 let note_msg = format!("`{ident}` could{also} refer to {what}");
1559
1560 let thing = b.res().descr();
1561 let mut help_msgs = Vec::new();
1562 if b.is_glob_import()
1563 && (kind == AmbiguityKind::GlobVsGlob
1564 || kind == AmbiguityKind::GlobVsExpanded
1565 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1566 {
1567 help_msgs.push(format!(
1568 "consider adding an explicit import of `{ident}` to disambiguate"
1569 ))
1570 }
1571 if b.is_extern_crate() && ident.span.rust_2018() {
1572 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1573 }
1574 match misc {
1575 AmbiguityErrorMisc::SuggestCrate => help_msgs
1576 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously")),
1577 AmbiguityErrorMisc::SuggestSelf => help_msgs
1578 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously")),
1579 AmbiguityErrorMisc::FromPrelude | AmbiguityErrorMisc::None => {}
1580 }
1581
1582 err.span_note(b.span, note_msg);
1583 for (i, help_msg) in help_msgs.iter().enumerate() {
1584 let or = if i == 0 { "" } else { "or " };
1585 err.help(format!("{}{}", or, help_msg));
1586 }
1587 };
1588
1589 could_refer_to(b1, misc1, "");
1590 could_refer_to(b2, misc2, " also");
1591 err.emit();
1592 }
1593
1594 /// If the binding refers to a tuple struct constructor with fields,
1595 /// returns the span of its fields.
ctor_fields_span(&self, binding: NameBinding<'_>) -> Option<Span>1596 fn ctor_fields_span(&self, binding: NameBinding<'_>) -> Option<Span> {
1597 if let NameBindingKind::Res(Res::Def(
1598 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
1599 ctor_def_id,
1600 )) = binding.kind
1601 {
1602 let def_id = self.tcx.parent(ctor_def_id);
1603 return self
1604 .field_def_ids(def_id)?
1605 .iter()
1606 .map(|&field_id| self.def_span(field_id))
1607 .reduce(Span::to); // None for `struct Foo()`
1608 }
1609 None
1610 }
1611
report_privacy_error(&mut self, privacy_error: &PrivacyError<'a>)1612 fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'a>) {
1613 let PrivacyError { ident, binding, outermost_res, parent_scope, dedup_span } =
1614 *privacy_error;
1615
1616 let res = binding.res();
1617 let ctor_fields_span = self.ctor_fields_span(binding);
1618 let plain_descr = res.descr().to_string();
1619 let nonimport_descr =
1620 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1621 let import_descr = nonimport_descr.clone() + " import";
1622 let get_descr =
1623 |b: NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1624
1625 // Print the primary message.
1626 let descr = get_descr(binding);
1627 let mut err =
1628 struct_span_err!(self.tcx.sess, ident.span, E0603, "{} `{}` is private", descr, ident);
1629 err.span_label(ident.span, format!("private {}", descr));
1630
1631 if let Some((this_res, outer_ident)) = outermost_res {
1632 let import_suggestions = self.lookup_import_candidates(
1633 outer_ident,
1634 this_res.ns().unwrap_or(Namespace::TypeNS),
1635 &parent_scope,
1636 &|res: Res| res == this_res,
1637 );
1638 let point_to_def = !show_candidates(
1639 self.tcx,
1640 &mut err,
1641 Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
1642 &import_suggestions,
1643 Instead::Yes,
1644 FoundUse::Yes,
1645 DiagnosticMode::Import,
1646 vec![],
1647 "",
1648 );
1649 // If we suggest importing a public re-export, don't point at the definition.
1650 if point_to_def && ident.span != outer_ident.span {
1651 err.span_label(
1652 outer_ident.span,
1653 format!("{} `{outer_ident}` is not publicly re-exported", this_res.descr()),
1654 );
1655 }
1656 }
1657
1658 let mut non_exhaustive = None;
1659 // If an ADT is foreign and marked as `non_exhaustive`, then that's
1660 // probably why we have the privacy error.
1661 // Otherwise, point out if the struct has any private fields.
1662 if let Some(def_id) = res.opt_def_id()
1663 && !def_id.is_local()
1664 && let Some(attr) = self.tcx.get_attr(def_id, sym::non_exhaustive)
1665 {
1666 non_exhaustive = Some(attr.span);
1667 } else if let Some(span) = ctor_fields_span {
1668 err.span_label(span, "a constructor is private if any of the fields is private");
1669 if let Res::Def(_, d) = res && let Some(fields) = self.field_visibility_spans.get(&d) {
1670 err.multipart_suggestion_verbose(
1671 format!(
1672 "consider making the field{} publicly accessible",
1673 pluralize!(fields.len())
1674 ),
1675 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
1676 Applicability::MaybeIncorrect,
1677 );
1678 }
1679 }
1680
1681 // Print the whole import chain to make it easier to see what happens.
1682 let first_binding = binding;
1683 let mut next_binding = Some(binding);
1684 let mut next_ident = ident;
1685 while let Some(binding) = next_binding {
1686 let name = next_ident;
1687 next_binding = match binding.kind {
1688 _ if res == Res::Err => None,
1689 NameBindingKind::Import { binding, import, .. } => match import.kind {
1690 _ if binding.span.is_dummy() => None,
1691 ImportKind::Single { source, .. } => {
1692 next_ident = source;
1693 Some(binding)
1694 }
1695 ImportKind::Glob { .. } | ImportKind::MacroUse | ImportKind::MacroExport => {
1696 Some(binding)
1697 }
1698 ImportKind::ExternCrate { .. } => None,
1699 },
1700 _ => None,
1701 };
1702
1703 let first = binding == first_binding;
1704 let msg = format!(
1705 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1706 and_refers_to = if first { "" } else { "...and refers to " },
1707 item = get_descr(binding),
1708 which = if first { "" } else { " which" },
1709 dots = if next_binding.is_some() { "..." } else { "" },
1710 );
1711 let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
1712 let mut note_span = MultiSpan::from_span(def_span);
1713 if !first && binding.vis.is_public() {
1714 note_span.push_span_label(def_span, "consider importing it directly");
1715 }
1716 // Final step in the import chain, point out if the ADT is `non_exhaustive`
1717 // which is probably why this privacy violation occurred.
1718 if next_binding.is_none() && let Some(span) = non_exhaustive {
1719 note_span.push_span_label(
1720 span,
1721 format!("cannot be constructed because it is `#[non_exhaustive]`"),
1722 );
1723 }
1724 err.span_note(note_span, msg);
1725 }
1726
1727 err.emit();
1728 }
1729
find_similarly_named_module_or_crate( &mut self, ident: Symbol, current_module: Module<'a>, ) -> Option<Symbol>1730 pub(crate) fn find_similarly_named_module_or_crate(
1731 &mut self,
1732 ident: Symbol,
1733 current_module: Module<'a>,
1734 ) -> Option<Symbol> {
1735 let mut candidates = self
1736 .extern_prelude
1737 .keys()
1738 .map(|ident| ident.name)
1739 .chain(
1740 self.module_map
1741 .iter()
1742 .filter(|(_, module)| {
1743 current_module.is_ancestor_of(**module) && current_module != **module
1744 })
1745 .flat_map(|(_, module)| module.kind.name()),
1746 )
1747 .filter(|c| !c.to_string().is_empty())
1748 .collect::<Vec<_>>();
1749 candidates.sort();
1750 candidates.dedup();
1751 match find_best_match_for_name(&candidates, ident, None) {
1752 Some(sugg) if sugg == ident => None,
1753 sugg => sugg,
1754 }
1755 }
1756
report_path_resolution_error( &mut self, path: &[Segment], opt_ns: Option<Namespace>, parent_scope: &ParentScope<'a>, ribs: Option<&PerNS<Vec<Rib<'a>>>>, ignore_binding: Option<NameBinding<'a>>, module: Option<ModuleOrUniformRoot<'a>>, failed_segment_idx: usize, ident: Ident, ) -> (String, Option<Suggestion>)1757 pub(crate) fn report_path_resolution_error(
1758 &mut self,
1759 path: &[Segment],
1760 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1761 parent_scope: &ParentScope<'a>,
1762 ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1763 ignore_binding: Option<NameBinding<'a>>,
1764 module: Option<ModuleOrUniformRoot<'a>>,
1765 failed_segment_idx: usize,
1766 ident: Ident,
1767 ) -> (String, Option<Suggestion>) {
1768 let is_last = failed_segment_idx == path.len() - 1;
1769 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1770 let module_res = match module {
1771 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1772 _ => None,
1773 };
1774 if module_res == self.graph_root.res() {
1775 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
1776 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
1777 candidates
1778 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
1779 if let Some(candidate) = candidates.get(0) {
1780 (
1781 String::from("unresolved import"),
1782 Some((
1783 vec![(ident.span, pprust::path_to_string(&candidate.path))],
1784 String::from("a similar path exists"),
1785 Applicability::MaybeIncorrect,
1786 )),
1787 )
1788 } else if self.tcx.sess.is_rust_2015() {
1789 (
1790 format!("maybe a missing crate `{ident}`?"),
1791 Some((
1792 vec![],
1793 format!(
1794 "consider adding `extern crate {ident}` to use the `{ident}` crate"
1795 ),
1796 Applicability::MaybeIncorrect,
1797 )),
1798 )
1799 } else {
1800 (format!("could not find `{ident}` in the crate root"), None)
1801 }
1802 } else if failed_segment_idx > 0 {
1803 let parent = path[failed_segment_idx - 1].ident.name;
1804 let parent = match parent {
1805 // ::foo is mounted at the crate root for 2015, and is the extern
1806 // prelude for 2018+
1807 kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
1808 "the list of imported crates".to_owned()
1809 }
1810 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
1811 _ => format!("`{parent}`"),
1812 };
1813
1814 let mut msg = format!("could not find `{}` in {}", ident, parent);
1815 if ns == TypeNS || ns == ValueNS {
1816 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
1817 let binding = if let Some(module) = module {
1818 self.resolve_ident_in_module(
1819 module,
1820 ident,
1821 ns_to_try,
1822 parent_scope,
1823 None,
1824 ignore_binding,
1825 ).ok()
1826 } else if let Some(ribs) = ribs
1827 && let Some(TypeNS | ValueNS) = opt_ns
1828 {
1829 match self.resolve_ident_in_lexical_scope(
1830 ident,
1831 ns_to_try,
1832 parent_scope,
1833 None,
1834 &ribs[ns_to_try],
1835 ignore_binding,
1836 ) {
1837 // we found a locally-imported or available item/module
1838 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
1839 _ => None,
1840 }
1841 } else {
1842 self.early_resolve_ident_in_lexical_scope(
1843 ident,
1844 ScopeSet::All(ns_to_try),
1845 parent_scope,
1846 None,
1847 false,
1848 ignore_binding,
1849 ).ok()
1850 };
1851 if let Some(binding) = binding {
1852 let mut found = |what| {
1853 msg = format!(
1854 "expected {}, found {} `{}` in {}",
1855 ns.descr(),
1856 what,
1857 ident,
1858 parent
1859 )
1860 };
1861 if binding.module().is_some() {
1862 found("module")
1863 } else {
1864 match binding.res() {
1865 // Avoid using TyCtxt::def_kind_descr in the resolver, because it
1866 // indirectly *calls* the resolver, and would cause a query cycle.
1867 Res::Def(kind, id) => found(kind.descr(id)),
1868 _ => found(ns_to_try.descr()),
1869 }
1870 }
1871 };
1872 }
1873 (msg, None)
1874 } else if ident.name == kw::SelfUpper {
1875 // As mentioned above, `opt_ns` being `None` indicates a module path in import.
1876 // We can use this to improve a confusing error for, e.g. `use Self::Variant` in an
1877 // impl
1878 if opt_ns.is_none() {
1879 ("`Self` cannot be used in imports".to_string(), None)
1880 } else {
1881 (
1882 "`Self` is only available in impls, traits, and type definitions".to_string(),
1883 None,
1884 )
1885 }
1886 } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
1887 // Check whether the name refers to an item in the value namespace.
1888 let binding = if let Some(ribs) = ribs {
1889 self.resolve_ident_in_lexical_scope(
1890 ident,
1891 ValueNS,
1892 parent_scope,
1893 None,
1894 &ribs[ValueNS],
1895 ignore_binding,
1896 )
1897 } else {
1898 None
1899 };
1900 let match_span = match binding {
1901 // Name matches a local variable. For example:
1902 // ```
1903 // fn f() {
1904 // let Foo: &str = "";
1905 // println!("{}", Foo::Bar); // Name refers to local
1906 // // variable `Foo`.
1907 // }
1908 // ```
1909 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
1910 Some(*self.pat_span_map.get(&id).unwrap())
1911 }
1912 // Name matches item from a local name binding
1913 // created by `use` declaration. For example:
1914 // ```
1915 // pub Foo: &str = "";
1916 //
1917 // mod submod {
1918 // use super::Foo;
1919 // println!("{}", Foo::Bar); // Name refers to local
1920 // // binding `Foo`.
1921 // }
1922 // ```
1923 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
1924 _ => None,
1925 };
1926 let suggestion = match_span.map(|span| {
1927 (
1928 vec![(span, String::from(""))],
1929 format!("`{}` is defined here, but is not a type", ident),
1930 Applicability::MaybeIncorrect,
1931 )
1932 });
1933
1934 (format!("use of undeclared type `{}`", ident), suggestion)
1935 } else {
1936 let mut suggestion = None;
1937 if ident.name == sym::alloc {
1938 suggestion = Some((
1939 vec![],
1940 String::from("add `extern crate alloc` to use the `alloc` crate"),
1941 Applicability::MaybeIncorrect,
1942 ))
1943 }
1944
1945 suggestion = suggestion.or_else(|| {
1946 self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
1947 |sugg| {
1948 (
1949 vec![(ident.span, sugg.to_string())],
1950 String::from("there is a crate or module with a similar name"),
1951 Applicability::MaybeIncorrect,
1952 )
1953 },
1954 )
1955 });
1956 (format!("use of undeclared crate or module `{}`", ident), suggestion)
1957 }
1958 }
1959
1960 /// Adds suggestions for a path that cannot be resolved.
make_path_suggestion( &mut self, span: Span, mut path: Vec<Segment>, parent_scope: &ParentScope<'a>, ) -> Option<(Vec<Segment>, Option<String>)>1961 pub(crate) fn make_path_suggestion(
1962 &mut self,
1963 span: Span,
1964 mut path: Vec<Segment>,
1965 parent_scope: &ParentScope<'a>,
1966 ) -> Option<(Vec<Segment>, Option<String>)> {
1967 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1968
1969 match (path.get(0), path.get(1)) {
1970 // `{{root}}::ident::...` on both editions.
1971 // On 2015 `{{root}}` is usually added implicitly.
1972 (Some(fst), Some(snd))
1973 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1974 // `ident::...` on 2018.
1975 (Some(fst), _)
1976 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1977 {
1978 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1979 path.insert(0, Segment::from_ident(Ident::empty()));
1980 }
1981 _ => return None,
1982 }
1983
1984 self.make_missing_self_suggestion(path.clone(), parent_scope)
1985 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
1986 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
1987 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
1988 }
1989
1990 /// Suggest a missing `self::` if that resolves to an correct module.
1991 ///
1992 /// ```text
1993 /// |
1994 /// LL | use foo::Bar;
1995 /// | ^^^ did you mean `self::foo`?
1996 /// ```
make_missing_self_suggestion( &mut self, mut path: Vec<Segment>, parent_scope: &ParentScope<'a>, ) -> Option<(Vec<Segment>, Option<String>)>1997 fn make_missing_self_suggestion(
1998 &mut self,
1999 mut path: Vec<Segment>,
2000 parent_scope: &ParentScope<'a>,
2001 ) -> Option<(Vec<Segment>, Option<String>)> {
2002 // Replace first ident with `self` and check if that is valid.
2003 path[0].ident.name = kw::SelfLower;
2004 let result = self.maybe_resolve_path(&path, None, parent_scope);
2005 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
2006 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2007 }
2008
2009 /// Suggests a missing `crate::` if that resolves to an correct module.
2010 ///
2011 /// ```text
2012 /// |
2013 /// LL | use foo::Bar;
2014 /// | ^^^ did you mean `crate::foo`?
2015 /// ```
make_missing_crate_suggestion( &mut self, mut path: Vec<Segment>, parent_scope: &ParentScope<'a>, ) -> Option<(Vec<Segment>, Option<String>)>2016 fn make_missing_crate_suggestion(
2017 &mut self,
2018 mut path: Vec<Segment>,
2019 parent_scope: &ParentScope<'a>,
2020 ) -> Option<(Vec<Segment>, Option<String>)> {
2021 // Replace first ident with `crate` and check if that is valid.
2022 path[0].ident.name = kw::Crate;
2023 let result = self.maybe_resolve_path(&path, None, parent_scope);
2024 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
2025 if let PathResult::Module(..) = result {
2026 Some((
2027 path,
2028 Some(
2029 "`use` statements changed in Rust 2018; read more at \
2030 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2031 clarity.html>"
2032 .to_string(),
2033 ),
2034 ))
2035 } else {
2036 None
2037 }
2038 }
2039
2040 /// Suggests a missing `super::` if that resolves to an correct module.
2041 ///
2042 /// ```text
2043 /// |
2044 /// LL | use foo::Bar;
2045 /// | ^^^ did you mean `super::foo`?
2046 /// ```
make_missing_super_suggestion( &mut self, mut path: Vec<Segment>, parent_scope: &ParentScope<'a>, ) -> Option<(Vec<Segment>, Option<String>)>2047 fn make_missing_super_suggestion(
2048 &mut self,
2049 mut path: Vec<Segment>,
2050 parent_scope: &ParentScope<'a>,
2051 ) -> Option<(Vec<Segment>, Option<String>)> {
2052 // Replace first ident with `crate` and check if that is valid.
2053 path[0].ident.name = kw::Super;
2054 let result = self.maybe_resolve_path(&path, None, parent_scope);
2055 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
2056 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2057 }
2058
2059 /// Suggests a missing external crate name if that resolves to an correct module.
2060 ///
2061 /// ```text
2062 /// |
2063 /// LL | use foobar::Baz;
2064 /// | ^^^^^^ did you mean `baz::foobar`?
2065 /// ```
2066 ///
2067 /// Used when importing a submodule of an external crate but missing that crate's
2068 /// name as the first part of path.
make_external_crate_suggestion( &mut self, mut path: Vec<Segment>, parent_scope: &ParentScope<'a>, ) -> Option<(Vec<Segment>, Option<String>)>2069 fn make_external_crate_suggestion(
2070 &mut self,
2071 mut path: Vec<Segment>,
2072 parent_scope: &ParentScope<'a>,
2073 ) -> Option<(Vec<Segment>, Option<String>)> {
2074 if path[1].ident.span.is_rust_2015() {
2075 return None;
2076 }
2077
2078 // Sort extern crate names in *reverse* order to get
2079 // 1) some consistent ordering for emitted diagnostics, and
2080 // 2) `std` suggestions before `core` suggestions.
2081 let mut extern_crate_names =
2082 self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2083 extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
2084
2085 for name in extern_crate_names.into_iter() {
2086 // Replace first ident with a crate name and check if that is valid.
2087 path[0].ident.name = name;
2088 let result = self.maybe_resolve_path(&path, None, parent_scope);
2089 debug!(
2090 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
2091 name, path, result
2092 );
2093 if let PathResult::Module(..) = result {
2094 return Some((path, None));
2095 }
2096 }
2097
2098 None
2099 }
2100
2101 /// Suggests importing a macro from the root of the crate rather than a module within
2102 /// the crate.
2103 ///
2104 /// ```text
2105 /// help: a macro with this name exists at the root of the crate
2106 /// |
2107 /// LL | use issue_59764::makro;
2108 /// | ^^^^^^^^^^^^^^^^^^
2109 /// |
2110 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
2111 /// at the root of the crate instead of the module where it is defined
2112 /// ```
check_for_module_export_macro( &mut self, import: Import<'a>, module: ModuleOrUniformRoot<'a>, ident: Ident, ) -> Option<(Option<Suggestion>, Option<String>)>2113 pub(crate) fn check_for_module_export_macro(
2114 &mut self,
2115 import: Import<'a>,
2116 module: ModuleOrUniformRoot<'a>,
2117 ident: Ident,
2118 ) -> Option<(Option<Suggestion>, Option<String>)> {
2119 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2120 return None;
2121 };
2122
2123 while let Some(parent) = crate_module.parent {
2124 crate_module = parent;
2125 }
2126
2127 if module == ModuleOrUniformRoot::Module(crate_module) {
2128 // Don't make a suggestion if the import was already from the root of the crate.
2129 return None;
2130 }
2131
2132 let resolutions = self.resolutions(crate_module).borrow();
2133 let binding_key = BindingKey::new(ident, MacroNS);
2134 let resolution = resolutions.get(&binding_key)?;
2135 let binding = resolution.borrow().binding()?;
2136 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
2137 let module_name = crate_module.kind.name().unwrap();
2138 let import_snippet = match import.kind {
2139 ImportKind::Single { source, target, .. } if source != target => {
2140 format!("{} as {}", source, target)
2141 }
2142 _ => format!("{}", ident),
2143 };
2144
2145 let mut corrections: Vec<(Span, String)> = Vec::new();
2146 if !import.is_nested() {
2147 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2148 // intermediate segments.
2149 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
2150 } else {
2151 // Find the binding span (and any trailing commas and spaces).
2152 // ie. `use a::b::{c, d, e};`
2153 // ^^^
2154 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2155 self.tcx.sess,
2156 import.span,
2157 import.use_span,
2158 );
2159 debug!(
2160 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
2161 found_closing_brace, binding_span
2162 );
2163
2164 let mut removal_span = binding_span;
2165 if found_closing_brace {
2166 // If the binding span ended with a closing brace, as in the below example:
2167 // ie. `use a::b::{c, d};`
2168 // ^
2169 // Then expand the span of characters to remove to include the previous
2170 // binding's trailing comma.
2171 // ie. `use a::b::{c, d};`
2172 // ^^^
2173 if let Some(previous_span) =
2174 extend_span_to_previous_binding(self.tcx.sess, binding_span)
2175 {
2176 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
2177 removal_span = removal_span.with_lo(previous_span.lo());
2178 }
2179 }
2180 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
2181
2182 // Remove the `removal_span`.
2183 corrections.push((removal_span, "".to_string()));
2184
2185 // Find the span after the crate name and if it has nested imports immediately
2186 // after the crate name already.
2187 // ie. `use a::b::{c, d};`
2188 // ^^^^^^^^^
2189 // or `use a::{b, c, d}};`
2190 // ^^^^^^^^^^^
2191 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
2192 self.tcx.sess,
2193 module_name,
2194 import.use_span,
2195 );
2196 debug!(
2197 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
2198 has_nested, after_crate_name
2199 );
2200
2201 let source_map = self.tcx.sess.source_map();
2202
2203 // Make sure this is actually crate-relative.
2204 let is_definitely_crate = import
2205 .module_path
2206 .first()
2207 .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
2208
2209 // Add the import to the start, with a `{` if required.
2210 let start_point = source_map.start_point(after_crate_name);
2211 if is_definitely_crate && let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
2212 corrections.push((
2213 start_point,
2214 if has_nested {
2215 // In this case, `start_snippet` must equal '{'.
2216 format!("{}{}, ", start_snippet, import_snippet)
2217 } else {
2218 // In this case, add a `{`, then the moved import, then whatever
2219 // was there before.
2220 format!("{{{}, {}", import_snippet, start_snippet)
2221 },
2222 ));
2223
2224 // Add a `};` to the end if nested, matching the `{` added at the start.
2225 if !has_nested {
2226 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2227 }
2228 } else {
2229 // If the root import is module-relative, add the import separately
2230 corrections.push((
2231 import.use_span.shrink_to_lo(),
2232 format!("use {module_name}::{import_snippet};\n"),
2233 ));
2234 }
2235 }
2236
2237 let suggestion = Some((
2238 corrections,
2239 String::from("a macro with this name exists at the root of the crate"),
2240 Applicability::MaybeIncorrect,
2241 ));
2242 Some((suggestion, Some("this could be because a macro annotated with `#[macro_export]` will be exported \
2243 at the root of the crate instead of the module where it is defined"
2244 .to_string())))
2245 } else {
2246 None
2247 }
2248 }
2249
2250 /// Finds a cfg-ed out item inside `module` with the matching name.
find_cfg_stripped( &mut self, err: &mut Diagnostic, last_segment: &Symbol, module: DefId, )2251 pub(crate) fn find_cfg_stripped(
2252 &mut self,
2253 err: &mut Diagnostic,
2254 last_segment: &Symbol,
2255 module: DefId,
2256 ) {
2257 let local_items;
2258 let symbols = if module.is_local() {
2259 local_items = self
2260 .stripped_cfg_items
2261 .iter()
2262 .filter_map(|item| {
2263 let parent_module = self.opt_local_def_id(item.parent_module)?.to_def_id();
2264 Some(StrippedCfgItem { parent_module, name: item.name, cfg: item.cfg.clone() })
2265 })
2266 .collect::<Vec<_>>();
2267 local_items.as_slice()
2268 } else {
2269 self.tcx.stripped_cfg_items(module.krate)
2270 };
2271
2272 for &StrippedCfgItem { parent_module, name, ref cfg } in symbols {
2273 if parent_module != module || name.name != *last_segment {
2274 continue;
2275 }
2276
2277 err.span_note(name.span, "found an item that was configured out");
2278
2279 if let MetaItemKind::List(nested) = &cfg.kind
2280 && let NestedMetaItem::MetaItem(meta_item) = &nested[0]
2281 && let MetaItemKind::NameValue(feature_name) = &meta_item.kind
2282 {
2283 err.note(format!("the item is gated behind the `{}` feature", feature_name.symbol));
2284 }
2285 }
2286 }
2287 }
2288
2289 /// Given a `binding_span` of a binding within a use statement:
2290 ///
2291 /// ```ignore (illustrative)
2292 /// use foo::{a, b, c};
2293 /// // ^
2294 /// ```
2295 ///
2296 /// then return the span until the next binding or the end of the statement:
2297 ///
2298 /// ```ignore (illustrative)
2299 /// use foo::{a, b, c};
2300 /// // ^^^
2301 /// ```
find_span_of_binding_until_next_binding( sess: &Session, binding_span: Span, use_span: Span, ) -> (bool, Span)2302 fn find_span_of_binding_until_next_binding(
2303 sess: &Session,
2304 binding_span: Span,
2305 use_span: Span,
2306 ) -> (bool, Span) {
2307 let source_map = sess.source_map();
2308
2309 // Find the span of everything after the binding.
2310 // ie. `a, e};` or `a};`
2311 let binding_until_end = binding_span.with_hi(use_span.hi());
2312
2313 // Find everything after the binding but not including the binding.
2314 // ie. `, e};` or `};`
2315 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2316
2317 // Keep characters in the span until we encounter something that isn't a comma or
2318 // whitespace.
2319 // ie. `, ` or ``.
2320 //
2321 // Also note whether a closing brace character was encountered. If there
2322 // was, then later go backwards to remove any trailing commas that are left.
2323 let mut found_closing_brace = false;
2324 let after_binding_until_next_binding =
2325 source_map.span_take_while(after_binding_until_end, |&ch| {
2326 if ch == '}' {
2327 found_closing_brace = true;
2328 }
2329 ch == ' ' || ch == ','
2330 });
2331
2332 // Combine the two spans.
2333 // ie. `a, ` or `a`.
2334 //
2335 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2336 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2337
2338 (found_closing_brace, span)
2339 }
2340
2341 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2342 /// binding.
2343 ///
2344 /// ```ignore (illustrative)
2345 /// use foo::a::{a, b, c};
2346 /// // ^^--- binding span
2347 /// // |
2348 /// // returned span
2349 ///
2350 /// use foo::{a, b, c};
2351 /// // --- binding span
2352 /// ```
extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span>2353 fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2354 let source_map = sess.source_map();
2355
2356 // `prev_source` will contain all of the source that came before the span.
2357 // Then split based on a command and take the first (ie. closest to our span)
2358 // snippet. In the example, this is a space.
2359 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2360
2361 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2362 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2363 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2364 return None;
2365 }
2366
2367 let prev_comma = prev_comma.first().unwrap();
2368 let prev_starting_brace = prev_starting_brace.first().unwrap();
2369
2370 // If the amount of source code before the comma is greater than
2371 // the amount of source code before the starting brace then we've only
2372 // got one item in the nested item (eg. `issue_52891::{self}`).
2373 if prev_comma.len() > prev_starting_brace.len() {
2374 return None;
2375 }
2376
2377 Some(binding_span.with_lo(BytePos(
2378 // Take away the number of bytes for the characters we've found and an
2379 // extra for the comma.
2380 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2381 )))
2382 }
2383
2384 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2385 /// it is a nested use tree.
2386 ///
2387 /// ```ignore (illustrative)
2388 /// use foo::a::{b, c};
2389 /// // ^^^^^^^^^^ -- false
2390 ///
2391 /// use foo::{a, b, c};
2392 /// // ^^^^^^^^^^ -- true
2393 ///
2394 /// use foo::{a, b::{c, d}};
2395 /// // ^^^^^^^^^^^^^^^ -- true
2396 /// ```
find_span_immediately_after_crate_name( sess: &Session, module_name: Symbol, use_span: Span, ) -> (bool, Span)2397 fn find_span_immediately_after_crate_name(
2398 sess: &Session,
2399 module_name: Symbol,
2400 use_span: Span,
2401 ) -> (bool, Span) {
2402 debug!(
2403 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
2404 module_name, use_span
2405 );
2406 let source_map = sess.source_map();
2407
2408 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2409 let mut num_colons = 0;
2410 // Find second colon.. `use issue_59764:`
2411 let until_second_colon = source_map.span_take_while(use_span, |c| {
2412 if *c == ':' {
2413 num_colons += 1;
2414 }
2415 !matches!(c, ':' if num_colons == 2)
2416 });
2417 // Find everything after the second colon.. `foo::{baz, makro};`
2418 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2419
2420 let mut found_a_non_whitespace_character = false;
2421 // Find the first non-whitespace character in `from_second_colon`.. `f`
2422 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2423 if found_a_non_whitespace_character {
2424 return false;
2425 }
2426 if !c.is_whitespace() {
2427 found_a_non_whitespace_character = true;
2428 }
2429 true
2430 });
2431
2432 // Find the first `{` in from_second_colon.. `foo::{`
2433 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2434
2435 (next_left_bracket == after_second_colon, from_second_colon)
2436 }
2437
2438 /// A suggestion has already been emitted, change the wording slightly to clarify that both are
2439 /// independent options.
2440 enum Instead {
2441 Yes,
2442 No,
2443 }
2444
2445 /// Whether an existing place with an `use` item was found.
2446 enum FoundUse {
2447 Yes,
2448 No,
2449 }
2450
2451 /// Whether a binding is part of a pattern or a use statement. Used for diagnostics.
2452 pub(crate) enum DiagnosticMode {
2453 Normal,
2454 /// The binding is part of a pattern
2455 Pattern,
2456 /// The binding is part of a use statement
2457 Import,
2458 }
2459
import_candidates( tcx: TyCtxt<'_>, err: &mut Diagnostic, use_placement_span: Option<Span>, candidates: &[ImportSuggestion], mode: DiagnosticMode, append: &str, )2460 pub(crate) fn import_candidates(
2461 tcx: TyCtxt<'_>,
2462 err: &mut Diagnostic,
2463 // This is `None` if all placement locations are inside expansions
2464 use_placement_span: Option<Span>,
2465 candidates: &[ImportSuggestion],
2466 mode: DiagnosticMode,
2467 append: &str,
2468 ) {
2469 show_candidates(
2470 tcx,
2471 err,
2472 use_placement_span,
2473 candidates,
2474 Instead::Yes,
2475 FoundUse::Yes,
2476 mode,
2477 vec![],
2478 append,
2479 );
2480 }
2481
2482 /// When an entity with a given name is not available in scope, we search for
2483 /// entities with that name in all crates. This method allows outputting the
2484 /// results of this search in a programmer-friendly way. If any entities are
2485 /// found and suggested, returns `true`, otherwise returns `false`.
show_candidates( tcx: TyCtxt<'_>, err: &mut Diagnostic, use_placement_span: Option<Span>, candidates: &[ImportSuggestion], instead: Instead, found_use: FoundUse, mode: DiagnosticMode, path: Vec<Segment>, append: &str, ) -> bool2486 fn show_candidates(
2487 tcx: TyCtxt<'_>,
2488 err: &mut Diagnostic,
2489 // This is `None` if all placement locations are inside expansions
2490 use_placement_span: Option<Span>,
2491 candidates: &[ImportSuggestion],
2492 instead: Instead,
2493 found_use: FoundUse,
2494 mode: DiagnosticMode,
2495 path: Vec<Segment>,
2496 append: &str,
2497 ) -> bool {
2498 if candidates.is_empty() {
2499 return false;
2500 }
2501
2502 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>, bool)> =
2503 Vec::new();
2504 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>, bool)> =
2505 Vec::new();
2506
2507 candidates.iter().for_each(|c| {
2508 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
2509 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note, c.via_import))
2510 });
2511
2512 // we want consistent results across executions, but candidates are produced
2513 // by iterating through a hash map, so make sure they are ordered:
2514 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2515 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2516 let core_path_strings =
2517 path_strings.extract_if(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
2518 path_strings.extend(core_path_strings);
2519 path_strings.dedup_by(|a, b| a.0 == b.0);
2520 }
2521
2522 if !accessible_path_strings.is_empty() {
2523 let (determiner, kind, name, through) =
2524 if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
2525 (
2526 "this",
2527 *descr,
2528 format!(" `{name}`"),
2529 if *via_import { " through its public re-export" } else { "" },
2530 )
2531 } else {
2532 ("one of these", "items", String::new(), "")
2533 };
2534
2535 let instead = if let Instead::Yes = instead { " instead" } else { "" };
2536 let mut msg = if let DiagnosticMode::Pattern = mode {
2537 format!(
2538 "if you meant to match on {kind}{instead}{name}, use the full path in the pattern",
2539 )
2540 } else {
2541 format!("consider importing {determiner} {kind}{through}{instead}")
2542 };
2543
2544 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2545 err.note(note.clone());
2546 }
2547
2548 if let Some(span) = use_placement_span {
2549 let (add_use, trailing) = match mode {
2550 DiagnosticMode::Pattern => {
2551 err.span_suggestions(
2552 span,
2553 msg,
2554 accessible_path_strings.into_iter().map(|a| a.0),
2555 Applicability::MaybeIncorrect,
2556 );
2557 return true;
2558 }
2559 DiagnosticMode::Import => ("", ""),
2560 DiagnosticMode::Normal => ("use ", ";\n"),
2561 };
2562 for candidate in &mut accessible_path_strings {
2563 // produce an additional newline to separate the new use statement
2564 // from the directly following item.
2565 let additional_newline = if let FoundUse::No = found_use && let DiagnosticMode::Normal = mode { "\n" } else { "" };
2566 candidate.0 =
2567 format!("{add_use}{}{append}{trailing}{additional_newline}", &candidate.0);
2568 }
2569
2570 err.span_suggestions_with_style(
2571 span,
2572 msg,
2573 accessible_path_strings.into_iter().map(|a| a.0),
2574 Applicability::MaybeIncorrect,
2575 SuggestionStyle::ShowAlways,
2576 );
2577 if let [first, .., last] = &path[..] {
2578 let sp = first.ident.span.until(last.ident.span);
2579 if sp.can_be_used_for_suggestions() {
2580 err.span_suggestion_verbose(
2581 sp,
2582 format!("if you import `{}`, refer to it directly", last.ident),
2583 "",
2584 Applicability::Unspecified,
2585 );
2586 }
2587 }
2588 } else {
2589 msg.push(':');
2590
2591 for candidate in accessible_path_strings {
2592 msg.push('\n');
2593 msg.push_str(&candidate.0);
2594 }
2595
2596 err.help(msg);
2597 }
2598 true
2599 } else if !matches!(mode, DiagnosticMode::Import) {
2600 assert!(!inaccessible_path_strings.is_empty());
2601
2602 let prefix = if let DiagnosticMode::Pattern = mode {
2603 "you might have meant to match on "
2604 } else {
2605 ""
2606 };
2607 if let [(name, descr, def_id, note, _)] = &inaccessible_path_strings[..] {
2608 let msg = format!(
2609 "{prefix}{descr} `{name}`{} exists but is inaccessible",
2610 if let DiagnosticMode::Pattern = mode { ", which" } else { "" }
2611 );
2612
2613 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2614 let span = tcx.source_span(local_def_id);
2615 let span = tcx.sess.source_map().guess_head_span(span);
2616 let mut multi_span = MultiSpan::from_span(span);
2617 multi_span.push_span_label(span, "not accessible");
2618 err.span_note(multi_span, msg);
2619 } else {
2620 err.note(msg);
2621 }
2622 if let Some(note) = (*note).as_deref() {
2623 err.note(note.to_string());
2624 }
2625 } else {
2626 let (_, descr_first, _, _, _) = &inaccessible_path_strings[0];
2627 let descr = if inaccessible_path_strings
2628 .iter()
2629 .skip(1)
2630 .all(|(_, descr, _, _, _)| descr == descr_first)
2631 {
2632 descr_first
2633 } else {
2634 "item"
2635 };
2636 let plural_descr =
2637 if descr.ends_with('s') { format!("{}es", descr) } else { format!("{}s", descr) };
2638
2639 let mut msg = format!("{}these {} exist but are inaccessible", prefix, plural_descr);
2640 let mut has_colon = false;
2641
2642 let mut spans = Vec::new();
2643 for (name, _, def_id, _, _) in &inaccessible_path_strings {
2644 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2645 let span = tcx.source_span(local_def_id);
2646 let span = tcx.sess.source_map().guess_head_span(span);
2647 spans.push((name, span));
2648 } else {
2649 if !has_colon {
2650 msg.push(':');
2651 has_colon = true;
2652 }
2653 msg.push('\n');
2654 msg.push_str(name);
2655 }
2656 }
2657
2658 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
2659 for (name, span) in spans {
2660 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
2661 }
2662
2663 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2664 err.note(note.clone());
2665 }
2666
2667 err.span_note(multi_span, msg);
2668 }
2669 true
2670 } else {
2671 false
2672 }
2673 }
2674
2675 #[derive(Debug)]
2676 struct UsePlacementFinder {
2677 target_module: NodeId,
2678 first_legal_span: Option<Span>,
2679 first_use_span: Option<Span>,
2680 }
2681
2682 impl UsePlacementFinder {
check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse)2683 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
2684 let mut finder =
2685 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
2686 finder.visit_crate(krate);
2687 if let Some(use_span) = finder.first_use_span {
2688 (Some(use_span), FoundUse::Yes)
2689 } else {
2690 (finder.first_legal_span, FoundUse::No)
2691 }
2692 }
2693 }
2694
2695 impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
visit_crate(&mut self, c: &Crate)2696 fn visit_crate(&mut self, c: &Crate) {
2697 if self.target_module == CRATE_NODE_ID {
2698 let inject = c.spans.inject_use_span;
2699 if is_span_suitable_for_use_injection(inject) {
2700 self.first_legal_span = Some(inject);
2701 }
2702 self.first_use_span = search_for_any_use_in_items(&c.items);
2703 return;
2704 } else {
2705 visit::walk_crate(self, c);
2706 }
2707 }
2708
visit_item(&mut self, item: &'tcx ast::Item)2709 fn visit_item(&mut self, item: &'tcx ast::Item) {
2710 if self.target_module == item.id {
2711 if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
2712 let inject = mod_spans.inject_use_span;
2713 if is_span_suitable_for_use_injection(inject) {
2714 self.first_legal_span = Some(inject);
2715 }
2716 self.first_use_span = search_for_any_use_in_items(items);
2717 return;
2718 }
2719 } else {
2720 visit::walk_item(self, item);
2721 }
2722 }
2723 }
2724
search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span>2725 fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
2726 for item in items {
2727 if let ItemKind::Use(..) = item.kind {
2728 if is_span_suitable_for_use_injection(item.span) {
2729 return Some(item.span.shrink_to_lo());
2730 }
2731 }
2732 }
2733 return None;
2734 }
2735
is_span_suitable_for_use_injection(s: Span) -> bool2736 fn is_span_suitable_for_use_injection(s: Span) -> bool {
2737 // don't suggest placing a use before the prelude
2738 // import or other generated ones
2739 !s.from_expansion()
2740 }
2741
2742 /// Convert the given number into the corresponding ordinal
ordinalize(v: usize) -> String2743 pub(crate) fn ordinalize(v: usize) -> String {
2744 let suffix = match ((11..=13).contains(&(v % 100)), v % 10) {
2745 (false, 1) => "st",
2746 (false, 2) => "nd",
2747 (false, 3) => "rd",
2748 _ => "th",
2749 };
2750 format!("{v}{suffix}")
2751 }
2752