Why is syn panicking instead of returning Expr::Verbatim when parsing custom syntax?

I have been writing a macro that scans blocks of code to look for identifiers prefixed with @, automatically calling to_owned() on them. It works roughly like this:

fn scan_expr_recursive(expr: &mut Expr) {
   Expr::Verbatim(tokens) => { // parse the identifier and the @ token, modify the expression to call #ident.to_owned() }
  ... => { //recursively scan the expression tree, concatenating the results to get a list of all identifiers used in this way}
}

#[proc_macro]
pub fn scan_expr(input: TokenStream) -> TokenStream {
    let mut to_scan = parse_macro_input!(input as Expr); //This fails
    let idents = scan_expr(&mut to_scan);
   quote!(#to_scan).into()
}


However, the parse! macro panics with "expected expression" as soon as it hits the @ token:

scan_expr!(@borrowed) //panic: expected expression

How can I configure syn to redirect unknown tokens to the Expr::Verbatim variant instead of panicking? Am I misunderstanding the point of the variant? It seems nonsensical to have a variant for un-parseable expressions and still panic when encountering such an expression.

AFAIK verbatim is for syntax that can be parsed, but cannot be represented in syn's types mainly due to backward compatibility.

1 Like

Do you know of a way to extend the Parsing logic of syn's primitives or do I have no choice but to re-implement Expr's parse logic and add an additional check for @ tokens?

Unfortunately I don't know a way to extend it. I think you'll have to reimplement it (maybe by copy-pasting syn's code?)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.