4 ms·
Macros can secretly add "unsafe" blocks into the code?
by codedokode 6mo ago
Macros can secretly add "unsafe" blocks into the code?
- mplanchard 6mo agoMacros are just text in, text out, so yep
- estebank 6mo agoRust macros are Token Trees and provide namespace hygiene, so not quite "text in, text out".
- 0x1ceb00da 6mo agoToken list, not token trees. There are official libraries for parsing token stream as rust code but you can parse it as anything (eg json, html) if you want to.
- estebank 6mo agoI think you meant TokenStream. They are trees, behind the scenes, because matching delimiters happens early on between lexing and parsing. By the time the rustc_proc_macro::TokenStream is exposed, the rustc_ast::tokenstream::TokenTree is hidden to the proc macro API. https://doc.rust-lang.org/stable/nightly-rustc/rustc_ast/tokenstream/index.html https://doc.rust-lang.org/stable/nightly-rustc/rustc_ast/tok... https://doc.rust-lang.org/stable/nightly-rustc/rustc_proc_macro/struct.TokenStream.html https://doc.rust-lang.org/stable/nightly-rustc/rustc_proc_ma...
- mplanchard 6mo agoYou know, I was going to say tokens rather than text, but the AI discourse has me so burnt out on the term that I edited it. Regardless, one can emit unsafe blocks from a macro, provided they are valid tokens.
- EFLKumo 6mo agoYes. It assumes author of the macro guarantees the safety. Common cases are not adding unsafe{} and leaving this to user, relying on audit tools or [highlighters](https://lukaswirth.dev/posts/semantic-unsafe/ https://lukaswirth.dev/posts/semantic-unsafe/), etc. However, it's indeed allowed to silently add unsafe blocks in macros. I'm not working on rust frequently btw, mistakes may exist.
- kibwen 6mo agoIf you're paranoid, you can use the `forbid(unsafe_code)` attribute, which will produce a compiler error when any code in its scope attempts to use `unsafe`, which includes macro expansions.