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.
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 itsParse
implementation rejects Rust keywords.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.