Skip to content

print raw lifetime idents with r# #144897

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions compiler/rustc_ast/src/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub use NtPatKind::*;
pub use TokenKind::*;
use rustc_macros::{Decodable, Encodable, HashStable_Generic};
use rustc_span::edition::Edition;
use rustc_span::symbol::IdentPrintMode;
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, kw, sym};
#[allow(clippy::useless_attribute)] // FIXME: following use of `hidden_glob_reexports` incorrectly triggers `useless_attribute` lint.
#[allow(hidden_glob_reexports)]
Expand Down Expand Up @@ -344,15 +345,24 @@ pub enum IdentIsRaw {
Yes,
}

impl From<bool> for IdentIsRaw {
fn from(b: bool) -> Self {
if b { Self::Yes } else { Self::No }
impl IdentIsRaw {
pub fn to_print_mode_ident(self) -> IdentPrintMode {
match self {
IdentIsRaw::No => IdentPrintMode::Normal,
IdentIsRaw::Yes => IdentPrintMode::RawIdent,
}
}
pub fn to_print_mode_lifetime(self) -> IdentPrintMode {
match self {
IdentIsRaw::No => IdentPrintMode::Normal,
IdentIsRaw::Yes => IdentPrintMode::RawLifetime,
}
}
}

impl From<IdentIsRaw> for bool {
fn from(is_raw: IdentIsRaw) -> bool {
matches!(is_raw, IdentIsRaw::Yes)
impl From<bool> for IdentIsRaw {
fn from(b: bool) -> Self {
if b { Self::Yes } else { Self::No }
}
}

Expand Down
17 changes: 8 additions & 9 deletions compiler/rustc_ast_pretty/src/pprust/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::sync::Arc;

use rustc_ast::attr::AttrIdGenerator;
use rustc_ast::ptr::P;
use rustc_ast::token::{self, CommentKind, Delimiter, IdentIsRaw, Token, TokenKind};
use rustc_ast::token::{self, CommentKind, Delimiter, Token, TokenKind};
use rustc_ast::tokenstream::{Spacing, TokenStream, TokenTree};
use rustc_ast::util::classify;
use rustc_ast::util::comments::{Comment, CommentStyle};
Expand Down Expand Up @@ -442,7 +442,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);

fn print_ident(&mut self, ident: Ident) {
self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
self.word(IdentPrinter::for_ast_ident(ident, ident.guess_print_mode()).to_string());
self.ann_post(ident)
}

Expand Down Expand Up @@ -1016,17 +1016,16 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere

/* Name components */
token::Ident(name, is_raw) => {
IdentPrinter::new(name, is_raw.into(), convert_dollar_crate).to_string().into()
IdentPrinter::new(name, is_raw.to_print_mode_ident(), convert_dollar_crate)
.to_string()
.into()
}
token::NtIdent(ident, is_raw) => {
IdentPrinter::for_ast_ident(ident, is_raw.into()).to_string().into()
IdentPrinter::for_ast_ident(ident, is_raw.to_print_mode_ident()).to_string().into()
}

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

/* Other */
Expand Down
16 changes: 11 additions & 5 deletions compiler/rustc_expand/src/proc_macro_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,20 +250,26 @@ impl FromInternal<(TokenStream, &mut Rustc<'_, '_>)> for Vec<TokenTree<TokenStre
Question => op("?"),
SingleQuote => op("'"),

Ident(sym, is_raw) => {
trees.push(TokenTree::Ident(Ident { sym, is_raw: is_raw.into(), span }))
}
Ident(sym, is_raw) => trees.push(TokenTree::Ident(Ident {
sym,
is_raw: matches!(is_raw, IdentIsRaw::Yes),
span,
})),
NtIdent(ident, is_raw) => trees.push(TokenTree::Ident(Ident {
sym: ident.name,
is_raw: is_raw.into(),
is_raw: matches!(is_raw, IdentIsRaw::Yes),
span: ident.span,
})),

Lifetime(name, is_raw) => {
let ident = rustc_span::Ident::new(name, span).without_first_quote();
trees.extend([
TokenTree::Punct(Punct { ch: b'\'', joint: true, span }),
TokenTree::Ident(Ident { sym: ident.name, is_raw: is_raw.into(), span }),
TokenTree::Ident(Ident {
sym: ident.name,
is_raw: matches!(is_raw, IdentIsRaw::Yes),
span,
}),
]);
}
NtLifetime(ident, is_raw) => {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_parse/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2191,7 +2191,7 @@ pub(crate) struct KeywordLifetime {
pub(crate) struct InvalidLabel {
#[primary_span]
pub span: Span,
pub name: Symbol,
pub name: String,
}

#[derive(Diagnostic)]
Expand Down
8 changes: 7 additions & 1 deletion compiler/rustc_parse/src/parser/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3083,7 +3083,13 @@ impl<'a> Parser<'a> {
if let Some((ident, is_raw)) = self.token.lifetime() {
// Disallow `'fn`, but with a better error message than `expect_lifetime`.
if matches!(is_raw, IdentIsRaw::No) && ident.without_first_quote().is_reserved() {
self.dcx().emit_err(errors::InvalidLabel { span: ident.span, name: ident.name });
self.dcx().emit_err(errors::InvalidLabel {
span: ident.span,
// `IntoDiagArg` prints the symbol as if it was an ident,
// so `'break` is printed as `r#break`. We don't want that
// here so convert to string eagerly.
name: ident.without_first_quote().name.to_string(),
});
}

self.bump();
Expand Down
26 changes: 11 additions & 15 deletions compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3112,7 +3112,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
} else {
self.suggest_introducing_lifetime(
&mut err,
Some(lifetime_ref.ident.name.as_str()),
Some(lifetime_ref.ident),
|err, _, span, message, suggestion, span_suggs| {
err.multipart_suggestion_verbose(
message,
Expand All @@ -3130,7 +3130,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
fn suggest_introducing_lifetime(
&self,
err: &mut Diag<'_>,
name: Option<&str>,
name: Option<Ident>,
suggest: impl Fn(
&mut Diag<'_>,
bool,
Expand Down Expand Up @@ -3177,7 +3177,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
let (span, sugg) = if span.is_empty() {
let mut binder_idents: FxIndexSet<Ident> = Default::default();
binder_idents.insert(Ident::from_str(name.unwrap_or("'a")));
binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));

// We need to special case binders in the following situation:
// Change `T: for<'a> Trait<T> + 'b` to `for<'a, 'b> T: Trait<T> + 'b`
Expand Down Expand Up @@ -3207,16 +3207,11 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
}
}

let binders_sugg = binder_idents.into_iter().enumerate().fold(
"".to_string(),
|mut binders, (i, x)| {
if i != 0 {
binders += ", ";
}
binders += x.as_str();
binders
},
);
let binders_sugg: String = binder_idents
.into_iter()
.map(|ident| ident.to_string())
.intersperse(", ".to_owned())
.collect();
let sugg = format!(
"{}<{}>{}",
if higher_ranked { "for" } else { "" },
Expand All @@ -3232,15 +3227,16 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
.source_map()
.span_through_char(span, '<')
.shrink_to_hi();
let sugg = format!("{}, ", name.unwrap_or("'a"));
let sugg =
format!("{}, ", name.map(|i| i.to_string()).as_deref().unwrap_or("'a"));
(span, sugg)
};

if higher_ranked {
let message = Cow::from(format!(
"consider making the {} lifetime-generic with a new `{}` lifetime",
kind.descr(),
name.unwrap_or("'a"),
name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
));
should_continue = suggest(
err,
Expand Down
70 changes: 57 additions & 13 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2505,10 +2505,16 @@ impl fmt::Debug for Ident {
/// except that AST identifiers don't keep the rawness flag, so we have to guess it.
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f)
fmt::Display::fmt(&IdentPrinter::new(self.name, self.guess_print_mode(), None), f)
}
}

pub enum IdentPrintMode {
Normal,
RawIdent,
RawLifetime,
}

/// The most general type to print identifiers.
///
/// AST pretty-printer is used as a fallback for turning AST structures into token streams for
Expand All @@ -2524,40 +2530,59 @@ impl fmt::Display for Ident {
/// done for a token stream or a single token.
pub struct IdentPrinter {
symbol: Symbol,
is_raw: bool,
mode: IdentPrintMode,
/// Span used for retrieving the crate name to which `$crate` refers to,
/// if this field is `None` then the `$crate` conversion doesn't happen.
convert_dollar_crate: Option<Span>,
}

impl IdentPrinter {
/// The most general `IdentPrinter` constructor. Do not use this.
pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option<Span>) -> IdentPrinter {
IdentPrinter { symbol, is_raw, convert_dollar_crate }
pub fn new(
symbol: Symbol,
mode: IdentPrintMode,
convert_dollar_crate: Option<Span>,
) -> IdentPrinter {
IdentPrinter { symbol, mode, convert_dollar_crate }
}

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

impl fmt::Display for IdentPrinter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_raw {
f.write_str("r#")?;
} else if self.symbol == kw::DollarCrate {
if let Some(span) = self.convert_dollar_crate {
let s = match self.mode {
IdentPrintMode::Normal
if self.symbol == kw::DollarCrate
&& let Some(span) = self.convert_dollar_crate =>
{
let converted = span.ctxt().dollar_crate_name();
if !converted.is_path_segment_keyword() {
f.write_str("::")?;
}
return fmt::Display::fmt(&converted, f);
converted
}
}
fmt::Display::fmt(&self.symbol, f)
IdentPrintMode::Normal => self.symbol,
IdentPrintMode::RawIdent => {
f.write_str("r#")?;
self.symbol
}
IdentPrintMode::RawLifetime => {
f.write_str("'r#")?;
let s = self
.symbol
.as_str()
.strip_prefix("'")
.expect("only lifetime idents should be passed with RawLifetime mode");
Symbol::intern(s)
}
};
s.fmt(f)
}
}

Expand Down Expand Up @@ -2949,6 +2974,25 @@ impl Ident {
self.name.can_be_raw() && self.is_reserved()
}

pub fn is_raw_lifetime_guess(self) -> bool {
// this should be kept consistent with `Parser::expect_lifetime` found under
// compiler/rustc_parse/src/parser/ty.rs
let name_without_apostrophe = self.without_first_quote();
name_without_apostrophe.name != self.name
&& ![kw::UnderscoreLifetime, kw::StaticLifetime].contains(&self.name)
&& name_without_apostrophe.is_raw_guess()
}

pub fn guess_print_mode(self) -> IdentPrintMode {
if self.is_raw_lifetime_guess() {
IdentPrintMode::RawLifetime
} else if self.is_raw_guess() {
IdentPrintMode::RawIdent
} else {
IdentPrintMode::Normal
}
}

/// Whether this would be the identifier for a tuple field like `self.0`, as
/// opposed to a named field like `self.thing`.
pub fn is_numeric(self) -> bool {
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/closures/issue-52437.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
fn main() {
[(); &(&'static: loop { |x| {}; }) as *const _ as usize]
//~^ ERROR: invalid label name `'static`
//~^ ERROR: invalid label name `static`
//~| ERROR: type annotations needed
}
2 changes: 1 addition & 1 deletion tests/ui/closures/issue-52437.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error: invalid label name `'static`
error: invalid label name `static`
--> $DIR/issue-52437.rs:2:13
|
LL | [(); &(&'static: loop { |x| {}; }) as *const _ as usize]
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/issues/issue-46311.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
fn main() {
'break: loop { //~ ERROR invalid label name `'break`
'break: loop { //~ ERROR invalid label name `break`
}
}
2 changes: 1 addition & 1 deletion tests/ui/issues/issue-46311.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error: invalid label name `'break`
error: invalid label name `break`
--> $DIR/issue-46311.rs:2:5
|
LL | 'break: loop {
Expand Down
4 changes: 2 additions & 2 deletions tests/ui/label/label-static.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
fn main() {
'static: loop { //~ ERROR invalid label name `'static`
break 'static //~ ERROR invalid label name `'static`
'static: loop { //~ ERROR invalid label name `static`
break 'static //~ ERROR invalid label name `static`
}
}
4 changes: 2 additions & 2 deletions tests/ui/label/label-static.stderr
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
error: invalid label name `'static`
error: invalid label name `static`
--> $DIR/label-static.rs:2:5
|
LL | 'static: loop {
| ^^^^^^^

error: invalid label name `'static`
error: invalid label name `static`
--> $DIR/label-static.rs:3:15
|
LL | break 'static
Expand Down
4 changes: 2 additions & 2 deletions tests/ui/label/label-underscore.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
fn main() {
'_: loop { //~ ERROR invalid label name `'_`
break '_ //~ ERROR invalid label name `'_`
'_: loop { //~ ERROR invalid label name `_`
break '_ //~ ERROR invalid label name `_`
}
}
4 changes: 2 additions & 2 deletions tests/ui/label/label-underscore.stderr
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
error: invalid label name `'_`
error: invalid label name `_`
--> $DIR/label-underscore.rs:2:5
|
LL | '_: loop {
| ^^

error: invalid label name `'_`
error: invalid label name `_`
--> $DIR/label-underscore.rs:3:15
|
LL | break '_
Expand Down
Loading
Loading