tree-sitter / tree-sitter-ruby

Ruby grammar for tree-sitter

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Query to get the body of a method

olimorris opened this issue · comments

commented

In other languages there are nodes which allow you to easily get the body of a method (or function in their case). In Java, Lua and Python there are body: block nodes for example.

Is there a way to easily get the body of a method in Ruby?

With the following code snippet

def method_no_params
  # Just some dumb comment
  puts "cool"
end

def method_with_params(a)
  test = 1
  test_other = 11

  [test, test_other].each do |v|
    puts "#{a} #{v}"
  end
end

How would you extract everything in between the def and end lines? My current thinking is that maybe doing something with #make-range! is the only way we could accomplish it.

commented

Taking this from here:

 ((method . name: (identifier) (method_parameters)? . (_) @function.inner (_)? @function.end .)
   (#make-range! "function.inner" @function.inner @function.end)) @function.outer

get's me somewhere close:

Screen Shot 2022-05-24 at 23 26 37@2x

Beware of this:

def method_no_params; shadowed; end; def method_no_params; real_one; end

You have to return the last match. And yes this code exists in the wild (especially generated).

#224 will allow easily querying class, module, method, and block bodies.

commented

@npezza93 very intriguing. What does a query, before and after your pull request, look like?

You can see a before and after here. It's way quicker and simpler

commented

Oh boy. Yep that is an insane improvement! 👏🏼

Edit: Not to 💩 on the original work but it's a nightmare to work with. Any idea what the process is for this finding its way into official Playground?

Not to 💩 on the original work but it's a nightmare to work with.

Haha funny story, i actually wrote those original queries. Finally got tired of how slow it was to load those queries and decided to figure out how to tweak the grammar.

Any idea what the process is for this finding its way into official Playground?

No clue. Im a long time lurker, first time contributor to lower level treesitter stuff so not sure what the process is. Im guessing a new npm version has to be cut and then what ever repo that runs the site has to update it's packages.

commented

I've never actually noticed a performance issue with them, just when I came to add ruby support to refactoring.nvim, getting the body of a method was really challenging compared to most other languages.

Great to see some dialog on the pull request though. Will be following it closely!