Experimental Macro Formatter: Simple string ↔ tokentree ↔ string

⚓ rust    📅 2025-04-26    👤 surdeus    👁️ 1      

surdeus

https://github.com/kouhe3/quickmacrofmt

As we all know, rustfmt skips formatting macros containing custom syntax. Here's an experimental solution I've developed:

In this example, the to_hash_map macro accepts K:V pairs as input tokens and converts them into a HashMap structure. Since rustfmt doesn't format K:V pairs, I created a fmt.rs binary program. This program:

  1. Locates the positions of fmtbegin and fmtend comments in the code

  2. Parses the lines between these comments

  3. Converts them into syn token structures

  4. Uses a custom to_string method to convert the token structures back to strings

  5. Inserts the formatted result into the source code at the comment locations

This approach maintains code readability while working around rustfmt's limitations with custom macro syntax.

2 posts - 1 participant

Read full topic

🏷️ rust_feed