Is there a way to see what a Crystal macro expands to?
Asked Answered
P

2

8

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!

Prentiss answered 11/7, 2020 at 17:47 Comment(0)
N
13

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

e.g.

macro foo
  ...
  {% debug %}
end
Neon answered 11/7, 2020 at 20:12 Comment(1)
Awesome! Thank you!Prentiss
A
1

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

Amann answered 15/10, 2021 at 2:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.