Skip to content

Error parsing Option<()> and Result<(), ()> literals in syn::parse_macro_input: unexpected end of input, expected an expression #1726

@cartercanedy

Description

@cartercanedy

I'm having issues with handling Option::<()>::Some(()) and Result::<(), ()>::Ok(()) literals in my macro.

Below is the gist of the macro that I've implemented, doesn't really stray from the documentation:

use syn::punctuated::Punctuated;
use syn::parse::{Parse, ParseStream};
use syn::{parse_macro_input, Token, Expr};

struct Args {
  args: Punctuated<Expr, Token![,]>,
}

impl Parse for Args {
  fn parse(input: ParseStream) -> syn::Result<Self> {
    Ok(Self { args: Punctuated::<Expr, Token![,]>::parse_terminated(input)? })
  }
}

#[proc_macro]
pub fn foo(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
  let args = parse_macro_input!(input as Args); // __this is where it fails__
  // ...
}

I have a proc_macro2 test that also confirms this behavior with both std prelude and fully qualified forms:

// Fails with Some(())...
syn::parse_macro_input(proc_macro2::TokenStream::from_str("Some(())").unwrap()); // error: expected '()', found 'TokenStream'
syn::parse_macro_input(proc_macro2::TokenStream::from_str("Option::<()>::Some(())").unwrap()); // error: expected '()', found 'TokenStream'

// and with Ok(())
syn::parse_macro_input(proc_macro2::TokenStream::from_str("Ok(())").unwrap()); // error: expected '()', found 'TokenStream'
syn::parse_macro_input(proc_macro2::TokenStream::from_str("Result::<(), ()>::Ok(())").unwrap()); // error: expected '()', found 'TokenStream'

The error that gets emitted from these tests is expected '()', found 'TokenStream'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions