Skip to content

Commit

Permalink
Union#to_s follows RBS/Lint/AmbiguousOperatorPrecedence
Browse files Browse the repository at this point in the history
At present, the result of `Union#to_s` does not respect
`RBS/Lint/AmbiguousOperatorPrecedence` cop from rubocop-on-rbs.

It would be better to wrap intersections in unions by paranthesis.

* Before: `Integer | String & bool`
* After:  `Integer | (String & bool)`

ref: soutaro/rbs-inline#174
  • Loading branch information
tk0miya committed Jan 13, 2025
1 parent d421a15 commit 09a3328
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
13 changes: 11 additions & 2 deletions lib/rbs/types.rb
Original file line number Diff line number Diff line change
Expand Up @@ -751,10 +751,19 @@ def sub(s)
end

def to_s(level = 0)
strs = types.map do |ty|
case ty
when Intersection
ty.to_s([1, level].max)
else
ty.to_s(level)
end
end

if level > 0
"(#{types.join(" | ")})"
"(#{strs.join(" | ")})"
else
types.join(" | ")
strs.join(" | ")
end
end

Expand Down
4 changes: 2 additions & 2 deletions test/rbs/types_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ def test_to_s
assert_equal "(String | bool)?", parse_type("(String | bool)?").to_s
assert_equal "String & bool?", parse_type("String & bool?").to_s
assert_equal "(String & bool)?", parse_type("(String & bool)?").to_s
assert_equal "Integer | String & bool", parse_type("Integer | String & bool").to_s
assert_equal "Integer | (String & bool)", parse_type("Integer | String & bool").to_s
assert_equal "(Integer | String) & bool", parse_type("(Integer | String) & bool").to_s
assert_equal "(Integer | String & bool)?", parse_type("(Integer | String & bool)?").to_s
assert_equal "(Integer | (String & bool))?", parse_type("(Integer | String & bool)?").to_s
assert_equal "((Integer | String) & bool)?", parse_type("((Integer | String) & bool)?").to_s
assert_equal "^() -> void", parse_type("^() -> void").to_s
assert_equal "(^() -> void)?", parse_type("(^() -> void)?").to_s
Expand Down

0 comments on commit 09a3328

Please sign in to comment.