Browse Source

Fix spaces around operators when nesting calls

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.
pull/19/head
Fredrik Ekre 2 years ago
parent
commit
04a20b7c30
No known key found for this signature in database
GPG Key ID: DE82E6D5E364C0A2
  1. 12
      src/chisels.jl
  2. 11
      src/runestone.jl
  3. 5
      test/runtests.jl

12
src/chisels.jl

@ -49,6 +49,18 @@ function first_leaf(node::JuliaSyntax.GreenNode) @@ -49,6 +49,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

11
src/runestone.jl

@ -209,18 +209,13 @@ function spaces_around_x(ctx::Context, node::JuliaSyntax.GreenNode, is_x::F) whe @@ -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]

5
test/runtests.jl

@ -130,6 +130,11 @@ end @@ -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

Loading…
Cancel
Save