Skip to content

Commit

Permalink
Last result local '__' (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
veelenga committed Oct 7, 2017
1 parent b22934d commit 2c3946a
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
52 changes: 52 additions & 0 deletions spec/integration/icr_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -301,4 +301,56 @@ describe "icr command" do
CRYSTAL
icr(input).should match /42/
end

context "__" do
it "returns last value" do
icr("a = 42\n__").should match /42/
end

it "returns nil if there is no last value" do
icr("__").should match /nil/
end

context "in expressions" do
it "works with unary operators" do
icr("true\n!__").should match /false/
end

it "works with binary operators" do
icr("42\n__ + 1").should match /43/
icr("42\n1 + __").should match /43/
end

it "allows method calls" do
input = <<-CRYSTAL
"aabbcc"
__.count('a')
CRYSTAL
icr(input).should match /2/
end

it "works in methods/blocks" do
input = <<-CRYSTAL
38
def add(v)
__ + v
end
add(3)
-> { __ + 1 }.call
CRYSTAL

icr(input).should match /42/
end
end

it "is not interpreted as the last value if is a part of var name or literal" do
icr("__v = 0").should match /0/
icr("v__ = 0").should match /0/
icr("v__1 = 0").should match /0/
icr("filename = \"spec__helper.cr\"").should match /spec__helper.cr/
icr("require \"secure_random\"").should match /ok/
end
end
end
9 changes: 7 additions & 2 deletions src/icr/console.cr
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ module Icr
end
end

private def paste_mode()
private def paste_mode
puts "# Entering paste mode (ctrl-D to finish)"
input = String.build do |input|
loop do
input_line = Readline.readline()
input_line = Readline.readline

if input_line.nil?
puts "\n\n# Ctrl-D was pressed, exiting paste mode...\n"
Expand All @@ -58,7 +58,12 @@ module Icr
end
end

private def last_value
@executer.execute.value
end

private def process_command(command : String)
command = command.to_s.gsub(/\b__\b/) { last_value.to_s.strip }
result = check_syntax(command)
process_result(result, command)
end
Expand Down

0 comments on commit 2c3946a

Please sign in to comment.