Last active
April 5, 2016 10:53
-
-
Save oprypin/8b1c593b3782f10d6a71 to your computer and use it in GitHub Desktop.
Print last expression in a Crystal program
This file contains hidden or 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/syntax" | |
def transform_eval(source) | |
ast = Crystal::Parser.parse(source) | |
unless ast.is_a?(Crystal::Expressions) | |
ast = Crystal::Expressions.new([ast]) | |
end | |
exprs = (ast as Crystal::Expressions).expressions | |
case exprs.last | |
when Crystal::Require, Crystal::Def, Crystal::FunDef, | |
Crystal::Macro, Crystal::ClassDef, Crystal::LibDef | |
else | |
# Wrap last expression | |
expr = Crystal::Parser.parse(%[ | |
x.try { |e| puts "\\n#=> \#{e.inspect}" } | |
]) as Crystal::Call | |
expr.obj = exprs[-1] | |
exprs[-1] = expr | |
end | |
ast.to_s | |
rescue | |
source | |
end | |
puts transform_eval(ARGV[0]) |
This file contains hidden or 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
$ crystal build eval.cr | |
$ ./eval 'require "json"; JSON.parse(%({"a": [1,2,3]}))' | tee >(crystal eval) | |
require "json" | |
(JSON.parse("{\"a\": [1,2,3]}")).try do |e| | |
puts(" | |
#=> #{e.inspect}") | |
end | |
#=> {"a" => [1, 2, 3]} | |
$ ./eval 'queue = Channel(String).new(5); spawn { 10.times { queue.send "hello" }; queue.close }; Array.new(5) { queue.receive }.join' | tee >(crystal eval) | |
queue = Channel(String).new(5) | |
spawn do | |
10.times do | |
queue.send("hello") | |
end | |
queue.close | |
end | |
(Array.new(5) do | |
queue.receive | |
end).join.try do |e| | |
puts(" | |
#=> #{e.inspect}") | |
end | |
#=> "hellohellohellohellohello" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment