Skip to content

Latest commit

 

History

History
49 lines (35 loc) · 1.47 KB

macros.md

File metadata and controls

49 lines (35 loc) · 1.47 KB

Overview

Idioms

  1. Slow down :-)
  2. Write the code by hand first (in a regular *.rs file)
  3. make it compile & make tests pass
    1. compiler error messages are helpful and point to correct lines
  4. extract & generalize code block into the macro
  5. use cargo clean when you see unexpected behavior
  6. use cargo expand <module> to bring broken code back into regular rs file
    1. ... so the compiler can help you

Gotchas

  1. Horrible support in Jetbrains products
  2. When derive proc macro fails, compiler doesn't show failing line
    • -Zmacro-backtrace does NOT help
  3. Jetbrains Debugger doesn't work inside proc macro code
  4. Error messages won't tell you which line in the macro is broken

Debugging

  1. worst case: use panic!("{:?}", x) to print things

Cargo expand (for macros)

  1. Expands attributes on structs, fields, etc
  2. Works even when code doesn't compile

Steps

  1. cargo install cargo-expand
  2. put example code in one rs file (eg. tests/example.rs)
  3. put test module (with assertions) in separate file (eg. tests/example_tests.rs)
cd $DIR_WITH_CARGO_TOML

TEST_RS_FILE_WITHOUT_EXTENSION=my_test
cargo expand --test $TEST_RS_FILE_WITHOUT_EXTENSION --color=always --theme=Dracula --tests

Write by hand

  1. Write the code by hand (eg. the impl)
  2. fix all compiler errors, then bring result back to the macro (and generalize)

Other Resources