Skip to content

Commit

Permalink
Fix spaces around operators when nesting calls
Browse files Browse the repository at this point in the history
The next leaf node might not be a direct grand child when nesting
operators. This patches introduces a function `replace_first_leaf` that
replaces the correct leaf.
  • Loading branch information
fredrikekre committed May 27, 2024
1 parent 7a8fb3e commit a1ee251
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
12 changes: 12 additions & 0 deletions src/chisels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ function first_leaf(node::JuliaSyntax.GreenNode)
end
end

function replace_first_leaf(node::JuliaSyntax.GreenNode, child′::JuliaSyntax.GreenNode)
if is_leaf(node)
return child′
else
children′ = copy(JuliaSyntax.children(node)::AbstractVector)
children′[1] = replace_first_leaf(children′[1], child′)
@assert length(children′) > 0
span′ = mapreduce(JuliaSyntax.span, +, children′; init = 0)
return JuliaSyntax.GreenNode(JuliaSyntax.head(node), span′, children′)
end
end

function last_leaf(node::JuliaSyntax.GreenNode)
if is_leaf(node)
return node
Expand Down
11 changes: 3 additions & 8 deletions src/runestone.jl
Original file line number Diff line number Diff line change
Expand Up @@ -209,18 +209,13 @@ function spaces_around_x(ctx::Context, node::JuliaSyntax.GreenNode, is_x::F) whe
any_changes && push!(children′, child)
else
# Replace the whitespace node of the child
grand_children = JuliaSyntax.children(child)[2:end]
pushfirst!(grand_children, ws)
span′ = mapreduce(JuliaSyntax.span, +, grand_children; init = 0)
@assert span′ == JuliaSyntax.span(child) - JuliaSyntax.span(child_ws) + 1
bytes_to_skip = JuliaSyntax.span(child) - span′
child′ = replace_first_leaf(child, ws)
@assert JuliaSyntax.span(child′) == JuliaSyntax.span(child) - JuliaSyntax.span(child_ws) + 1
bytes_to_skip = JuliaSyntax.span(child) - JuliaSyntax.span(child′)
@assert bytes_to_skip > 0
remaining_bytes_inclusive =
@view original_bytes[(span_sum + 1 + bytes_to_skip - JuliaSyntax.span(child)):end]
write_and_reset(ctx, remaining_bytes_inclusive)
child′ = JuliaSyntax.GreenNode(
JuliaSyntax.head(child), span′, grand_children,
)
any_changes = true
if children′ === children
children′ = children[1:i - 1]
Expand Down
5 changes: 5 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ end
"$(sp)(1 + 2):(1 + 3):(1 + 4)$(sp)"
# a^b
@test format_string("$(sp)a$(sp)^$(sp)b$(sp)") == "$(sp)a^b$(sp)"
# Edgecase when formatting whitespace in the next leaf, when the next leaf is a
# grand child or even younger. Note that this test depends a bit on where
# JuliaSyntax.jl decides to place the K"Whitespace" node.
@test format_string("$(sp)a$(sp)+$(sp)b$(sp)*$(sp)c$(sp)/$(sp)d$(sp)") ==
"$(sp)a + b * c / d$(sp)"
end
end

Expand Down

0 comments on commit a1ee251

Please sign in to comment.