rust-lang / rust-lang/reference

Reference is incorrect about macro expanding expressions in builtin attributes

Open
#1,806 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-attributes A-macros
Dominant language
Rust
Stars
1.6k
Forks
607
PR merge metrics
PR metrics pending

Description

See https://doc.rust-lang.org/nightly/reference/attributes.html#r-attributes.meta.literal-expr

Syntax
MetaItem :
      [SimplePath]
   | [SimplePath] = [Expression]
   | [SimplePath] ( MetaSeq? )

MetaSeq :
   MetaItemInner ( , MetaItemInner )* ,?

MetaItemInner :
      MetaItem
   | [Expression]

Expressions in meta items must macro-expand to literal expressions, which must not
include integer or float type suffixes. Expressions which are not literal expressions
will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing.

To me this implies that #[attr(name= literal_expr!())]is valid, but it is not. It appears that macro expanding expressions in attributes only happens for #[attr = literal_expr!()].

For example (to take a random attribute that accepts multiple flavors of metaitem syntax):

#![feature(rustc_attrs)]
#![allow(internal_features)]

#[rustc_on_unimplemented = concat!("the", " ", "message")]
pub trait A {}

#[rustc_on_unimplemented(message = concat!("the", " ", "message"))]
pub trait B {}

Results in:

error: expected unsuffixed literal, found `concat`
 --> src/lib.rs:7:36
  |
7 | #[rustc_on_unimplemented(message = concat!("the", " ", "message"))]
  |                                    ^^^^^^
  |
help: surround the identifier with quotation marks to make it into a string literal
  |
7 | #[rustc_on_unimplemented(message = "concat"!("the", " ", "message"))]
  |                                    +      +

error: could not compile `playground` (lib) due to 1 previous error

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the referenced MetaItem and literal-expr section in the Rust Reference, then compare its wording with the two rustc_on_unimplemented examples in the issue. Verify which attribute forms expand expressions and revise the reference so its syntax and prose match the observed behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.