Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add read_file macro method #2791

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions spec/compiler/macro/macro_methods_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1039,4 +1039,18 @@ describe "macro methods" do
assert_macro "", %({{flag?(:foo)}}), [] of ASTNode, %(false)
end
end

describe "read_file" do
it "reads file (exists)" do
run(%q<
{{read_file("#{__DIR__}/../data/build")}}
>, filename = __FILE__).to_string.should eq(File.read("#{__DIR__}/../data/build"))
end

it "reads file (doesn't exists)" do
run(%q<
{{read_file("#{__DIR__}/../data/build_foo")}} ? 10 : 20
>, filename = __FILE__).to_i.should eq(20)
end
end
end
11 changes: 11 additions & 0 deletions src/compiler/crystal/macros.cr
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,17 @@ module Crystal::Macros
def raise(message) : NoReturn
end

# Reads a file: if it exists, returns a StringLiteral with its contents;
# otherwise `nil` is returned.
#
# To read a file relative to where the macro is defined, use:
#
# ```
# read_file("#{__DIR__}/some_file.txt")
# ```
def read_file(filename) : StringLiteral | NilLiteral
end

# Compiles and execute a Crystal program and returns its output
# as a `MacroId`.
#
Expand Down
16 changes: 16 additions & 0 deletions src/compiler/crystal/macros/methods.cr
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ module Crystal
interpret_system(node)
when "raise"
interpret_raise(node)
when "read_file"
interpret_read_file(node)
when "run"
interpret_run(node)
else
Expand Down Expand Up @@ -94,6 +96,20 @@ module Crystal
@last = Nop.new
end

def interpret_read_file(node)
if node.args.size == 1
node.args[0].accept self
filename = @last.to_macro_id
if File.exists?(filename)
@last = StringLiteral.new(File.read(filename))
else
@last = NilLiteral.new
end
else
node.wrong_number_of_arguments "macro call 'read_file'", node.args.size, 1
end
end

def interpret_system(node)
cmd = node.args.map do |arg|
arg.accept self
Expand Down