Created
June 30, 2015 21:58
-
-
Save bcardiff/a663b1ea1e8fd6a308cc to your computer and use it in GitHub Desktop.
Crystal AST dump
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "./ast_dump" | |
dump "[1,2,3].each do |e| | |
puts e | |
end" |
@radiospiel, sorry I've just notice your message. Take a look at crystal-lang/crystal#438 This involves almost the same requirement as building the crystal compiler, so checking if you are able to build a compiler is a good step for using this snippet.
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
With the current crystal this does not link, on osx at least:
what am I doing wrong?