3 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
5 use rustc::hir::def::{self, DefKind, CtorKind, Namespace::*};
6 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
7 use rustc::session::{Session, config::nightly_options};
8 use syntax::ast::{self, Expr, ExprKind, Ident};
9 use syntax::ext::base::MacroKind;
10 use syntax::symbol::{Symbol, keywords};
11 use syntax_pos::{BytePos, Span};
13 type Def = def::Def<ast::NodeId>;
15 use crate::macros::ParentScope;
16 use crate::resolve_imports::{ImportDirective, ImportDirectiveSubclass, ImportResolver};
17 use crate::{import_candidate_to_enum_paths, is_self_type, is_self_value, path_names_to_string};
18 use crate::{AssocSuggestion, CrateLint, ImportSuggestion, ModuleOrUniformRoot, PathResult,
19 PathSource, Resolver, Segment, Suggestion};
21 impl<'a> Resolver<'a> {
22 /// Handles error reporting for `smart_resolve_path_fragment` function.
23 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
24 pub(crate) fn smart_resolve_report_errors(
28 source: PathSource<'_>,
30 ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
31 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
32 let ns = source.namespace();
33 let is_expected = &|def| source.is_expected(def);
34 let is_enum_variant = &|def| {
35 if let Def::Def(DefKind::Variant, _) = def { true } else { false }
38 // Make the base error.
39 let expected = source.descr_expected();
40 let path_str = Segment::names_to_string(path);
41 let item_str = path.last().unwrap().ident;
42 let code = source.error_code(def.is_some());
43 let (base_msg, fallback_label, base_span) = if let Some(def) = def {
44 (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
45 format!("not a {}", expected),
48 let item_span = path.last().unwrap().ident.span;
49 let (mod_prefix, mod_str) = if path.len() == 1 {
50 (String::new(), "this scope".to_string())
51 } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() {
52 (String::new(), "the crate root".to_string())
54 let mod_path = &path[..path.len() - 1];
55 let mod_prefix = match self.resolve_path_without_parent_scope(
56 mod_path, Some(TypeNS), false, span, CrateLint::No
58 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
61 }.map_or(String::new(), |kind| format!("{} ", kind.descr()));
62 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
64 (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
65 format!("not found in {}", mod_str),
69 let code = DiagnosticId::Error(code.into());
70 let mut err = self.session.struct_span_err_with_code(base_span, &base_msg, code);
72 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
73 if ["this", "my"].contains(&&*item_str.as_str())
74 && self.self_value_is_available(path[0].ident.span, span) {
79 Applicability::MaybeIncorrect,
83 // Emit special messages for unresolved `Self` and `self`.
84 if is_self_type(path, ns) {
85 __diagnostic_used!(E0411);
86 err.code(DiagnosticId::Error("E0411".into()));
87 err.span_label(span, format!("`Self` is only available in impls, traits, \
88 and type definitions"));
89 return (err, Vec::new());
91 if is_self_value(path, ns) {
92 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
94 __diagnostic_used!(E0424);
95 err.code(DiagnosticId::Error("E0424".into()));
96 err.span_label(span, match source {
98 format!("`self` value is a keyword \
99 and may not be bound to \
100 variables or shadowed")
103 format!("`self` value is a keyword \
104 only available in methods \
105 with `self` parameter")
108 return (err, Vec::new());
111 // Try to lookup name in more relaxed fashion for better error reporting.
112 let ident = path.last().unwrap().ident;
113 let candidates = self.lookup_import_candidates(ident, ns, is_expected)
115 .filter(|ImportSuggestion { did, .. }| {
116 match (did, def.and_then(|def| def.opt_def_id())) {
117 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
121 .collect::<Vec<_>>();
122 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
123 if candidates.is_empty() && is_expected(Def::Def(DefKind::Enum, crate_def_id)) {
124 let enum_candidates =
125 self.lookup_import_candidates(ident, ns, is_enum_variant);
126 let mut enum_candidates = enum_candidates.iter()
128 import_candidate_to_enum_paths(&suggestion)
129 }).collect::<Vec<_>>();
130 enum_candidates.sort();
132 if !enum_candidates.is_empty() {
133 // Contextualize for E0412 "cannot find type", but don't belabor the point
134 // (that it's a variant) for E0573 "expected type, found variant".
135 let preamble = if def.is_none() {
136 let others = match enum_candidates.len() {
138 2 => " and 1 other".to_owned(),
139 n => format!(" and {} others", n)
141 format!("there is an enum variant `{}`{}; ",
142 enum_candidates[0].0, others)
146 let msg = format!("{}try using the variant's enum", preamble);
148 err.span_suggestions(
151 enum_candidates.into_iter()
152 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
153 // Variants re-exported in prelude doesn't mean `prelude::v1` is the
155 // FIXME: is there a more principled way to do this that
156 // would work for other re-exports?
157 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
158 // Also write `Option` rather than `std::prelude::v1::Option`.
159 .map(|enum_ty_path| {
160 // FIXME #56861: DRY-er prelude filtering.
161 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
163 Applicability::MachineApplicable,
167 if path.len() == 1 && self.self_type_is_available(span) {
168 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
169 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
171 AssocSuggestion::Field => {
172 if self_is_available {
175 "you might have meant to use the available field",
176 format!("self.{}", path_str),
177 Applicability::MachineApplicable,
182 "a field by this name exists in `Self`",
186 AssocSuggestion::MethodWithSelf if self_is_available => {
190 format!("self.{}", path_str),
191 Applicability::MachineApplicable,
194 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
198 format!("Self::{}", path_str),
199 Applicability::MachineApplicable,
203 return (err, candidates);
207 let mut levenshtein_worked = false;
209 // Try Levenshtein algorithm.
210 let suggestion = self.lookup_typo_candidate(path, ns, is_expected, span);
211 if let Some(suggestion) = suggestion {
213 "{} {} with a similar name exists",
214 suggestion.article, suggestion.kind
219 suggestion.candidate.to_string(),
220 Applicability::MaybeIncorrect,
223 levenshtein_worked = true;
226 // Try context-dependent help if relaxed lookup didn't work.
227 if let Some(def) = def {
228 if self.smart_resolve_context_dependent_help(&mut err,
234 return (err, candidates);
239 if !levenshtein_worked {
240 err.span_label(base_span, fallback_label);
241 self.type_ascription_suggestion(&mut err, base_span);
246 fn followed_by_brace(&self, span: Span) -> (bool, Option<(Span, String)>) {
247 // HACK(estebank): find a better way to figure out that this was a
248 // parser issue where a struct literal is being used on an expression
249 // where a brace being opened means a block is being started. Look
250 // ahead for the next text to see if `span` is followed by a `{`.
251 let sm = self.session.source_map();
254 sp = sm.next_point(sp);
255 match sm.span_to_snippet(sp) {
257 if snippet.chars().any(|c| { !c.is_whitespace() }) {
264 let followed_by_brace = match sm.span_to_snippet(sp) {
265 Ok(ref snippet) if snippet == "{" => true,
268 // In case this could be a struct literal that needs to be surrounded
269 // by parenthesis, find the appropriate span.
271 let mut closing_brace = None;
273 sp = sm.next_point(sp);
274 match sm.span_to_snippet(sp) {
277 let sp = span.to(sp);
278 if let Ok(snippet) = sm.span_to_snippet(sp) {
279 closing_brace = Some((sp, snippet));
287 // The bigger the span, the more likely we're incorrect --
288 // bound it to 100 chars long.
293 return (followed_by_brace, closing_brace)
296 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
298 /// Returns `true` if able to provide context-dependent help.
299 fn smart_resolve_context_dependent_help(
301 err: &mut DiagnosticBuilder<'a>,
303 source: PathSource<'_>,
306 fallback_label: &str,
308 let ns = source.namespace();
309 let is_expected = &|def| source.is_expected(def);
311 let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.node {
312 ExprKind::Field(_, ident) => {
315 "use the path separator to refer to an item",
316 format!("{}::{}", path_str, ident),
317 Applicability::MaybeIncorrect,
321 ExprKind::MethodCall(ref segment, ..) => {
322 let span = expr.span.with_hi(segment.ident.span.hi());
325 "use the path separator to refer to an item",
326 format!("{}::{}", path_str, segment.ident),
327 Applicability::MaybeIncorrect,
334 let mut bad_struct_syntax_suggestion = || {
335 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
336 let mut suggested = false;
338 PathSource::Expr(Some(parent)) => {
339 suggested = path_sep(err, &parent);
341 PathSource::Expr(None) if followed_by_brace == true => {
342 if let Some((sp, snippet)) = closing_brace {
345 "surround the struct literal with parenthesis",
346 format!("({})", snippet),
347 Applicability::MaybeIncorrect,
351 span, // Note the parenthesis surrounding the suggestion below
352 format!("did you mean `({} {{ /* fields */ }})`?", path_str),
362 format!("did you mean `{} {{ /* fields */ }}`?", path_str),
367 match (def, source) {
368 (Def::Def(DefKind::Macro(..), _), _) => {
371 "use `!` to invoke the macro",
372 format!("{}!", path_str),
373 Applicability::MaybeIncorrect,
375 if path_str == "try" && span.rust_2015() {
376 err.note("if you want the `try` keyword, you need to be in the 2018 edition");
379 (Def::Def(DefKind::TyAlias, _), PathSource::Trait(_)) => {
380 err.span_label(span, "type aliases cannot be used as traits");
381 if nightly_options::is_nightly_build() {
382 err.note("did you mean to use a trait alias?");
385 (Def::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
386 if !path_sep(err, &parent) {
390 (Def::Def(DefKind::Enum, def_id), PathSource::TupleStruct)
391 | (Def::Def(DefKind::Enum, def_id), PathSource::Expr(..)) => {
392 if let Some(variants) = self.collect_enum_variants(def_id) {
393 if !variants.is_empty() {
394 let msg = if variants.len() == 1 {
395 "try using the enum's variant"
397 "try using one of the enum's variants"
400 err.span_suggestions(
403 variants.iter().map(path_names_to_string),
404 Applicability::MaybeIncorrect,
408 err.note("did you mean to use one of the enum's variants?");
411 (Def::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
412 if let Some((ctor_def, ctor_vis))
413 = self.struct_constructors.get(&def_id).cloned() {
414 let accessible_ctor = self.is_accessible(ctor_vis);
415 if is_expected(ctor_def) && !accessible_ctor {
418 format!("constructor is not visible here due to private fields"),
422 bad_struct_syntax_suggestion();
425 (Def::Def(DefKind::Union, _), _) |
426 (Def::Def(DefKind::Variant, _), _) |
427 (Def::Def(DefKind::Ctor(_, CtorKind::Fictive), _), _) if ns == ValueNS => {
428 bad_struct_syntax_suggestion();
430 (Def::SelfTy(..), _) if ns == ValueNS => {
431 err.span_label(span, fallback_label);
432 err.note("can't use `Self` as a constructor, you must use the implemented struct");
434 (Def::Def(DefKind::TyAlias, _), _)
435 | (Def::Def(DefKind::AssociatedTy, _), _) if ns == ValueNS => {
436 err.note("can't use a type alias as a constructor");
444 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
445 /// Adds suggestions for a path that cannot be resolved.
446 pub(crate) fn make_path_suggestion(
449 mut path: Vec<Segment>,
450 parent_scope: &ParentScope<'b>,
451 ) -> Option<(Vec<Segment>, Vec<String>)> {
452 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
454 match (path.get(0), path.get(1)) {
455 // `{{root}}::ident::...` on both editions.
456 // On 2015 `{{root}}` is usually added implicitly.
457 (Some(fst), Some(snd)) if fst.ident.name == keywords::PathRoot.name() &&
458 !snd.ident.is_path_segment_keyword() => {}
459 // `ident::...` on 2018.
460 (Some(fst), _) if fst.ident.span.rust_2018() &&
461 !fst.ident.is_path_segment_keyword() => {
462 // Insert a placeholder that's later replaced by `self`/`super`/etc.
463 path.insert(0, Segment::from_ident(keywords::Invalid.ident()));
468 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
469 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
470 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
471 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
474 /// Suggest a missing `self::` if that resolves to an correct module.
478 /// LL | use foo::Bar;
479 /// | ^^^ did you mean `self::foo`?
481 fn make_missing_self_suggestion(
484 mut path: Vec<Segment>,
485 parent_scope: &ParentScope<'b>,
486 ) -> Option<(Vec<Segment>, Vec<String>)> {
487 // Replace first ident with `self` and check if that is valid.
488 path[0].ident.name = keywords::SelfLower.name();
489 let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
490 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
491 if let PathResult::Module(..) = result {
492 Some((path, Vec::new()))
498 /// Suggests a missing `crate::` if that resolves to an correct module.
502 /// LL | use foo::Bar;
503 /// | ^^^ did you mean `crate::foo`?
505 fn make_missing_crate_suggestion(
508 mut path: Vec<Segment>,
509 parent_scope: &ParentScope<'b>,
510 ) -> Option<(Vec<Segment>, Vec<String>)> {
511 // Replace first ident with `crate` and check if that is valid.
512 path[0].ident.name = keywords::Crate.name();
513 let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
514 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
515 if let PathResult::Module(..) = result {
519 "`use` statements changed in Rust 2018; read more at \
520 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
521 clarity.html>".to_string()
529 /// Suggests a missing `super::` if that resolves to an correct module.
533 /// LL | use foo::Bar;
534 /// | ^^^ did you mean `super::foo`?
536 fn make_missing_super_suggestion(
539 mut path: Vec<Segment>,
540 parent_scope: &ParentScope<'b>,
541 ) -> Option<(Vec<Segment>, Vec<String>)> {
542 // Replace first ident with `crate` and check if that is valid.
543 path[0].ident.name = keywords::Super.name();
544 let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
545 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
546 if let PathResult::Module(..) = result {
547 Some((path, Vec::new()))
553 /// Suggests a missing external crate name if that resolves to an correct module.
557 /// LL | use foobar::Baz;
558 /// | ^^^^^^ did you mean `baz::foobar`?
561 /// Used when importing a submodule of an external crate but missing that crate's
562 /// name as the first part of path.
563 fn make_external_crate_suggestion(
566 mut path: Vec<Segment>,
567 parent_scope: &ParentScope<'b>,
568 ) -> Option<(Vec<Segment>, Vec<String>)> {
569 if path[1].ident.span.rust_2015() {
573 // Sort extern crate names in reverse order to get
574 // 1) some consistent ordering for emitted dignostics, and
575 // 2) `std` suggestions before `core` suggestions.
576 let mut extern_crate_names =
577 self.resolver.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
578 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
580 for name in extern_crate_names.into_iter() {
581 // Replace first ident with a crate name and check if that is valid.
582 path[0].ident.name = name;
583 let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
584 debug!("make_external_crate_suggestion: name={:?} path={:?} result={:?}",
586 if let PathResult::Module(..) = result {
587 return Some((path, Vec::new()));
594 /// Suggests importing a macro from the root of the crate rather than a module within
598 /// help: a macro with this name exists at the root of the crate
600 /// LL | use issue_59764::makro;
601 /// | ^^^^^^^^^^^^^^^^^^
603 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
604 /// at the root of the crate instead of the module where it is defined
606 pub(crate) fn check_for_module_export_macro(
608 directive: &'b ImportDirective<'b>,
609 module: ModuleOrUniformRoot<'b>,
611 ) -> Option<(Option<Suggestion>, Vec<String>)> {
612 let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
618 while let Some(parent) = crate_module.parent {
619 crate_module = parent;
622 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
623 // Don't make a suggestion if the import was already from the root of the
628 let resolutions = crate_module.resolutions.borrow();
629 let resolution = resolutions.get(&(ident, MacroNS))?;
630 let binding = resolution.borrow().binding()?;
631 if let Def::Def(DefKind::Macro(MacroKind::Bang), _) = binding.def() {
632 let module_name = crate_module.kind.name().unwrap();
633 let import = match directive.subclass {
634 ImportDirectiveSubclass::SingleImport { source, target, .. } if source != target =>
635 format!("{} as {}", source, target),
636 _ => format!("{}", ident),
639 let mut corrections: Vec<(Span, String)> = Vec::new();
640 if !directive.is_nested() {
641 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
642 // intermediate segments.
643 corrections.push((directive.span, format!("{}::{}", module_name, import)));
645 // Find the binding span (and any trailing commas and spaces).
646 // ie. `use a::b::{c, d, e};`
648 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
649 self.resolver.session, directive.span, directive.use_span,
651 debug!("check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
652 found_closing_brace, binding_span);
654 let mut removal_span = binding_span;
655 if found_closing_brace {
656 // If the binding span ended with a closing brace, as in the below example:
657 // ie. `use a::b::{c, d};`
659 // Then expand the span of characters to remove to include the previous
660 // binding's trailing comma.
661 // ie. `use a::b::{c, d};`
663 if let Some(previous_span) = extend_span_to_previous_binding(
664 self.resolver.session, binding_span,
666 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
667 removal_span = removal_span.with_lo(previous_span.lo());
670 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
672 // Remove the `removal_span`.
673 corrections.push((removal_span, "".to_string()));
675 // Find the span after the crate name and if it has nested imports immediatately
676 // after the crate name already.
677 // ie. `use a::b::{c, d};`
679 // or `use a::{b, c, d}};`
681 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
682 self.resolver.session, module_name, directive.use_span,
684 debug!("check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
685 has_nested, after_crate_name);
687 let source_map = self.resolver.session.source_map();
689 // Add the import to the start, with a `{` if required.
690 let start_point = source_map.start_point(after_crate_name);
691 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
695 // In this case, `start_snippet` must equal '{'.
696 format!("{}{}, ", start_snippet, import)
698 // In this case, add a `{`, then the moved import, then whatever
700 format!("{{{}, {}", import, start_snippet)
705 // Add a `};` to the end if nested, matching the `{` added at the start.
707 corrections.push((source_map.end_point(after_crate_name),
712 let suggestion = Some((
714 String::from("a macro with this name exists at the root of the crate"),
715 Applicability::MaybeIncorrect,
718 "this could be because a macro annotated with `#[macro_export]` will be exported \
719 at the root of the crate instead of the module where it is defined".to_string(),
721 Some((suggestion, note))
728 /// Given a `binding_span` of a binding within a use statement:
731 /// use foo::{a, b, c};
735 /// then return the span until the next binding or the end of the statement:
738 /// use foo::{a, b, c};
741 pub(crate) fn find_span_of_binding_until_next_binding(
746 let source_map = sess.source_map();
748 // Find the span of everything after the binding.
749 // ie. `a, e};` or `a};`
750 let binding_until_end = binding_span.with_hi(use_span.hi());
752 // Find everything after the binding but not including the binding.
753 // ie. `, e};` or `};`
754 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
756 // Keep characters in the span until we encounter something that isn't a comma or
760 // Also note whether a closing brace character was encountered. If there
761 // was, then later go backwards to remove any trailing commas that are left.
762 let mut found_closing_brace = false;
763 let after_binding_until_next_binding = source_map.span_take_while(
764 after_binding_until_end,
766 if ch == '}' { found_closing_brace = true; }
767 ch == ' ' || ch == ','
771 // Combine the two spans.
774 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
775 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
777 (found_closing_brace, span)
780 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
784 /// use foo::a::{a, b, c};
785 /// ^^--- binding span
789 /// use foo::{a, b, c};
792 pub(crate) fn extend_span_to_previous_binding(
796 let source_map = sess.source_map();
798 // `prev_source` will contain all of the source that came before the span.
799 // Then split based on a command and take the first (ie. closest to our span)
800 // snippet. In the example, this is a space.
801 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
803 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
804 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
805 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
809 let prev_comma = prev_comma.first().unwrap();
810 let prev_starting_brace = prev_starting_brace.first().unwrap();
812 // If the amount of source code before the comma is greater than
813 // the amount of source code before the starting brace then we've only
814 // got one item in the nested item (eg. `issue_52891::{self}`).
815 if prev_comma.len() > prev_starting_brace.len() {
819 Some(binding_span.with_lo(BytePos(
820 // Take away the number of bytes for the characters we've found and an
821 // extra for the comma.
822 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1
826 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
827 /// it is a nested use tree.
830 /// use foo::a::{b, c};
831 /// ^^^^^^^^^^ // false
833 /// use foo::{a, b, c};
834 /// ^^^^^^^^^^ // true
836 /// use foo::{a, b::{c, d}};
837 /// ^^^^^^^^^^^^^^^ // true
839 fn find_span_immediately_after_crate_name(
844 debug!("find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
845 module_name, use_span);
846 let source_map = sess.source_map();
848 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
849 let mut num_colons = 0;
850 // Find second colon.. `use issue_59764:`
851 let until_second_colon = source_map.span_take_while(use_span, |c| {
852 if *c == ':' { num_colons += 1; }
854 ':' if num_colons == 2 => false,
858 // Find everything after the second colon.. `foo::{baz, makro};`
859 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
861 let mut found_a_non_whitespace_character = false;
862 // Find the first non-whitespace character in `from_second_colon`.. `f`
863 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
864 if found_a_non_whitespace_character { return false; }
865 if !c.is_whitespace() { found_a_non_whitespace_character = true; }
869 // Find the first `{` in from_second_colon.. `foo::{`
870 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
872 (next_left_bracket == after_second_colon, from_second_colon)