From efab8961a9683326d4b80fd2b81db009116546b5 Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Mon, 13 Jan 2025 15:03:34 +0900 Subject: [PATCH] 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: https://github.com/soutaro/rbs-inline/issues/174 --- lib/rbs/types.rb | 13 +++++++++++-- test/rbs/types_test.rb | 4 ++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/lib/rbs/types.rb b/lib/rbs/types.rb index 1edcffa87..8fd1aa69c 100644 --- a/lib/rbs/types.rb +++ b/lib/rbs/types.rb @@ -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 + end + end + if level > 0 - "(#{types.join(" | ")})" + "(#{strs.join(" | ")})" else - types.join(" | ") + strs.join(" | ") end end diff --git a/test/rbs/types_test.rb b/test/rbs/types_test.rb index 2cb01b316..7cd1ceb45 100644 --- a/test/rbs/types_test.rb +++ b/test/rbs/types_test.rb @@ -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