Skip to content

Commit

Permalink
Fixed #228: incorrect SymbolLiteral#to_s. Also fixed Symbol#inspect
Browse files Browse the repository at this point in the history
  • Loading branch information
Ary Borenszweig committed Oct 13, 2014
1 parent c3d22c6 commit aa42d6c
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 4 deletions.
8 changes: 8 additions & 0 deletions spec/compiler/parser/to_s_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,12 @@ describe "ASTNode#to_s" do
it "puts parenthesis in call argument if it's a cast" do
Parser.parse("foo(a as Int32)").to_s.should eq("foo((a as Int32))")
end

it "correctly convert a symbol that doesn't need qoutes" do
Parser.parse(%(:foo)).to_s.should eq(%(:foo))
end

it "correctly convert a symbol that needs qoutes" do
Parser.parse(%(:"{")).to_s.should eq(%(:"{"))
end
end
10 changes: 10 additions & 0 deletions spec/std/symbol_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
require "spec"

describe Symbol do
it "inspects" do
:foo.inspect.should eq(%(:foo))
:"{".inspect.should eq(%(:"{"))
:"hi there".inspect.should eq(%(:"hi there"))
# :かたな.inspect.should eq(%(:かたな))
end
end
13 changes: 10 additions & 3 deletions src/compiler/crystal/syntax/to_s.cr
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,22 @@ module Crystal
end

def visit(node : CharLiteral)
@str << node.value.inspect
node.value.inspect(@str)
end

def visit(node : SymbolLiteral)
@str << ":" << node.value
@str << ':'

value = node.value
if Symbol.needs_quotes?(value)
value.inspect(@str)
else
value.to_s(@str)
end
end

def visit(node : StringLiteral)
@str << node.value.inspect
node.value.inspect(@str)
end

def visit(node : StringInterpolation)
Expand Down
21 changes: 20 additions & 1 deletion src/symbol.cr
Original file line number Diff line number Diff line change
@@ -1,10 +1,29 @@
struct Symbol
def inspect(io : IO)
io << ":"
to_s io

value = to_s
if Symbol.needs_quotes?(value)
value.inspect(io)
else
value.to_s(io)
end
end

def to_s(io : IO)
io << to_s
end

# Determines if a string needs to be quoted to be used for a symbol.
def self.needs_quotes?(string)
string.each_char do |char|
case char
when '0'..'9', 'A'..'Z', 'a'..'z', '_'
# Nothing
else
return true
end
end
false
end
end

0 comments on commit aa42d6c

Please sign in to comment.