Search code examples
rustrust-macrosrust-proc-macros

In a procedural macro, how can I check if a string is a valid variable name and not a keyword?


In a procedural macro, I wish to be able to check a string is a valid variable name and is not a keyword.

proc_macro2::Ident will panic if one tries to use an invalid variable name, but it will allow keywords which I do not want to be allowed. It would also be nicer to handle the error with a nice and useful error message before panicking.

Is there some macro or function (in a crate or otherwise) that will check a string obeys the rules about variable names? I could probably do it with a regex, but dragons live in regexes.

The use case for this is in handling user input strings, which may include garbage strings.


Solution

  • You can use Ident::parse from the syn crate. It will fail if the input is a keyword:

    use syn::{Ident, parse::Parse as _};
    
    let ident = parse_stream.call(Ident::parse)?;
    

    From the documentation:

    An identifier constructed with Ident::new is permitted to be a Rust keyword, though parsing one through its Parse implementation rejects Rust keywords.