Rollup merge of #95970 - WaffleLapkin:nicer_trait_suggestions, r=compiler-errors

Fix suggestions in case of `T:` bounds

This PR fixes a corner case in `suggest_constraining_type_params` that was causing incorrect suggestions.

For the following functions:
```rust
fn a<T:>(t: T) { [t, t]; }
fn b<T>(t: T) where T: { [t, t]; }
```

We previously suggested the following:
```text
...
help: consider restricting type parameter `T`
  |
1 | fn a<T: Copy:>(t: T) { [t, t]; }
  |       ++++++
...
help: consider further restricting this bound
  |
2 | fn b<T>(t: T) where T: + Copy { [t, t]; }
  |                        ++++++
```

Note that neither `T: Copy:` not `where T: + Copy` is a correct bound.

With this commit the suggestions are correct:
```text
...
help: consider restricting type parameter `T`
  |
1 | fn a<T: Copy>(t: T) { [t, t]; }
  |         ++++
...
help: consider further restricting this bound
  |
2 | fn b<T>(t: T) where T: Copy { [t, t]; }
  |                        ++++
```

r? `@compiler-errors`

I've tried fixing #95898 here too, but got too confused with how `suggest_traits_to_import` works and what it does 😅
This commit is contained in:
Dylan DPC 2022-04-12 23:17:00 +02:00 committed by GitHub
commit d63a46ad28
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 124 additions and 9 deletions

View file

@ -17,7 +17,7 @@ use rustc_error_messages::MultiSpan;
use rustc_index::vec::IndexVec;
use rustc_macros::HashStable_Generic;
use rustc_span::hygiene::MacroKind;
use rustc_span::source_map::Spanned;
use rustc_span::source_map::{SourceMap, Spanned};
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{def_id::LocalDefId, BytePos, Span, DUMMY_SP};
use rustc_target::asm::InlineAsmRegOrRegClass;
@ -523,6 +523,40 @@ impl<'hir> GenericParam<'hir> {
})
.map(|sp| sp.shrink_to_hi())
}
/// Returns the span of `:` after a generic parameter.
///
/// For example:
///
/// ```text
/// fn a<T:>()
/// ^
/// | here
/// here |
/// v
/// fn b<T :>()
///
/// fn c<T
///
/// :>()
/// ^
/// |
/// here
/// ```
pub fn colon_span_for_suggestions(&self, source_map: &SourceMap) -> Option<Span> {
let sp = source_map
.span_extend_while(self.span.shrink_to_hi(), |c| c.is_whitespace() || c == ':')
.ok()?;
let snippet = source_map.span_to_snippet(sp).ok()?;
let offset = snippet.find(':')?;
let colon_sp = sp
.with_lo(BytePos(sp.lo().0 + offset as u32))
.with_hi(BytePos(sp.lo().0 + (offset + ':'.len_utf8()) as u32));
Some(colon_sp)
}
}
#[derive(Default)]