Skip to content

Commit efab896

Browse files
committed
Union#to_s should follow RBS/Lint/AmbiguousOperatorPrecedence
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
1 parent 991bacb commit efab896

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

lib/rbs/types.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -751,10 +751,19 @@ def sub(s)
751751
end
752752

753753
def to_s(level = 0)
754+
strs = types.map do |ty|
755+
case ty
756+
when Intersection
757+
ty.to_s([1, level].max)
758+
else
759+
ty.to_s
760+
end
761+
end
762+
754763
if level > 0
755-
"(#{types.join(" | ")})"
764+
"(#{strs.join(" | ")})"
756765
else
757-
types.join(" | ")
766+
strs.join(" | ")
758767
end
759768
end
760769

test/rbs/types_test.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@ def test_to_s
2323
assert_equal "(String | bool)?", parse_type("(String | bool)?").to_s
2424
assert_equal "String & bool?", parse_type("String & bool?").to_s
2525
assert_equal "(String & bool)?", parse_type("(String & bool)?").to_s
26-
assert_equal "Integer | String & bool", parse_type("Integer | String & bool").to_s
26+
assert_equal "Integer | (String & bool)", parse_type("Integer | String & bool").to_s
2727
assert_equal "(Integer | String) & bool", parse_type("(Integer | String) & bool").to_s
28-
assert_equal "(Integer | String & bool)?", parse_type("(Integer | String & bool)?").to_s
28+
assert_equal "(Integer | (String & bool))?", parse_type("(Integer | String & bool)?").to_s
2929
assert_equal "((Integer | String) & bool)?", parse_type("((Integer | String) & bool)?").to_s
3030
assert_equal "^() -> void", parse_type("^() -> void").to_s
3131
assert_equal "(^() -> void)?", parse_type("(^() -> void)?").to_s

0 commit comments

Comments
 (0)