4

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.

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
Henry Gomersall
  • 8,434
  • 3
  • 31
  • 54

1 Answers1

7

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.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • If the string is actually a string (say from a file) rather than a stream, you can do what you need using `syn::parse_str::("my_ident_str")?;` – Henry Gomersall Nov 19 '19 at 17:46