Sunder
Sunder

Reputation: 1513

Is there a way to see what a Crystal macro expands to?

I've a macro that refuses to work as expected and I was wondering if there was a way to see what it expands to, is there something like macroexpand-1 from lisp in Crystal? If so, how do I use it? Thanks!

Upvotes: 8

Views: 554

Answers (2)

rogerdpack
rogerdpack

Reputation: 66771

Appears another tool is crystal tool expand

ex file mapping_test.cr

require "json"
require "./json_mapping"# wget https://raw.githubusercontent.com/crystal-lang/json_mapping.cr/master/src/json_mapping.cr
class Location
  JSON.mapping(  # <---- line: 4, column: 3
    lat: Float64,
    lng: Float64,
  )
end

run it like this:

crystal tool expand -c mapping_test.cr:4:3 mapping_test.cr (must be right location or within the macro at least, or will get "no expansion found"

output

1 expansion found
expansion 1:
   JSON.mapping(lat: Float64, lng: Float64)

# expand macro 'JSON.mapping' (/home/a/json_mapping.cr:236:3)
~> ::JSON.mapping({lat: {type: Float64, key_id: lat}, lng: {type: Float64, key_id: lng}})

...

ref https://groups.google.com/g/crystal-lang/c/L7ADzhRQGLk

Upvotes: 1

Stephie
Stephie

Reputation: 3175

Placing {% debug %} at the end of the macro will print it's contents at compile time.

e.g.

macro foo
  ...
  {% debug %}
end

Upvotes: 13

Related Questions