Proc_macro error handling

I am trying to provide better compile errors using quote_spanned and compile_error macro however compiler is giving a lot of nonsensical help messages. Is there a way to prevent this?
The only named struct fields are supported part is my actual error but compiler adds whole bunch of extra stuff

Please post the code you are using to generate the output. It's overwhelmingly likely that the compiler isn't "adding extra stuff", but your proc-macro indeed produces incorrect code.

pub type Result<T> = std::result::Result<T, TokenStream>;
pub fn fail(span: Span, txt: impl AsRef<str>) -> Result<Infallible>
{
	let txt = txt.as_ref();
	Err(quote_spanned! { span => compile_error!(#txt) }.into())
}

this is my method to fail with a span.

pub fn parse_root(i: &DeriveInput) -> crate::Result<(&DataStruct, &FieldsNamed)>
//{{{
{
	let _attrs = parse_attrs(i, &["name"])?; // top level
	match i.data {
		syn::Data::Struct(ref d) => match d.fields {
			syn::Fields::Named(ref f) => {
				if f.named.is_empty() {
					fail(i.ident.span(), "struct must have at least one named field")?;
					unreachable!()
				}
				Ok((d, f))
			}
			_ => {
				fail(i.ident.span(), "Only named struct fields are supported")?;
				unreachable!()
			}
		},
		_ => panic!("#[derive(Tbl)] can only be used on structs"),
	}
}```
and this is how I use it

For macros that use syn, syn::Error is the canonical way to do compile errors correctly. In your case maybe something like: syn::Error::new(span, txt).to_compile_error()

2 Likes

Oh I didnt even know such a method existed quote_spanned is all over the internet for some reason and the long waited Diagnostics API people talk about but syn::Error for some reason was not mentioned anywhere I checked

That fixed it all thanks :smiley:

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.