ruby-syntax-tree / syntax_tree

Interact with the Ruby syntax tree

Home Page:https://ruby-syntax-tree.github.io/syntax_tree/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

visit_methods don't work as commented in the readme

stoivo opened this issue · comments

commented

I would expect these three Visitors to work the same.

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'
  gem 'syntax_tree', '5.3.0'
end

require "syntax_tree"

class UnsaveVisitor < SyntaxTree::Visitor
  def visit_binary(node)
    if node in { left: SyntaxTree::Int, operator: :+ | :- | :* | :/, right: SyntaxTree::Int }
      puts "The result is: #{node.left.value.to_i.public_send(node.operator, node.right.value.to_i)}"
    end
  end
end

class VisitMethodVisitor < SyntaxTree::Visitor
  visit_method def visit_binary(node)
        if node in { left: SyntaxTree::Int, operator: :+ | :- | :* | :/, right: SyntaxTree::Int }
          puts "The result is: #{node.left.value.to_i.public_send(node.operator, node.right.value.to_i)}"
      end
    end
end


class VisitMethodsVisitor < SyntaxTree::Visitor
  visit_methods do
    def visit_binary(node)
        if node in { left: SyntaxTree::Int, operator: :+ | :- | :* | :/, right: SyntaxTree::Int }
          puts "The result is: #{node.left.value.to_i.public_send(node.operator, node.right.value.to_i)}"
      end
    end
  end
end


[UnsaveVisitor, VisitMethodVisitor, VisitMethodsVisitor]
  .each do |visitor|
    puts "visitor #{visitor}"
    visitor = visitor.new
    visitor.visit(SyntaxTree.parse("1 + 1"))
  end

# =>
# visitor UnsaveVisitor
# The result is: 2
# visitor VisitMethodVisitor
# The result is: 2
# visitor VisitMethodsVisitor

This is kinda funny.

visit_methods with the block isn't released yet. It'll be part of the next release.

There is a method call visit_methods, however, which contains an array of all of the allowed method names. You'd calling that method and then passing a block to it that never gets executed.

commented

ahh, I didn't think of that. Why does it take a block?

All methods in Ruby take blocks.