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

ident_str!(...) macro may not be robust sufficiently. #19813

Open
jymchng opened this issue Oct 11, 2024 · 0 comments
Open

ident_str!(...) macro may not be robust sufficiently. #19813

jymchng opened this issue Oct 11, 2024 · 0 comments
Assignees
Labels

Comments

@jymchng
Copy link

jymchng commented Oct 11, 2024

let is_valid = $crate::identifier::is_valid(s);
["String is not a valid Move identifier"][!is_valid as usize];

The check using 'out of range' error is not robust as one can easily turn it off by #![allow(conditional_panic)], as shown in this Playground. The program only panics at runtime instead of compile time which is not an expected behavior for ident_str!(...) that is advertised for checking valid identifier at compile time.

I suggest to use a dummy struct with an associated constant that does the assertion of is_valid at compile time like so:

struct _Whatever;
impl _Whatever {
    const IS_VALID: () =
            assert!($crate::is_valid(s), "String is not a valid Move identifier");
    }
_Whatever::IS_VALID;

This is more robust as the macro ident_str expands into {...; _Whatever::IS_VALID; and since _Whatever::IS_VALID is unconditionally evaluated at compile time, this will be a more robust way to check for valid IdentStr at compile time. Playground.

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

No branches or pull requests

5 participants