询问是否存在Clojure代码树结构可视化工具(含宏展开前后AST)
Great question! As someone who also started with Clojure as their first LISP, I totally get the excitement (and curiosity) around visualizing that core "code as data" principle—especially when macros are involved, since they rewrite the AST so drastically before evaluation. Here are some solid options for generating SVG-based tree visualizations for both pre- and post-macro-expansion states:
Local & Library-Based Tools
clj-ast-visualizer
This is a lightweight Clojure library you can add to your project via Leiningen or deps.edn. It lets you pass in raw code forms (pre-macro-expansion) or fully expanded forms (usingmacroexpand-allunder the hood, or you can feed in your own manually expanded code) and generates clean SVG tree diagrams. You can customize node colors, spacing, and even which parts of the AST to highlight, making it perfect for local development deep dives.REPL + Graphviz Workflow
If you prefer a do-it-yourself approach, you can combine Clojure's built-in AST traversal functions with Graphviz to generate SVGs. Here's a quick breakdown:- Use
read-stringto get the raw AST from your code (pre-expansion). - Use
macroexpand-1(for top-level macro expansion) ormacroexpand-all(for full nested expansion) to get the post-expansion AST. - Write a small helper function with
clojure.walkto convert the AST structure into Graphviz's DOT language syntax. - Run the
dot -Tsvg input.dot -o output.svgcommand to generate the SVG tree.
This method gives you full control over what gets visualized, which is great if you want to focus on specific parts of the AST.
- Use
Browser-Based Tools
- Clojure AST Explorer
A browser-based tool that lets you paste in Clojure code and toggle between pre- and post-macro-expansion views with a single click. It renders the AST as an interactive SVG tree—you can click nodes to expand or collapse nested structures, hover to see detailed syntax info, and export the final visualization as an SVG file. It's super handy for quick checks without setting up local dependencies.
Quick Tip
When working with macro expansion, remember the difference between macroexpand-1 and macroexpand-all:
macroexpand-1only expands the top-level macro, which is useful if you want to see step-by-step how a single macro transforms your code.macroexpand-allexpands every nested macro in the form, giving you the full AST that the Clojure evaluator will process.
Hope these tools help you get a clear visual handle on Clojure's AST—seeing the structure in action makes it way easier to wrap your head around how macros work!
内容的提问来源于stack exchange,提问作者MFave

