Are you using macros with low-level code?


#1

I’m curious about how Rust macros are being used for very low-level programming. I’m currently planning some changes to the macro system and this is a domain where I am not familiar. If you’ve been writing a kernel, device driver, or something similar and you’ve used Rust macros, please tell me about your experience! Did they do the job? Was there friction anywhere? Are there areas where C macros are traditionally used where Rust macros were more awkward?

Thanks in advance!


#2

I am building kprintln! in the same way as println!, as is @phil-opp: https://github.com/intermezzOS/kernel/blob/original_backup/vga/src/lib.rs#L145-L159

I am pretty bad at macros, but it was easy to write, and works well. The format machinery is so nice… not having to write out all that stuff is just amazing.


#3

I’m writing a toy OS in Rust, and I’ve used a number of macros. I ended up using a bunch of macros to implement traits for some types, kernel-level println! like @steveklabnik’s, and a couple other simple macros to avoid writing repetitive code. Just like in other Rust projects, I’ve had a pretty good experience using macros. It’s nice that Rust’s macros, unlike the C preprocessor, actually have some static checking to make sure they’re reasonable.


#4

Do proofs of concept like wom count? It uses a macro (wom!) to allow write-only access to struct fields when the base struct is write only. The macro uses an unsafe block, so it can’t be used in no-unsafe crates even though it exposes a perfectly safe abstraction.


#5

Do you mean macro_rules! only, or also compiler plugins? Apparently Zinc is heavily based on the latter:


#6

I use macros quite extensively with inline assembly in my current project. This allows me to avoid code duplication when generating many similar asm! blocks.

Here is an example.


#7

Thanks for the links and comments everyone! Very useful, especially links to projects which use macros. You’re all too positive :slight_smile: Has anyone found things that don’t work very well or which are frustrating to work with?

@steveklabnik - that link is broken. By “format machinery” do you mean the concepts or the format! implementation stuff in the compiler/libs?

@SimonSapin both


#8

Sorry, I just broke that link today. Here’s the updated one, which should last a long time: https://github.com/intermezzOS/kernel/blob/master/src/vga/src/lib.rs#L135-L159