Skip to content

Instantly share code, notes, and snippets.

@kkuchta
Created September 29, 2022 19:42
Show Gist options
  • Save kkuchta/9f286954d90846a8b6e39f1ecd949b21 to your computer and use it in GitHub Desktop.
Save kkuchta/9f286954d90846a8b6e39f1ecd949b21 to your computer and use it in GitHub Desktop.
Block formatting example
require 'syntax_tree'
# Create a node visitor that walks the syntax tree looking for blocks.
class BlockFinder < SyntaxTree::Visitor
attr_reader :first_block
visit_method def visit_do_block(node)
puts "found a brace block node!"
@first_block ||= node
# Don't traverse further
end
visit_method def visit_brace_block(node)
puts "found a brace block node!"
@first_block ||= node
# Don't traverse further
end
end
input_string = "foo = bar() { |x| x + 1}"
root = SyntaxTree.parse(input_string)
# use that visitor to find the first, outermost block
visitor = BlockFinder.new
visitor.visit(root)
block_node = visitor.first_block
formatter = SyntaxTree::Formatter.new(input_string, [], 80)
# This throws an error:
# /Users/kevin/.rvm/gems/ruby-3.0.0/gems/syntax_tree-3.6.0/lib/syntax_tree/node.rb:1990:in `forced_do_end_bounds?': undefined method `call' for nil:NilClass
# formatter.format(block_node)
# But if I comment that line out and then fake that this block node is nested
# within a parent node, it works:
formatter.instance_variable_set(:@stack, [proc {SyntaxTree::Program.new(statements: [], location: nil)}])
formatter.format(block_node)
formatter.flush
output_string = formatter.output.join
puts output_string # Prints { |x| x + 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment