Skip to content

Instantly share code, notes, and snippets.

@bcardiff
Created June 30, 2015 21:58
Show Gist options
  • Save bcardiff/a663b1ea1e8fd6a308cc to your computer and use it in GitHub Desktop.
Save bcardiff/a663b1ea1e8fd6a308cc to your computer and use it in GitHub Desktop.
Crystal AST dump
require "compiler/crystal/**"
class Object
def dump_inspect(io, level)
io << " " * level
to_s(io)
io << " :: " << self.class
end
end
macro dump_prop(name)
io << " " * (level+1) << {{name.stringify}} << ":\n"
if v = {{name}}
if v.is_a?(Array)
if v.empty?
io << " " * (level+2) << "[]"
end
v.each_with_index do |e, i|
io << " " * (level+2) << "[" << i << "]\n"
e.dump_inspect(io, level + 2)
end
else
v.dump_inspect(io, level + 2)
end
else
io << " " * (level+2) << "nil"
end
io << '\n'
end
module Crystal
abstract class ASTNode
macro def dump_inspect(io, level) : Int32
io << " " * level << {{@type.name}} << '\n'
{% for ivar, i in @type.instance_vars %}
{% unless {
"is_expansion": true,
"has_parenthesis": true,
"location": true,
"type": true,
"dirty": true,
"uses_with_scope": true,
"global": true,
"visited": true,
"name_column_number": true,
"name_length": true,
"doc": true,
}[ivar.stringify] %}
dump_prop @{{ivar}}
{% end %}
{% end %}
0
end
def dump_inspect(io)
dump_inspect(io, 0)
end
end
end
def dump(code)
parser = Crystal::Parser.new(code)
parser.parse.dump_inspect(STDOUT)
end
require "./ast_dump"
dump "[1,2,3].each do |e|
puts e
end"
@guipublic
Copy link

Hello,

I just tried this sample and I have the following error
Syntax error in src/crystal/ast_dump.cr:33: unexpected token: dump_inspect (parentheses are mandatory for macro arguments)

macro def dump_inspect(io, level) : Int32

The error is when I import the ast_dump file (require "./crystal/ast_dump"), which is a copy/paste of the snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment