But when I try to add $crate:: to the TokenStream, it errors out with:
error: expected expression, found `$`
--> tests/macros.rs:12:14
|
12 | let x2 = tinystr4!("foo");
| ^^^^^^^^^^^^^^^^ expected expression
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error
error: could not compile `tinystr-macros`.
To learn more, run the command again with --verbose.
As far as I know, there’s no built-in way to do this, but you can read the CARGO_PKG_NAME environment variable to figure out whether it’s your crate or a downstream user’s that the macro is being expanded into.
I’m admittedly not very experienced with proc macros, so I may be misremembering something. While searching for the Rust issue where I saw that this is a known problem, I ran across proc-macro-crate that has a more robust way to handle this.
I don't know, but I would assume that it outputs $crate verbatim, which is then handled by the declarative macro around the procedural macro. At least, that's how I understand that proc-macro-hack works, but I'm not 100% sure.