Stream: general

Topic: Help with attribute macro basics


Kyle Strand (Nov 29 2019 at 18:08, on Zulip):

I'm trying to write a simple attribute-like macro for the first time and am having trouble. Would anyone be willing to walk through some bits with me?

For instance, the macro is defined in src/lib.rs, and I'm trying to write a test in tests/main.rs, and it seems the macro must be imported using the name of the crate rather than the crate keyword. I seem to be running in to a lot of confusing problems like this.

Kyle Strand (Nov 29 2019 at 18:12, on Zulip):

If anyone would like to take a look, the code is here: https://github.com/BatmanAoD/flexible_bin_heap

Kyle Strand (Nov 29 2019 at 18:28, on Zulip):

The error I'm currently seeing that I don't understand is:

error[E0214]: parenthesized type parameters may only be used with a `Fn` trait
  --> tests/main.rs:26:1
   |
26 | #[with_comparator(data2)]
   | ^^^^^^^^^^^^^^^^^^^^^^^^^
   | |
   | only `Fn` traits may use parentheses
   | help: use angle brackets instead: `#[with_comparator<data2)>`

The unmatched parenthesis in the help message is interesting but not enlightening. Comparing my macro against those in some other crates that use parentheses, I don't see the difference.

bjorn3 (Nov 29 2019 at 18:51, on Zulip):

https://github.com/BatmanAoD/flexible_bin_heap/blob/cf1bfe68ea8d31b2ee9d548f0b83f181fa0ad142/src/lib.rs#L53

That is true for derive macros, but not for attribute macros

bjorn3 (Nov 29 2019 at 18:52, on Zulip):

https://github.com/BatmanAoD/flexible_bin_heap/blob/cf1bfe68ea8d31b2ee9d548f0b83f181fa0ad142/src/lib.rs#L56

You accidentially used Option() instead of Option<>.

Kyle Strand (Nov 29 2019 at 21:05, on Zulip):

That is true for derive macros, but not for attribute macros

Thanks! I see the bit I missed in the reference now -- "The returned TokenStream replaces the item..."

Kyle Strand (Nov 29 2019 at 22:36, on Zulip):

You accidentially used Option() instead of Option<>.

Ahh, okay, that fiexes the "parenthesized type parameters" error; thank you! I thought that was referring to the parentheses around data2.

bjorn3 (Nov 29 2019 at 22:45, on Zulip):

These suggestions are just heuristics which often go wrong with macros

Kyle Strand (Nov 29 2019 at 23:06, on Zulip):

@bjorn3 That also gave me enough of an understanding of what it "looks like" when things go wrong to get it working entirely. Thanks again!

Kyle Strand (Nov 29 2019 at 23:07, on Zulip):

I'm still a bit surprised that use flexible_bin_heap::with_comparator works, while use crate::with_comparator doesn't, though.

bjorn3 (Nov 29 2019 at 23:13, on Zulip):

It normally uses def site hygiene, which means that it is like if you pasted the macro output in the file yourself, so names get resolved relative to the place you use the macro.

Last update: Dec 12 2019 at 00:50UTC