Skip to content

Commit b847e88

Browse files
committed
Specialized formatting for sorbet
1 parent 368889f commit b847e88

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
@@ -2222,6 +2222,7 @@ def initialize(node)
22222222

22232223
def format(q)
22242224
children = [node]
2225+
threshold = 3
22252226

22262227
# First, walk down the chain until we get to the point where we're not
22272228
# longer at a chainable node.
@@ -2238,7 +2239,27 @@ def format(q)
22382239
end
22392240
end
22402241

2241-
if children.length > 2
2242+
# Here, we have very specialized behavior where if we're within a sig
2243+
# block, then we're going to assume we're creating a Sorbet type
2244+
# signature. In that case, we really want the threshold to be lowered so
2245+
# that we create method chains off of any two method calls within the
2246+
# block. For more details, see
2247+
# https://github.com/prettier/plugin-ruby/issues/863.
2248+
parents = q.parents.take(4)
2249+
if parent = parents[2]
2250+
# If we're at a do_block, then we want to go one more level up. This is
2251+
# because do blocks have BodyStmt nodes instead of just Statements
2252+
# nodes.
2253+
parent = parents[3] if parent.is_a?(DoBlock)
2254+
2255+
case parent
2256+
in MethodAddBlock[call: FCall[value: { value: "sig" }]]
2257+
threshold = 2
2258+
else
2259+
end
2260+
end
2261+
2262+
if children.length >= threshold
22422263
q.group { q.if_break { format_chain(q, children) }.if_flat { node.format_contents(q) } }
22432264
else
22442265
node.format_contents(q)
@@ -2329,18 +2350,20 @@ def self.chained?(node)
23292350
# For certain nodes, we want to attach directly to the end and don't
23302351
# want to indent the first call. So we'll pop off the first children and
23312352
# format it separately here.
2332-
def attach_directly?(child)
2353+
def attach_directly?(node)
23332354
[ArrayLiteral, HashLiteral, Heredoc, If, Unless, XStringLiteral]
2334-
.include?(child.receiver.class)
2355+
.include?(node.receiver.class)
23352356
end
23362357

23372358
def format_child(q, child, skip_operator: false, skip_attached: false)
23382359
# First, format the actual contents of the child.
23392360
case child
23402361
in Call
2341-
q.format(CallOperatorFormatter.new(child.operator)) unless skip_operator
2342-
q.format(child.message) if child.message != :call
2343-
child.format_arguments(q) unless skip_attached
2362+
q.group do
2363+
q.format(CallOperatorFormatter.new(child.operator)) unless skip_operator
2364+
q.format(child.message) if child.message != :call
2365+
child.format_arguments(q) unless skip_attached
2366+
end
23442367
in MethodAddBlock
23452368
q.format(child.block) unless skip_attached
23462369
end

0 commit comments

Comments
 (0)