Skip to content

Reference is incorrect about macro expanding expressions in builtin attributes #1806

Open
@mejrs

Description

@mejrs

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions