Rollup merge of #156797 - ariagivens:suggest-quotes, r=JonathanBrouwer

Suggest adding quotation marks to identifiers in attributes

When the user provides an identifier when a literal was expected in an attribute value, suggest adding quotation marks to the identifier to make it a string literal.

For instance:
```
error: attribute value must be a literal
  --> $DIR/crate-type-non-crate.rs:9:16
   |
LL | #[crate_type = lib]
   |                ^^^ help: try adding quotation marks: `"lib"`
```
This commit is contained in:
Matthias Krüger
2026-05-28 07:53:36 +02:00
committed by GitHub
4 changed files with 22 additions and 9 deletions
+15 -2
View File
@@ -12,7 +12,7 @@
AttrArgs, Expr, ExprKind, LitKind, MetaItemLit, Path, PathSegment, StmtKind, UnOp,
};
use rustc_ast_pretty::pprust;
use rustc_errors::{Diag, PResult};
use rustc_errors::{Applicability, Diag, PResult};
use rustc_hir::{self as hir, AttrPath};
use rustc_parse::exp;
use rustc_parse::parser::{ForceCollect, Parser, PathStyle, Recovery, token_descr};
@@ -410,7 +410,20 @@ fn expr_to_lit<'sess>(
// - `#[foo = include_str!("nonexistent-file.rs")]`:
// results in `ast::ExprKind::Err`.
let msg = "attribute value must be a literal";
let err = psess.dcx().struct_span_err(span, msg);
let mut err = psess.dcx().struct_span_err(span, msg);
// Suggest adding quotation marks to turn an identifier into a string literal
if let ExprKind::Path(None, ref path) = expr.kind
&& let [segment] = path.segments.as_slice()
{
err.span_suggestion(
expr.span,
"try adding quotation marks",
&format!("\"{}\"", segment.ident),
Applicability::MaybeIncorrect,
);
}
Err(err)
}
}