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 print macro #13336

Merged
merged 1 commit into from
May 22, 2023
Merged
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
9 changes: 9 additions & 0 deletions spec/compiler/macro/macro_methods_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3137,6 +3137,15 @@ module Crystal
end.should eq %(bar\n)
end

it "print" do
String.build do |io|
assert_macro(%({% print foo %}), "") do |program|
program.stdout = io
{foo: "bar".string}
end
end.should eq %(bar)
end

it "p" do
String.build do |io|
assert_macro(%({% p foo %}), "") do |program|
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/crystal/macros.cr
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,10 @@ module Crystal::Macros
def puts(*expressions) : Nop
end

# Prints AST nodes at compile-time. Useful for debugging macros.
def print(*expressions) : Nop
end

# Same as `puts`.
def p(*expressions) : Nop
end
Expand Down
14 changes: 14 additions & 0 deletions src/compiler/crystal/macros/methods.cr
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ module Crystal
interpret_parse_type(node)
when "puts"
interpret_puts(node)
when "print"
interpret_print(node)
when "p", "pp"
interpret_p(node)
when "p!", "pp!"
Expand Down Expand Up @@ -196,6 +198,18 @@ module Crystal
@last = Nop.new
end

def interpret_print(node)
node.args.each do |arg|
arg.accept self
last = @last
last = last.value if last.is_a?(StringLiteral)

@program.stdout.print last
end

@last = Nop.new
end

def interpret_p(node)
node.args.each do |arg|
arg.accept self
Expand Down