Crystal macros: write code that writes code at compile time

10 steps · about 3 h 40 min · Intermediate

  1. Chapter 9: Macros and Metaprogramming (guide, Crystal for Rubyists, 15 min)

    A gentle start that explains why Crystal has macros instead of eval, using one tiny define_method example.

  2. Macros - Crystal (doc, Crystal language reference, 40 min)

    The official reference covers interpolation, @type and the rule that generated code must itself be valid Crystal.

  3. Writing Macros in Crystal (blog, Will Richardson, 20 min)

    Practical tips such as {% debug %}, variables in {% %} and @type.stringify, to add right after the reference.

  4. Crystal::Macros - Crystal 1.19.1 (reference, Crystal API docs, 30 min)

    Lists the AST node methods you can call at compile time, plus p!, print, raise and flag? for debugging and checks.

  5. Hooks - Crystal (doc, Crystal language reference, 20 min)

    Covers inherited, included, method_added and finished, which let macros react to how types are defined.

  6. Annotations (doc, crystal-lang/crystal-book, 20 min)

    Annotations attach metadata that macros can read, which is the basis of declarative APIs such as JSON::Field.

  7. Utilizing Macros & Annotations in a Web Framework (blog, blacksmoke16 on DEV Community, 20 min)

    Shows annotations and the finished hook generating routes in a real framework.

  8. Add finished macro hook (article, crystal-lang/crystal on GitHub, 15 min)

    The original design discussion explains why finished exists and how it can gather data at compile time.

  9. Is it possible to run a macro at the very end of compilation? (blog, Crystal Forum, 10 min)

    Explains how finished ordering works and the nested-finished trick for running code last.

  10. Building Dependency Injection with Crystal Macros (blog, Will Richardson, 30 min)

    A capstone project that combines annotations, included hooks and nested finished macros into a working feature.