Skip to content

Commit e4af53b

Browse files
committed
print raw lifetime idents with r#
1 parent 2e2642e commit e4af53b

File tree

7 files changed

+166
-48
lines changed

7 files changed

+166
-48
lines changed

compiler/rustc_ast/src/token.rs

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ pub use NtPatKind::*;
77
pub use TokenKind::*;
88
use rustc_macros::{Decodable, Encodable, HashStable_Generic};
99
use rustc_span::edition::Edition;
10+
use rustc_span::symbol::IdentPrintMode;
1011
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, kw, sym};
1112
#[allow(clippy::useless_attribute)] // FIXME: following use of `hidden_glob_reexports` incorrectly triggers `useless_attribute` lint.
1213
#[allow(hidden_glob_reexports)]
@@ -344,15 +345,24 @@ pub enum IdentIsRaw {
344345
Yes,
345346
}
346347

347-
impl From<bool> for IdentIsRaw {
348-
fn from(b: bool) -> Self {
349-
if b { Self::Yes } else { Self::No }
348+
impl IdentIsRaw {
349+
pub fn to_print_mode_ident(self) -> IdentPrintMode {
350+
match self {
351+
IdentIsRaw::No => IdentPrintMode::Normal,
352+
IdentIsRaw::Yes => IdentPrintMode::RawIdent,
353+
}
354+
}
355+
pub fn to_print_mode_lifetime(self) -> IdentPrintMode {
356+
match self {
357+
IdentIsRaw::No => IdentPrintMode::Normal,
358+
IdentIsRaw::Yes => IdentPrintMode::RawLifetime,
359+
}
350360
}
351361
}
352362

353-
impl From<IdentIsRaw> for bool {
354-
fn from(is_raw: IdentIsRaw) -> bool {
355-
matches!(is_raw, IdentIsRaw::Yes)
363+
impl From<bool> for IdentIsRaw {
364+
fn from(b: bool) -> Self {
365+
if b { Self::Yes } else { Self::No }
356366
}
357367
}
358368

compiler/rustc_ast_pretty/src/pprust/state.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use std::borrow::Cow;
1010
use std::sync::Arc;
1111

1212
use rustc_ast::attr::AttrIdGenerator;
13-
use rustc_ast::token::{self, CommentKind, Delimiter, IdentIsRaw, Token, TokenKind};
13+
use rustc_ast::token::{self, CommentKind, Delimiter, Token, TokenKind};
1414
use rustc_ast::tokenstream::{Spacing, TokenStream, TokenTree};
1515
use rustc_ast::util::classify;
1616
use rustc_ast::util::comments::{Comment, CommentStyle};
@@ -441,7 +441,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
441441
fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
442442

443443
fn print_ident(&mut self, ident: Ident) {
444-
self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
444+
self.word(IdentPrinter::for_ast_ident(ident, ident.guess_print_mode()).to_string());
445445
self.ann_post(ident)
446446
}
447447

@@ -1015,17 +1015,16 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
10151015

10161016
/* Name components */
10171017
token::Ident(name, is_raw) => {
1018-
IdentPrinter::new(name, is_raw.into(), convert_dollar_crate).to_string().into()
1018+
IdentPrinter::new(name, is_raw.to_print_mode_ident(), convert_dollar_crate)
1019+
.to_string()
1020+
.into()
10191021
}
10201022
token::NtIdent(ident, is_raw) => {
1021-
IdentPrinter::for_ast_ident(ident, is_raw.into()).to_string().into()
1023+
IdentPrinter::for_ast_ident(ident, is_raw.to_print_mode_ident()).to_string().into()
10221024
}
10231025

1024-
token::Lifetime(name, IdentIsRaw::No)
1025-
| token::NtLifetime(Ident { name, .. }, IdentIsRaw::No) => name.to_string().into(),
1026-
token::Lifetime(name, IdentIsRaw::Yes)
1027-
| token::NtLifetime(Ident { name, .. }, IdentIsRaw::Yes) => {
1028-
format!("'r#{}", &name.as_str()[1..]).into()
1026+
token::Lifetime(name, is_raw) | token::NtLifetime(Ident { name, .. }, is_raw) => {
1027+
IdentPrinter::new(name, is_raw.to_print_mode_lifetime(), None).to_string().into()
10291028
}
10301029

10311030
/* Other */

compiler/rustc_expand/src/proc_macro_server.rs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -250,20 +250,26 @@ impl FromInternal<(TokenStream, &mut Rustc<'_, '_>)> for Vec<TokenTree<TokenStre
250250
Question => op("?"),
251251
SingleQuote => op("'"),
252252

253-
Ident(sym, is_raw) => {
254-
trees.push(TokenTree::Ident(Ident { sym, is_raw: is_raw.into(), span }))
255-
}
253+
Ident(sym, is_raw) => trees.push(TokenTree::Ident(Ident {
254+
sym,
255+
is_raw: matches!(is_raw, IdentIsRaw::Yes),
256+
span,
257+
})),
256258
NtIdent(ident, is_raw) => trees.push(TokenTree::Ident(Ident {
257259
sym: ident.name,
258-
is_raw: is_raw.into(),
260+
is_raw: matches!(is_raw, IdentIsRaw::Yes),
259261
span: ident.span,
260262
})),
261263

262264
Lifetime(name, is_raw) => {
263265
let ident = rustc_span::Ident::new(name, span).without_first_quote();
264266
trees.extend([
265267
TokenTree::Punct(Punct { ch: b'\'', joint: true, span }),
266-
TokenTree::Ident(Ident { sym: ident.name, is_raw: is_raw.into(), span }),
268+
TokenTree::Ident(Ident {
269+
sym: ident.name,
270+
is_raw: matches!(is_raw, IdentIsRaw::Yes),
271+
span,
272+
}),
267273
]);
268274
}
269275
NtLifetime(ident, is_raw) => {

compiler/rustc_resolve/src/late/diagnostics.rs

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3094,7 +3094,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
30943094
} else {
30953095
self.suggest_introducing_lifetime(
30963096
&mut err,
3097-
Some(lifetime_ref.ident.name.as_str()),
3097+
Some(lifetime_ref.ident),
30983098
|err, _, span, message, suggestion, span_suggs| {
30993099
err.multipart_suggestion_verbose(
31003100
message,
@@ -3112,7 +3112,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
31123112
fn suggest_introducing_lifetime(
31133113
&self,
31143114
err: &mut Diag<'_>,
3115-
name: Option<&str>,
3115+
name: Option<Ident>,
31163116
suggest: impl Fn(
31173117
&mut Diag<'_>,
31183118
bool,
@@ -3159,7 +3159,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
31593159
let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
31603160
let (span, sugg) = if span.is_empty() {
31613161
let mut binder_idents: FxIndexSet<Ident> = Default::default();
3162-
binder_idents.insert(Ident::from_str(name.unwrap_or("'a")));
3162+
binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
31633163

31643164
// We need to special case binders in the following situation:
31653165
// Change `T: for<'a> Trait<T> + 'b` to `for<'a, 'b> T: Trait<T> + 'b`
@@ -3189,16 +3189,11 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
31893189
}
31903190
}
31913191

3192-
let binders_sugg = binder_idents.into_iter().enumerate().fold(
3193-
"".to_string(),
3194-
|mut binders, (i, x)| {
3195-
if i != 0 {
3196-
binders += ", ";
3197-
}
3198-
binders += x.as_str();
3199-
binders
3200-
},
3201-
);
3192+
let binders_sugg: String = binder_idents
3193+
.into_iter()
3194+
.map(|ident| ident.to_string())
3195+
.intersperse(", ".to_owned())
3196+
.collect();
32023197
let sugg = format!(
32033198
"{}<{}>{}",
32043199
if higher_ranked { "for" } else { "" },
@@ -3214,15 +3209,16 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
32143209
.source_map()
32153210
.span_through_char(span, '<')
32163211
.shrink_to_hi();
3217-
let sugg = format!("{}, ", name.unwrap_or("'a"));
3212+
let sugg =
3213+
format!("{}, ", name.map(|i| i.to_string()).as_deref().unwrap_or("'a"));
32183214
(span, sugg)
32193215
};
32203216

32213217
if higher_ranked {
32223218
let message = Cow::from(format!(
32233219
"consider making the {} lifetime-generic with a new `{}` lifetime",
32243220
kind.descr(),
3225-
name.unwrap_or("'a"),
3221+
name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
32263222
));
32273223
should_continue = suggest(
32283224
err,

compiler/rustc_span/src/symbol.rs

Lines changed: 57 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2522,10 +2522,16 @@ impl fmt::Debug for Ident {
25222522
/// except that AST identifiers don't keep the rawness flag, so we have to guess it.
25232523
impl fmt::Display for Ident {
25242524
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2525-
fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f)
2525+
fmt::Display::fmt(&IdentPrinter::new(self.name, self.guess_print_mode(), None), f)
25262526
}
25272527
}
25282528

2529+
pub enum IdentPrintMode {
2530+
Normal,
2531+
RawIdent,
2532+
RawLifetime,
2533+
}
2534+
25292535
/// The most general type to print identifiers.
25302536
///
25312537
/// AST pretty-printer is used as a fallback for turning AST structures into token streams for
@@ -2541,40 +2547,59 @@ impl fmt::Display for Ident {
25412547
/// done for a token stream or a single token.
25422548
pub struct IdentPrinter {
25432549
symbol: Symbol,
2544-
is_raw: bool,
2550+
mode: IdentPrintMode,
25452551
/// Span used for retrieving the crate name to which `$crate` refers to,
25462552
/// if this field is `None` then the `$crate` conversion doesn't happen.
25472553
convert_dollar_crate: Option<Span>,
25482554
}
25492555

25502556
impl IdentPrinter {
25512557
/// The most general `IdentPrinter` constructor. Do not use this.
2552-
pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option<Span>) -> IdentPrinter {
2553-
IdentPrinter { symbol, is_raw, convert_dollar_crate }
2558+
pub fn new(
2559+
symbol: Symbol,
2560+
mode: IdentPrintMode,
2561+
convert_dollar_crate: Option<Span>,
2562+
) -> IdentPrinter {
2563+
IdentPrinter { symbol, mode, convert_dollar_crate }
25542564
}
25552565

25562566
/// This implementation is supposed to be used when printing identifiers
25572567
/// as a part of pretty-printing for larger AST pieces.
25582568
/// Do not use this either.
2559-
pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter {
2560-
IdentPrinter::new(ident.name, is_raw, Some(ident.span))
2569+
pub fn for_ast_ident(ident: Ident, mode: IdentPrintMode) -> IdentPrinter {
2570+
IdentPrinter::new(ident.name, mode, Some(ident.span))
25612571
}
25622572
}
25632573

25642574
impl fmt::Display for IdentPrinter {
25652575
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2566-
if self.is_raw {
2567-
f.write_str("r#")?;
2568-
} else if self.symbol == kw::DollarCrate {
2569-
if let Some(span) = self.convert_dollar_crate {
2576+
let s = match self.mode {
2577+
IdentPrintMode::Normal
2578+
if self.symbol == kw::DollarCrate
2579+
&& let Some(span) = self.convert_dollar_crate =>
2580+
{
25702581
let converted = span.ctxt().dollar_crate_name();
25712582
if !converted.is_path_segment_keyword() {
25722583
f.write_str("::")?;
25732584
}
2574-
return fmt::Display::fmt(&converted, f);
2585+
converted
25752586
}
2576-
}
2577-
fmt::Display::fmt(&self.symbol, f)
2587+
IdentPrintMode::Normal => self.symbol,
2588+
IdentPrintMode::RawIdent => {
2589+
f.write_str("r#")?;
2590+
self.symbol
2591+
}
2592+
IdentPrintMode::RawLifetime => {
2593+
f.write_str("'r#")?;
2594+
let s = self
2595+
.symbol
2596+
.as_str()
2597+
.strip_prefix("'")
2598+
.expect("only lifetime idents should be passed with RawLifetime mode");
2599+
Symbol::intern(s)
2600+
}
2601+
};
2602+
s.fmt(f)
25782603
}
25792604
}
25802605

@@ -3009,6 +3034,25 @@ impl Ident {
30093034
self.name.can_be_raw() && self.is_reserved()
30103035
}
30113036

3037+
pub fn is_raw_lifetime_guess(self) -> bool {
3038+
// this should be kept consistent with `Parser::expect_lifetime` found under
3039+
// compiler/rustc_parse/src/parser/ty.rs
3040+
let name_without_apostrophe = self.without_first_quote();
3041+
name_without_apostrophe.name != self.name
3042+
&& ![kw::UnderscoreLifetime, kw::StaticLifetime].contains(&self.name)
3043+
&& name_without_apostrophe.is_raw_guess()
3044+
}
3045+
3046+
pub fn guess_print_mode(self) -> IdentPrintMode {
3047+
if self.is_raw_lifetime_guess() {
3048+
IdentPrintMode::RawLifetime
3049+
} else if self.is_raw_guess() {
3050+
IdentPrintMode::RawIdent
3051+
} else {
3052+
IdentPrintMode::Normal
3053+
}
3054+
}
3055+
30123056
/// Whether this would be the identifier for a tuple field like `self.0`, as
30133057
/// opposed to a named field like `self.thing`.
30143058
pub fn is_numeric(self) -> bool {
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Check that we properly suggest `r#fn` if we use it undeclared.
2+
// https://github.com/rust-lang/rust/issues/143150
3+
//
4+
//@ edition: 2021
5+
6+
fn a(_: dyn Trait + 'r#fn) {
7+
//~^ ERROR use of undeclared lifetime name `'r#fn` [E0261]
8+
}
9+
10+
trait Trait {}
11+
12+
struct Test {
13+
a: &'r#fn str,
14+
//~^ ERROR use of undeclared lifetime name `'r#fn` [E0261]
15+
}
16+
17+
trait Trait1<T>
18+
where T: for<'a> Trait1<T> + 'r#fn { }
19+
//~^ ERROR use of undeclared lifetime name `'r#fn` [E0261]
20+
21+
fn main() {}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
error[E0261]: use of undeclared lifetime name `'r#fn`
2+
--> $DIR/use-of-undeclared-raw-lifetimes.rs:6:21
3+
|
4+
LL | fn a(_: dyn Trait + 'r#fn) {
5+
| ^^^^^ undeclared lifetime
6+
|
7+
help: consider introducing lifetime `'r#fn` here
8+
|
9+
LL | fn a<'r#fn>(_: dyn Trait + 'r#fn) {
10+
| +++++++
11+
12+
error[E0261]: use of undeclared lifetime name `'r#fn`
13+
--> $DIR/use-of-undeclared-raw-lifetimes.rs:13:9
14+
|
15+
LL | a: &'r#fn str,
16+
| ^^^^^ undeclared lifetime
17+
|
18+
help: consider introducing lifetime `'r#fn` here
19+
|
20+
LL | struct Test<'r#fn> {
21+
| +++++++
22+
23+
error[E0261]: use of undeclared lifetime name `'r#fn`
24+
--> $DIR/use-of-undeclared-raw-lifetimes.rs:18:32
25+
|
26+
LL | where T: for<'a> Trait1<T> + 'r#fn { }
27+
| ^^^^^ undeclared lifetime
28+
|
29+
= note: for more information on higher-ranked polymorphism, visit https://doc.rust-lang.org/nomicon/hrtb.html
30+
help: consider making the bound lifetime-generic with a new `'r#fn` lifetime
31+
|
32+
LL - where T: for<'a> Trait1<T> + 'r#fn { }
33+
LL + where for<'r#fn, 'a> T: Trait1<T> + 'r#fn { }
34+
|
35+
help: consider introducing lifetime `'r#fn` here
36+
|
37+
LL | trait Trait1<'r#fn, T>
38+
| ++++++
39+
40+
error: aborting due to 3 previous errors
41+
42+
For more information about this error, try `rustc --explain E0261`.

0 commit comments

Comments
 (0)