Skip to content

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

Open
@jymchng

Description

@jymchng

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions