Auto merge of #94584 - pnkfelix:inject-use-suggestion-sites, r=ekuber

More robust fallback for `use` suggestion

Our old way to suggest where to add `use`s would first look for pre-existing `use`s in the relevant crate/module, and if there are *no* uses, it would fallback on trying to use another item as the basis for the suggestion.

But this was fragile, as illustrated in issue #87613

This PR instead identifies span of the first token after any inner attributes, and uses *that* as the fallback for the `use` suggestion.

Fix #87613
This commit is contained in:
bors
2022-03-15 03:56:33 +00:00
27 changed files with 295 additions and 106 deletions

View File

@@ -27,8 +27,8 @@ use tracing::debug;
impl<'a> Parser<'a> {
/// Parses a source module as a crate. This is the main entry point for the parser.
pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
let (attrs, items, span) = self.parse_mod(&token::Eof)?;
Ok(ast::Crate { attrs, items, span, id: DUMMY_NODE_ID, is_placeholder: false })
let (attrs, items, spans) = self.parse_mod(&token::Eof)?;
Ok(ast::Crate { attrs, items, spans, id: DUMMY_NODE_ID, is_placeholder: false })
}
/// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
@@ -52,10 +52,11 @@ impl<'a> Parser<'a> {
pub fn parse_mod(
&mut self,
term: &TokenKind,
) -> PResult<'a, (Vec<Attribute>, Vec<P<Item>>, Span)> {
) -> PResult<'a, (Vec<Attribute>, Vec<P<Item>>, ModSpans)> {
let lo = self.token.span;
let attrs = self.parse_inner_attributes()?;
let post_attr_lo = self.token.span;
let mut items = vec![];
while let Some(item) = self.parse_item(ForceCollect::No)? {
items.push(item);
@@ -72,7 +73,9 @@ impl<'a> Parser<'a> {
}
}
Ok((attrs, items, lo.to(self.prev_token.span)))
let inject_use_span = post_attr_lo.data().with_hi(post_attr_lo.lo());
let mod_spans = ModSpans { inner_span: lo.to(self.prev_token.span), inject_use_span };
Ok((attrs, items, mod_spans))
}
}