Skip to content

Commit

Permalink
parser: suggest quotes only for ident attribute values
Browse files Browse the repository at this point in the history
When encountering code like:

```
#[cfg(key = ["foo", "bar"])]
fn main() {}
```

the parser incorrectly suggests:

```
error: expected unsuffixed literal, found `[`
 --> ../pg/src/main.rs:1:13
  |
1 | #[cfg(key = ["foo", "bar"])]
  |             ^
  |
help: surround the identifier with quotation marks to parse it as a string
  |
1 | #[cfg(key =" "["foo", "bar"])]
  |            + +

error: aborting due to 1 previous error
```

This commit modifies the parser to check if an attribute value is an
ident before suggesting.
  • Loading branch information
ohno418 committed May 2, 2024
1 parent fcc06c8 commit ea04951
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
5 changes: 4 additions & 1 deletion compiler/rustc_parse/src/parser/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,10 @@ impl<'a> Parser<'a> {
// Check for unquoted idents in meta items, e.g.: #[cfg(key = foo)]
// `from_expansion()` ensures we don't suggest for cases such as
// `#[cfg(feature = $expr)]` in macros
if self.prev_token == token::Eq && !self.token.span.from_expansion() {
if self.token.is_ident()
&& self.prev_token == token::Eq
&& !self.token.span.from_expansion()
{
let before = self.token.span.shrink_to_lo();
while matches!(self.token.kind, token::Ident(..)) {
self.bump();
Expand Down
7 changes: 7 additions & 0 deletions tests/ui/attributes/suggest_quoting_values_only_for_idents.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Ensures to suggest quoting attribute values only when they are identifiers.

#[doc(alias = "val")]
#[doc(alias = val)] //~ ERROR expected unsuffixed literal, found `val`
#[doc(alias = ["va", "al"])] //~ ERROR expected unsuffixed literal or identifier, found `[`
#[doc(alias = &["va", "al"])] //~ ERROR expected unsuffixed literal or identifier, found `&`
fn main() {}
25 changes: 25 additions & 0 deletions tests/ui/attributes/suggest_quoting_values_only_for_idents.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
error: expected unsuffixed literal, found `val`
--> $DIR/suggest_quoting_values_only_for_idents.rs:4:15
|
LL | #[doc(alias = val)]
| ^^^
|
help: surround the identifier with quotation marks to parse it as a string
|
LL | #[doc(alias = "val")]
| + +

error: expected unsuffixed literal or identifier, found `[`
--> $DIR/suggest_quoting_values_only_for_idents.rs:5:15
|
LL | #[doc(alias = ["va", "al"])]
| ^

error: expected unsuffixed literal or identifier, found `&`
--> $DIR/suggest_quoting_values_only_for_idents.rs:6:15
|
LL | #[doc(alias = &["va", "al"])]
| ^

error: aborting due to 3 previous errors

0 comments on commit ea04951

Please sign in to comment.