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

Fix symbol and string literal types' to_s #1316

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
52 changes: 51 additions & 1 deletion lib/rbs/types.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1212,7 +1212,57 @@ def to_json(state = _ = nil)
end

def to_s(level = 0)
literal.inspect
case literal
when String
string_to_s(literal)
when Symbol
symbol_to_s(literal)
else
literal.inspect
end
end

private

def string_to_s(str)
content = str.chars.map do |c|
case c
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldnt a hash and [] work better? like str.chars.map { |c| SPECIAL_CHARS.fetch(c, c) } ?

when "\a"
"\\a"
when "\b"
"\\b"
when "\e"
"\\e"
when "\f"
"\\f"
when "\n"
"\\n"
when "\r"
"\\r"
when "\t"
"\\t"
when "\v"
"\\v"
when '"'
'\\"'
when '\\'
'\\\\'
else
c
end
end.join
'"' + content + '"'
end

def symbol_to_s(sym)
begin
r = ":#{sym}"
node = Parser.parse_type(r, require_eof: true)
return r if node.is_a?(self.class) && node.literal == sym
rescue RBS::ParsingError
end

":" + string_to_s(sym.to_s)
end
end
end
Expand Down
5 changes: 5 additions & 0 deletions sig/types.rbs
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,11 @@ module RBS
include NoTypeName

attr_reader location: loc?

private

def string_to_s: (String) -> String
def symbol_to_s: (Symbol) -> String
end
end
end
4 changes: 4 additions & 0 deletions test/rbs/types_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ def test_to_s
assert_equal '"foo"?', parse_type('"foo" ?').to_s
assert_equal '"foo\\\\n"', parse_type(%q{'foo\n'}).to_s
assert_equal '"foo\\n"', parse_type('"foo\n"').to_s
assert_equal '"\a"', parse_type(%Q{"\x07"}).to_s
assert_equal %Q{"\x03"}, parse_type(%Q{"\x03"}).to_s
assert_equal ":foo ?", parse_type(":foo ?").to_s
assert_equal ':":C"', parse_type(':":C"').to_s
assert_equal %Q{:"x\\n"}, parse_type(%Q{:"x\\n"}).to_s
assert_equal "[ Integer, bool? ]", parse_type("[Integer, bool?]").to_s
assert_equal "[ ]", parse_type("[ ]").to_s
assert_equal "{ }", Types::Record.new(fields: {}, location: nil).to_s # NOTE: parse_type("{ }") is syntax error
Expand Down