Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bug] Cannot use negative integer as default #9

Open
Carter12s opened this issue Dec 20, 2022 · 6 comments
Open

[bug] Cannot use negative integer as default #9

Carter12s opened this issue Dec 20, 2022 · 6 comments

Comments

@Carter12s
Copy link

Minimum reproducible example:

use smart_default::SmartDefault

#[derive(SmartDefault)]
struct MyStruct {
    #[default = -1]
    x: i16
}

Gives compiler error:

$ cargo build
   Compiling smart_deafult_test v0.1.0 (/home/carter/smart_deafult_test)
error: unexpected token: `-1`
 --> src/lib.rs:5:17
  |
5 |     #[default = -1]
  |                 ^^

error: could not compile `smart_deafult_test` due to previous error

Removing the negative sign lets it compile perfectly.

Same result occurs on both rustc versions 1.60 and 1.66.
Using library version "0.6".

@Carter12s
Copy link
Author

I appears a workaround of:

#[default(_code = "-1")]

does work.

@Carter12s
Copy link
Author

It also appears this syntax is valid:

#[default(-1)]

Just not the '=' version shown in the documentation

@idanarye
Copy link
Owner

I checked, and this is not smart-default's doing - it properly parses and emits code for that case, and then something else is failing on this. I'm afraid there is nothing I can do...

@Carter12s
Copy link
Author

Okay... just to follow up that I'm not crazy...

Here is an example crate showing the bug in a repo: https://github.com/Carter12s/smart_default_test

Here is a CI run using the default github rust action replicating the failure: https://github.com/Carter12s/smart_default_test/actions/runs/3751186707/jobs/6371862293

@Carter12s
Copy link
Author

Also here's a PR adding a test case to the repo that reproduces the compiler failure:
#10

@tertsdiepraam
Copy link

I've been looking into this and it is (currently) expected behavior of the compiler. What happens is that it parses an arbitrary expression, which is required to macro-expand to a literal. It is documented like this in the Reference:

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.

Source: https://doc.rust-lang.org/reference/attributes.html#meta-item-attribute-syntax

I'm not exactly sure why this is required though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants