How do I extract the first argument from a function in tree-sitter

Viewed 302

Given that I have the code below in JavaScript/Typescript:

findOne('testing', () => {
});

findLegacy('testing2', () => {
});

findOne('testing3', () => {
});

I want to match the first argument of every function call using a tree-sitter query.

Here's where I got to, it matches all arguments

(call_expression arguments: (arguments) @arguments)

How do I match only the first argument?

As a bonus challenge, can I match the first argument of functions called findOne only?

1 Answers

How do I match only the first argument?

(call_expression
  arguments: (arguments ((string)+ @desc))
)

As a bonus challenge, can I match the first argument of functions called findOne only?

Yes. See Predicates section in the query syntax docs: https://tree-sitter.github.io/tree-sitter/using-parsers#query-syntax

(call_expression
  function: (identifier) @fn
  arguments: (arguments ((string)+ @desc))
  (#eq? @fn "findOne")
)
Related