Skip to content

Commit

Permalink
Merge pull request #397 from Shopify/at-rbs-nilable-procs
Browse files Browse the repository at this point in the history
Protect nilable procs with parenthesis when translating to RBS
  • Loading branch information
Morriar authored Jan 15, 2025
2 parents 61cdaf1 + 08b26c2 commit e9e5148
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/rbi/rbs_printer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -891,7 +891,14 @@ def visit_attached_class(type)

sig { params(type: Type::Nilable).void }
def visit_nilable(type)
visit(type.type)
inner = type.type
if inner.is_a?(Type::Proc)
@string << "("
end
visit(inner)
if inner.is_a?(Type::Proc)
@string << ")"
end
@string << "?"
end

Expand Down Expand Up @@ -964,6 +971,12 @@ def visit_proc(type)
end
@string << ") "
end
proc_bind = type.proc_bind
if proc_bind
@string << "[self: "
visit(proc_bind)
@string << "] "
end
@string << "-> "
visit(type.proc_returns)
end
Expand Down
26 changes: 26 additions & 0 deletions test/rbi/rbs_printer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,32 @@ def e: -> Class[untyped]
RBI
end

def test_print_procs
rbi = parse_rbi(<<~RBI)
sig { params(x: T.nilable(T.proc.void)) }
def proc1(x); end
sig { params(x: T.proc.bind(T.untyped).void) }
def proc2(x); end
sig { params(block: T.nilable(T.proc.void)) }
def block1(&block); end
sig { params(block: T.proc.bind(T.untyped).void) }
def block2(&block); end
RBI

assert_equal(<<~RBI, rbi.rbs_string)
def proc1: ((^-> void)? x) -> void
def proc2: (^[self: untyped] -> void x) -> void
def block1: ?{ -> void } -> void
def block2: { [self: untyped] -> void } -> void
RBI
end

def test_print_t_structs
rbi = parse_rbi(<<~RBI)
class Foo < T::Struct; end
Expand Down

0 comments on commit e9e5148

Please sign in to comment.