Can I use negative integers in attributes

Hi there,
I was ondering wheather it is possible to put negative integers in attributes. Something like #[attribute(something_negative = -1)]. I read that normally, integers (which, IMO, can be negative) are accepted in arguments (RFC: Allow all literals in attributes by SergioBenitez · Pull Request #1559 · rust-lang/rfcs · GitHub), but I read in the Reference that the minus sign is not part of the literal (Tokens - The Rust Reference).

So, is there a way to have negative integers in attributes or not? I can give a minimal working example if necessary.

1 Like

I don't have a confident answer, but based on the Reference I believe a negative integer could be used in the expression portion of the attribute or parsed from a string literal.

The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign ( = ) followed by an expression.

I am fairly certain that things have changed significantly since that RFC. Inside of the parentheses in your example, any arbitrary token stream is allowed. e.g.

// These are all valid
#[attribute(something_negative = -1)]
#[attribute(something_missing =)]
#[attribute(gobbledy * gook())]

This stabilized tracking issue seems to confirm.

On that page you might notice a PATH = TOKEN_TREE code snippet, however this is referring specifically to #[attribute = thing] without any inner parentheses. At first, I thought that this might not allow a negative integer in this limited location due to "not being a single token tree," but I get a somewhat different error from what I expected:

Compiling playground v0.0.1 (/playground)
error: unexpected token: `-1`
 --> src/
1 | #[foo = -1]
  |         ^^
1 Like

Looks like the thing after the equality sign is, in fact, a single token tree wrapped in invisible delimiters - checked with this code:

#[foo = -1 + 1]
fn main() {}


error: unexpected token: `-1 + 1`
 --> src/
1 | #[foo = -1 + 1]
  |         ^^^^^^

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.