Skip to content

Instantly share code, notes, and snippets.

@schneems
Created March 26, 2025 02:43
Show Gist options
  • Save schneems/6e27cc2e7fe8dea212f95ed9e154bbc7 to your computer and use it in GitHub Desktop.
Save schneems/6e27cc2e7fe8dea212f95ed9e154bbc7 to your computer and use it in GitHub Desktop.

Daft snapshot testing analysis

This investigates the daft crate and categorizes the error cases:

  • Emit code and errors (Warning error)
  • Emit code only, no errors (Compile error)
  • Emit errors only, no code (Error)

When to emit cases: Emit code and errors (Warning)

All "warning" errors happen because the attributes cannot have any effect on the outcome. In my analysis, I found two cases where I feel we could safely emit code, but aren't:

  • Code in: field-specified-multiple-times.rs
    • Errors emitted
    • Generated code out: Empty
    • Why I think it's okay to emit code here: This code has the same attribute repeated several times. This could happen if someone deleted a field but forgot to delete it's attribute. It should be cleaned up, but since all signals point to the same intention we should be able to emit generated code, but are not.
  • Code in: struct-specified-multiple-times.rs
    • Errors emitted
    • Generated code out: Empty
    • Why I think it's okay to emit code here: This code has the same problem as field-specified-multiple-times.rs but the duplicate attribute is on the container (struct) rather than the field. The intent is clear, code generation should be possible

Fail and do not emit code

When to emit cases: Emit code but no error

  • Code in: struct-field-not-diffable.rs
    • Errors emitted
    • Generated code out
    • Why it's okay to emit code: No error is found at macro time, the error comes from the compiler because of the emitted code, not despite it. The macro cannot reflect whether a given struct has an implementation or not. Therefore, it must emit the code to let the compiler issue a warning.

This failure mode is fairly normal for a macro as we don't have enough reflective power to detect the error. While reflection tools in a language like Ruby might allow us to query the capabilities of an object duck.respond_to?(:quack), there's currently no way to ask Rust "does this struct implement this trait?" So there's nothing else the macro could do other than emit code and let the compiler produce a (hopefully) helpful error message.

@schneems
Copy link
Author

Please don't leave comments here. I won't be notified about them. Message me on mastodon please.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment