CPS (AKA macro variables & let expressions)
TLDR:
use cps;
;
}
Why?
Reason 1 - Maintainability
Macro execution order is confusing. Because each macro is passed a token tree, macros execute outside-in. For example:
Reading the above code as if macros are classical functions, you may expect this program to print woof. However unfortunately it prints dog!(), as if println! expands its macros while stringify! does not. This makes macros hard to maintain.
The Little Book of Macros describes callbacks, where a macro takes as an argument the next macro to execute. This leads to the following improved version of the above example:
While now having the correct behaviour, this is difficult to maintain as the flow of execution is confusing. Using CPS instead we get:
;
}
Reason 2 - Expanding macros
The let expressions in CPS macros must be built from other CPS macros, but the body doesn't. This allows us to add computation to be substituted in to macros developed by other people.
For example:
// Non-CPS macro from another crate
;
}
This crate comes with a collection of CPS macros that are copies of macros in the standard library, that can be used to perform compile-time computation on token trees in a maintainable way.