Skip to content

Commit 2a25b37

Browse files
committed
Specialized formatting for sorbet
1 parent db96880 commit 2a25b37

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

lib/syntax_tree/node.rb

+29-6
Original file line numberDiff line numberDiff line change
@@ -2215,6 +2215,7 @@ def initialize(node)
22152215

22162216
def format(q)
22172217
children = [node]
2218+
threshold = 3
22182219

22192220
# First, walk down the chain until we get to the point where we're not
22202221
# longer at a chainable node.
@@ -2231,7 +2232,27 @@ def format(q)
22312232
end
22322233
end
22332234

2234-
if children.length > 2
2235+
# Here, we have very specialized behavior where if we're within a sig
2236+
# block, then we're going to assume we're creating a Sorbet type
2237+
# signature. In that case, we really want the threshold to be lowered so
2238+
# that we create method chains off of any two method calls within the
2239+
# block. For more details, see
2240+
# https://github.com/prettier/plugin-ruby/issues/863.
2241+
parents = q.parents.take(4)
2242+
if parent = parents[2]
2243+
# If we're at a do_block, then we want to go one more level up. This is
2244+
# because do blocks have BodyStmt nodes instead of just Statements
2245+
# nodes.
2246+
parent = parents[3] if parent.is_a?(DoBlock)
2247+
2248+
case parent
2249+
in MethodAddBlock[call: FCall[value: { value: "sig" }]]
2250+
threshold = 2
2251+
else
2252+
end
2253+
end
2254+
2255+
if children.length >= threshold
22352256
q.group { q.if_break { format_chain(q, children) }.if_flat { node.format_contents(q) } }
22362257
else
22372258
node.format_contents(q)
@@ -2322,18 +2343,20 @@ def self.chained?(node)
23222343
# For certain nodes, we want to attach directly to the end and don't
23232344
# want to indent the first call. So we'll pop off the first children and
23242345
# format it separately here.
2325-
def attach_directly?(child)
2346+
def attach_directly?(node)
23262347
[ArrayLiteral, HashLiteral, Heredoc, If, Unless, XStringLiteral]
2327-
.include?(child.receiver.class)
2348+
.include?(node.receiver.class)
23282349
end
23292350

23302351
def format_child(q, child, skip_operator: false, skip_attached: false)
23312352
# First, format the actual contents of the child.
23322353
case child
23332354
in Call
2334-
q.format(CallOperatorFormatter.new(child.operator)) unless skip_operator
2335-
q.format(child.message) if child.message != :call
2336-
child.format_arguments(q) unless skip_attached
2355+
q.group do
2356+
q.format(CallOperatorFormatter.new(child.operator)) unless skip_operator
2357+
q.format(child.message) if child.message != :call
2358+
child.format_arguments(q) unless skip_attached
2359+
end
23372360
in MethodAddBlock
23382361
q.format(child.block) unless skip_attached
23392362
end

0 commit comments

Comments
 (0)