robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
36.9 KiB1172 linesraw
1--- @brief This Lua |treesitter-query| interface allows you to create queries and use them to parse
2--- text. See |vim.treesitter.query.parse()| for a working example.
3
4local api = vim.api
5local nvim_on = require('vim._core.util').nvim_on
6local language = require('vim.treesitter.language')
7local memoize = vim.func._memoize
8local cmp_ge = require('vim.treesitter._range').cmp_pos.ge
9
10local MODELINE_FORMAT = '^;+%s*inherits%s*:?%s*([a-z_,()]+)%s*$'
11local EXTENDS_FORMAT = '^;+%s*extends%s*$'
12
13local M = {}
14
15---Parsed query, see |vim.treesitter.query.parse()|
16---
17---@class vim.treesitter.Query
18---@field lang string parser language name
19---@field captures string[] list of (unique) capture names defined in query
20---@field info vim.treesitter.QueryInfo query context (e.g. captures, predicates, directives)
21---@field has_conceal_line boolean whether the query sets conceal_lines metadata
22---@field has_combined_injections boolean whether the query contains combined injections
23---@field query TSQuery userdata query object
24---@field private _processed_patterns table<integer, vim.treesitter.query.ProcessedPattern>
25local Query = {}
26Query.__index = Query
27
28---@param name string
29local function is_directive(name)
30  return string.sub(name, -1) == '!'
31end
32
33---@nodoc
34---@class vim.treesitter.query.ProcessedPredicate
35---@field [1] string predicate name
36---@field [2] boolean should match
37---@field [3] (integer|string)[] the original predicate
38
39---@alias vim.treesitter.query.ProcessedDirective (integer|string)[]
40
41---@nodoc
42---@class vim.treesitter.query.ProcessedPattern {
43---@field predicates vim.treesitter.query.ProcessedPredicate[]
44---@field directives vim.treesitter.query.ProcessedDirective[]
45
46--- Splits the query patterns into predicates and directives.
47function Query:_process_patterns()
48  self._processed_patterns = {}
49
50  for k, pattern_list in pairs(self.info.patterns) do
51    ---@type vim.treesitter.query.ProcessedPredicate[]
52    local predicates = {}
53    ---@type vim.treesitter.query.ProcessedDirective[]
54    local directives = {}
55
56    for _, pattern in ipairs(pattern_list) do
57      -- Note: tree-sitter strips the leading # from predicates for us.
58      local pred_name = pattern[1]
59      ---@cast pred_name string
60
61      if is_directive(pred_name) then
62        table.insert(directives, pattern)
63        if vim.deep_equal(pattern, { 'set!', 'injection.combined' }) then
64          self.has_combined_injections = true
65        end
66        if vim.deep_equal(pattern, { 'set!', 'conceal_lines', '' }) then
67          self.has_conceal_line = true
68        end
69      else
70        local should_match = true
71        if pred_name:match('^not%-') then
72          pred_name = pred_name:sub(5)
73          should_match = false
74        end
75        table.insert(predicates, { pred_name, should_match, pattern })
76      end
77    end
78
79    self._processed_patterns[k] = { predicates = predicates, directives = directives }
80  end
81end
82
83---@package
84---@see vim.treesitter.query.parse
85---@param lang string
86---@param ts_query TSQuery
87---@return vim.treesitter.Query
88function Query.new(lang, ts_query)
89  local self = setmetatable({}, Query)
90  local query_info = ts_query:inspect() ---@type TSQueryInfo
91  self.query = ts_query
92  self.lang = lang
93  self.info = {
94    captures = query_info.captures,
95    patterns = query_info.patterns,
96  }
97  self.captures = self.info.captures
98  self:_process_patterns()
99  return self
100end
101
102---@nodoc
103---Information for Query, see |vim.treesitter.query.parse()|
104---@class vim.treesitter.QueryInfo
105---
106---List of (unique) capture names defined in query.
107---@field captures string[]
108---
109---Contains information about predicates and directives.
110---Key is pattern id, and value is list of predicates or directives defined in the pattern.
111---A predicate or directive is a list of (integer|string); integer represents `capture_id`, and
112---string represents (literal) arguments to predicate/directive. See |treesitter-predicates|
113---and |treesitter-directives| for more details.
114---@field patterns table<integer, (integer|string)[][]>
115
116---@param files string[]
117---@return string[]
118local function dedupe_files(files)
119  local result = {}
120  ---@type table<string,boolean>
121  local seen = {}
122
123  for _, path in ipairs(files) do
124    if not seen[path] then
125      table.insert(result, path)
126      seen[path] = true
127    end
128  end
129
130  return result
131end
132
133--- @param filename string
134--- @param read_quantifier '*a'|'*l'
135local function safe_read(filename, read_quantifier)
136  local file, err = io.open(filename, 'r')
137  if not file then
138    error(err)
139  end
140  local content = file:read(read_quantifier)
141  io.close(file)
142  return content
143end
144
145--- Adds {ilang} to {base_langs}, only if {ilang} is different than {lang}
146---
147---@param base_langs string[]
148---@param lang string
149---@param ilang string
150---@return boolean true If lang == ilang
151local function add_included_lang(base_langs, lang, ilang)
152  if lang == ilang then
153    return true
154  end
155  table.insert(base_langs, ilang)
156  return false
157end
158
159--- Gets the list of files used to make up a query
160---
161---@param lang string Language to get query for
162---@param query_name string Name of the query to load (e.g., "highlights")
163---@param is_included? boolean Internal parameter, most of the time left as `nil`
164---@return string[] query_files List of files to load for given query and language
165function M.get_files(lang, query_name, is_included)
166  local query_path = string.format('queries/%s/%s.scm', lang, query_name)
167  local lang_files = dedupe_files(api.nvim_get_runtime_file(query_path, true))
168
169  if #lang_files == 0 then
170    return {}
171  end
172
173  local base_query = nil ---@type string?
174  local extensions = {}
175
176  local base_langs = {} ---@type string[]
177
178  -- Now get the base languages by looking at the first line of every file
179  -- The syntax is the following :
180  -- ;+ inherits: ({language},)*{language}
181  --
182  -- {language} ::= {lang} | ({lang})
183  for _, filename in ipairs(lang_files) do
184    local file, err = io.open(filename, 'r')
185    if not file then
186      error(err)
187    end
188
189    local extension = false
190
191    for modeline in
192      ---@return string
193      function()
194        return file:read('*l')
195      end
196    do
197      if not vim.startswith(modeline, ';') then
198        break
199      end
200
201      local langlist = modeline:match(MODELINE_FORMAT)
202      if langlist then
203        ---@diagnostic disable-next-line:param-type-mismatch
204        for _, incllang in ipairs(vim.split(langlist, ',')) do
205          local is_optional = incllang:match('%(.*%)')
206
207          if is_optional then
208            if not is_included then
209              if add_included_lang(base_langs, lang, incllang:sub(2, #incllang - 1)) then
210                extension = true
211              end
212            end
213          else
214            if add_included_lang(base_langs, lang, incllang) then
215              extension = true
216            end
217          end
218        end
219      elseif modeline:match(EXTENDS_FORMAT) then
220        extension = true
221      end
222    end
223
224    if extension then
225      table.insert(extensions, filename)
226    elseif base_query == nil then
227      base_query = filename
228    end
229    io.close(file)
230  end
231
232  local query_files = {}
233  for _, base_lang in ipairs(base_langs) do
234    local base_files = M.get_files(base_lang, query_name, true)
235    vim.list_extend(query_files, base_files)
236  end
237  vim.list_extend(query_files, { base_query })
238  vim.list_extend(query_files, extensions)
239
240  return query_files
241end
242
243---@param filenames string[]
244---@return string
245local function read_query_files(filenames)
246  local contents = {}
247
248  for _, filename in ipairs(filenames) do
249    table.insert(contents, safe_read(filename, '*a'))
250  end
251
252  return table.concat(contents, '')
253end
254
255-- The explicitly set query strings from |vim.treesitter.query.set()|
256---@type table<string,table<string,string>>
257local explicit_queries = setmetatable({}, {
258  __index = function(t, k)
259    local lang_queries = {}
260    rawset(t, k, lang_queries)
261
262    return lang_queries
263  end,
264})
265
266--- Sets the runtime query named {query_name} for {lang}
267---
268--- This allows users to override or extend any runtime files and/or configuration
269--- set by plugins.
270---
271--- For example, you could enable spellchecking of `C` identifiers with the
272--- following code:
273--- ```lua
274--- vim.treesitter.query.set(
275---   'c',
276---   'highlights',
277---   [[;inherits c
278---   (identifier) @spell]]
279--- )
280--- ```
281---
282---@param lang string Language to use for the query
283---@param query_name string Name of the query (e.g., "highlights")
284---@param text string Query text (unparsed).
285function M.set(lang, query_name, text)
286  --- @diagnostic disable-next-line: undefined-field LuaLS bad at generics
287  M.get:clear(lang, query_name)
288  explicit_queries[lang][query_name] = text
289end
290
291--- Returns the runtime query {query_name} for {lang}.
292---
293---@param lang string Language to use for the query
294---@param query_name string Name of the query (e.g. "highlights")
295---
296---@return vim.treesitter.Query? : Parsed query. `nil` if no query files are found.
297M.get = memoize('concat-2', function(lang, query_name)
298  local query_string ---@type string
299
300  if explicit_queries[lang][query_name] then
301    local query_files = {}
302    local base_langs = {} ---@type string[]
303
304    for line in explicit_queries[lang][query_name]:gmatch('([^\n]*)\n?') do
305      if not vim.startswith(line, ';') then
306        break
307      end
308
309      local lang_list = line:match(MODELINE_FORMAT)
310      if lang_list then
311        for _, incl_lang in ipairs(vim.split(lang_list, ',')) do
312          local is_optional = incl_lang:match('%(.*%)')
313
314          if is_optional then
315            add_included_lang(base_langs, lang, incl_lang:sub(2, #incl_lang - 1))
316          else
317            add_included_lang(base_langs, lang, incl_lang)
318          end
319        end
320      elseif line:match(EXTENDS_FORMAT) then
321        table.insert(base_langs, lang)
322      end
323    end
324
325    for _, base_lang in ipairs(base_langs) do
326      local base_files = M.get_files(base_lang, query_name, true)
327      vim.list_extend(query_files, base_files)
328    end
329
330    query_string = read_query_files(query_files) .. explicit_queries[lang][query_name]
331  else
332    local query_files = M.get_files(lang, query_name)
333    query_string = read_query_files(query_files)
334  end
335
336  if #query_string == 0 then
337    return nil
338  end
339
340  return M.parse(lang, query_string)
341end, false)
342
343nvim_on(
344  'OptionSet',
345  api.nvim_create_augroup('nvim.treesitter.query_cache_reset', { clear = true }),
346  {
347    pattern = { 'runtimepath' },
348  },
349  function()
350    --- @diagnostic disable-next-line: undefined-field LuaLS bad at generics
351    M.get:clear()
352  end
353)
354
355--- Parses a {query} string and returns a `Query` object (|lua-treesitter-query|), which can be used
356--- to search the tree for the query patterns (via |Query:iter_captures()|, |Query:iter_matches()|),
357--- or inspect/modify the query via these fields:
358---   - `captures`: a list of unique capture names defined in the query (alias: `info.captures`).
359---   - `info.patterns`: information about predicates.
360---   - `query`: the underlying |TSQuery| which can be used to disable patterns or captures.
361---
362--- Example:
363--- ```lua
364--- local query = vim.treesitter.query.parse('vimdoc', [[
365---   ; query
366---   ((h1) @str
367---     (#trim! @str 1 1 1 1))
368--- ]])
369--- local tree = vim.treesitter.get_parser():parse()[1]
370--- for id, node, metadata in query:iter_captures(tree:root(), 0) do
371---    -- Print the node name and source text.
372---    vim.print({node:type(), vim.treesitter.get_node_text(node, vim.api.nvim_get_current_buf())})
373--- end
374--- ```
375---
376---@param lang string Language to use for the query
377---@param query string Query text, in s-expr syntax
378---
379---@return vim.treesitter.Query : Parsed query
380---
381---@see [vim.treesitter.query.get()]
382M.parse = memoize('concat-2', function(lang, query)
383  assert(language.add(lang))
384  local ts_query = vim._ts_parse_query(lang, query)
385  return Query.new(lang, ts_query)
386end, false)
387
388--- Implementations of predicates that can optionally be prefixed with "any-".
389---
390--- These functions contain the implementations for each predicate, correctly
391--- handling the "any" vs "all" semantics. They are called from the
392--- predicate_handlers table with the appropriate arguments for each predicate.
393local impl = {
394  --- @param match table<integer,TSNode[]?>
395  --- @param source integer|string
396  --- @param predicate any[]
397  --- @param any boolean
398  ['eq'] = function(match, source, predicate, any)
399    local nodes = match[predicate[2]]
400    if not nodes or #nodes == 0 then
401      return true
402    end
403
404    for _, node in ipairs(nodes) do
405      local node_text = vim.treesitter.get_node_text(node, source)
406
407      local str ---@type string
408      if type(predicate[3]) == 'string' then
409        -- (#eq? @aa "foo")
410        str = predicate[3]
411      else
412        -- (#eq? @aa @bb)
413        local other = assert(match[predicate[3]])
414        assert(#other == 1, '#eq? does not support comparison with captures on multiple nodes')
415        str = vim.treesitter.get_node_text(other[1], source)
416      end
417
418      local res = str ~= nil and node_text == str
419      if any and res then
420        return true
421      elseif not any and not res then
422        return false
423      end
424    end
425
426    return not any
427  end,
428
429  --- @param match table<integer,TSNode[]>
430  --- @param source integer|string
431  --- @param predicate any[]
432  --- @param any boolean
433  ['lua-match'] = function(match, source, predicate, any)
434    local nodes = match[predicate[2]]
435    if not nodes or #nodes == 0 then
436      return true
437    end
438
439    for _, node in ipairs(nodes) do
440      local regex = predicate[3]
441      local res = string.find(vim.treesitter.get_node_text(node, source), regex) ~= nil
442      if any and res then
443        return true
444      elseif not any and not res then
445        return false
446      end
447    end
448
449    return not any
450  end,
451
452  ['match'] = (function()
453    local magic_prefixes = { ['\\v'] = true, ['\\m'] = true, ['\\M'] = true, ['\\V'] = true }
454    --- @param str string
455    local function check_magic(str)
456      if string.len(str) < 2 or magic_prefixes[string.sub(str, 1, 2)] then
457        return str
458      end
459      return '\\v' .. str
460    end
461
462    local compiled_vim_regexes = setmetatable({}, {
463      __index = function(t, pattern)
464        local res = vim.regex(check_magic(pattern))
465        rawset(t, pattern, res)
466        return res
467      end,
468    })
469
470    --- @param match table<integer,TSNode[]>
471    --- @param source integer|string
472    --- @param predicate any[]
473    --- @param any boolean
474    return function(match, source, predicate, any)
475      local nodes = match[predicate[2]]
476      if not nodes or #nodes == 0 then
477        return true
478      end
479
480      for _, node in ipairs(nodes) do
481        local regex = compiled_vim_regexes[predicate[3]] ---@type vim.regex
482        local res = regex:match_str(vim.treesitter.get_node_text(node, source))
483        if any and res then
484          return true
485        elseif not any and not res then
486          return false
487        end
488      end
489      return not any
490    end
491  end)(),
492
493  --- @param match table<integer,TSNode[]>
494  --- @param source integer|string
495  --- @param predicate any[]
496  --- @param any boolean
497  ['contains'] = function(match, source, predicate, any)
498    local nodes = match[predicate[2]]
499    if not nodes or #nodes == 0 then
500      return true
501    end
502
503    for _, node in ipairs(nodes) do
504      local node_text = vim.treesitter.get_node_text(node, source)
505
506      for i = 3, #predicate do
507        local res = string.find(node_text, predicate[i], 1, true)
508        if any and res then
509          return true
510        elseif not any and not res then
511          return false
512        end
513      end
514    end
515
516    return not any
517  end,
518}
519
520---@alias TSPredicate fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[]): boolean
521
522-- Predicate handler receive the following arguments
523-- (match, pattern, bufnr, predicate)
524---@type table<string,TSPredicate>
525local predicate_handlers = {
526  ['eq?'] = function(match, _, source, predicate)
527    return impl['eq'](match, source, predicate, false)
528  end,
529
530  ['any-eq?'] = function(match, _, source, predicate)
531    return impl['eq'](match, source, predicate, true)
532  end,
533
534  ['lua-match?'] = function(match, _, source, predicate)
535    return impl['lua-match'](match, source, predicate, false)
536  end,
537
538  ['any-lua-match?'] = function(match, _, source, predicate)
539    return impl['lua-match'](match, source, predicate, true)
540  end,
541
542  ['match?'] = function(match, _, source, predicate)
543    return impl['match'](match, source, predicate, false)
544  end,
545
546  ['any-match?'] = function(match, _, source, predicate)
547    return impl['match'](match, source, predicate, true)
548  end,
549
550  ['contains?'] = function(match, _, source, predicate)
551    return impl['contains'](match, source, predicate, false)
552  end,
553
554  ['any-contains?'] = function(match, _, source, predicate)
555    return impl['contains'](match, source, predicate, true)
556  end,
557
558  --- @param predicate any[] & { string_set?: table<string, boolean> }
559  ['any-of?'] = function(match, _, source, predicate)
560    local nodes = match[predicate[2]]
561    if not nodes or #nodes == 0 then
562      return true
563    end
564
565    for _, node in ipairs(nodes) do
566      local node_text = vim.treesitter.get_node_text(node, source)
567
568      -- Since 'predicate' will not be used by callers of this function, use it
569      -- to store a string set built from the list of words to check against.
570      local string_set = predicate['string_set']
571      if not string_set then
572        string_set = {}
573        for i = 3, #predicate do
574          string_set[predicate[i]] = true
575        end
576        predicate['string_set'] = string_set
577      end
578
579      if string_set[node_text] then
580        return true
581      end
582    end
583
584    return false
585  end,
586
587  ['has-ancestor?'] = function(match, _, _, predicate)
588    local nodes = match[predicate[2]]
589    if not nodes or #nodes == 0 then
590      return true
591    end
592
593    for _, node in ipairs(nodes) do
594      if node:__has_ancestor(predicate) then
595        return true
596      end
597    end
598    return false
599  end,
600
601  ['has-parent?'] = function(match, _, _, predicate)
602    local nodes = match[predicate[2]]
603    if not nodes or #nodes == 0 then
604      return true
605    end
606
607    for _, node in ipairs(nodes) do
608      local parent = node:parent()
609      if parent and vim.list_contains({ unpack(predicate, 3) }, parent:type()) then
610        return true
611      end
612    end
613    return false
614  end,
615}
616
617-- As we provide lua-match? also expose vim-match?
618predicate_handlers['vim-match?'] = predicate_handlers['match?']
619predicate_handlers['any-vim-match?'] = predicate_handlers['any-match?']
620
621---@nodoc
622---@class vim.treesitter.query.TSMetadata
623---@field range? Range
624---@field offset? Range4
625---@field conceal? string|boolean
626---@field bo.commentstring? string
627---@field [integer]? vim.treesitter.query.TSMetadata
628---@field [string]? integer|string
629
630---@alias TSDirective fun(match: table<integer,TSNode[]>, _, _, predicate: (string|integer)[], metadata: vim.treesitter.query.TSMetadata)
631
632-- Predicate handler receive the following arguments
633-- (match, pattern, bufnr, predicate)
634
635-- Directives store metadata or perform side effects against a match.
636-- Directives should always end with a `!`.
637-- Directive handler receive the following arguments
638-- (match, pattern, bufnr, predicate, metadata)
639---@type table<string,TSDirective>
640local directive_handlers = {
641  ['set!'] = function(_, _, _, pred, metadata)
642    if #pred >= 3 and type(pred[2]) == 'number' then
643      -- (#set! @capture key value)
644      local capture_id, key, value = pred[2], pred[3], pred[4]
645      if not metadata[capture_id] then
646        metadata[capture_id] = {}
647      end
648      metadata[capture_id][key] = value
649    else
650      -- (#set! key value)
651      local key, value = pred[2], pred[3]
652      metadata[key] = value or true
653    end
654  end,
655  -- Shifts the range of a node.
656  -- Example: (#offset! @_node 0 1 0 -1)
657  ['offset!'] = function(match, _, _, pred, metadata)
658    local capture_id = pred[2] --[[@as integer]]
659    local nodes = match[capture_id]
660    if not nodes or #nodes == 0 then
661      return
662    end
663
664    if not metadata[capture_id] then
665      metadata[capture_id] = {}
666    end
667
668    metadata[capture_id].offset = {
669      pred[3] --[[@as integer]] or 0,
670      pred[4] --[[@as integer]] or 0,
671      pred[5] --[[@as integer]] or 0,
672      pred[6] --[[@as integer]] or 0,
673    }
674  end,
675  -- Transform the content of the node
676  -- Example: (#gsub! @_node ".*%.(.*)" "%1")
677  ['gsub!'] = function(match, _, bufnr, pred, metadata)
678    assert(#pred == 4)
679
680    local id = pred[2]
681    assert(type(id) == 'number')
682
683    local nodes = match[id]
684    if not nodes or #nodes == 0 then
685      return
686    end
687    assert(#nodes == 1, '#gsub! does not support captures on multiple nodes')
688    local node = nodes[1]
689    local text = vim.treesitter.get_node_text(node, bufnr, { metadata = metadata[id] }) or ''
690
691    if not metadata[id] then
692      metadata[id] = {}
693    end
694
695    local pattern, replacement = pred[3], pred[4]
696    assert(type(pattern) == 'string')
697    assert(type(replacement) == 'string')
698
699    metadata[id].text = text:gsub(pattern, replacement)
700  end,
701  -- Trim whitespace from both sides of the node
702  -- Example: (#trim! @fold 1 1 1 1)
703  ['trim!'] = function(match, _, bufnr, pred, metadata)
704    local capture_id = pred[2]
705    assert(type(capture_id) == 'number')
706
707    local trim_start_lines = pred[3] == '1'
708    local trim_start_cols = pred[4] == '1'
709    local trim_end_lines = pred[5] == '1' or not pred[3] -- default true for backwards compatibility
710    local trim_end_cols = pred[6] == '1'
711
712    local nodes = match[capture_id]
713    if not nodes or #nodes == 0 then
714      return
715    end
716    assert(#nodes == 1, '#trim! does not support captures on multiple nodes')
717    local node = nodes[1]
718
719    local start_row, start_col, end_row, end_col = node:range()
720
721    local node_text = vim.split(vim.treesitter.get_node_text(node, bufnr), '\n')
722
723    local end_idx = #node_text
724    local start_idx = 1
725
726    local end_line = node_text[end_idx]
727    if trim_end_lines then
728      while end_line and end_line:find('^%s*$') do
729        end_idx = end_idx - 1
730        end_line = node_text[end_idx]
731        end_row = end_row - 1
732        -- set the end position to the last column of the next line, or 0 if we just trimmed the
733        -- last line
734        end_col = end_line and #end_line or 0
735      end
736    end
737    if trim_end_cols then
738      if not end_line then
739        end_row = start_row
740        end_col = start_col
741      else
742        local whitespace_start = assert(end_line:find('(%s*)$'))
743        end_col = (whitespace_start - 1) + (end_idx == 1 and start_col or 0)
744      end
745    end
746
747    local start_line = node_text[start_idx]
748    if trim_start_lines then
749      while start_idx <= end_idx and assert(start_line):find('^%s*$') do
750        start_idx = start_idx + 1
751        start_line = node_text[start_idx]
752        start_row = start_row + 1
753        start_col = 0
754      end
755    end
756    if trim_start_cols and start_line then
757      local _, whitespace_end = start_line:find('^(%s*)')
758      whitespace_end = whitespace_end or 0
759      start_col = (start_idx == 1 and start_col or 0) + whitespace_end
760    end
761
762    -- If this produces an invalid range, we just skip it.
763    if start_row < end_row or (start_row == end_row and start_col <= end_col) then
764      metadata[capture_id] = metadata[capture_id] or {}
765      metadata[capture_id].range = { start_row, start_col, end_row, end_col }
766    end
767  end,
768}
769
770--- @class vim.treesitter.query.add_predicate.Opts
771--- @inlinedoc
772---
773--- Override an existing predicate of the same name
774--- @field force? boolean
775
776--- Adds a new predicate to be used in queries
777---
778---@param name string Name of the predicate, without leading #
779---@param handler fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[], metadata: vim.treesitter.query.TSMetadata): boolean? #
780---   - see |vim.treesitter.query.add_directive()| for argument meanings
781---@param opts? vim.treesitter.query.add_predicate.Opts
782function M.add_predicate(name, handler, opts)
783  -- Backward compatibility: old signature had "force" as boolean argument
784  if type(opts) == 'boolean' then
785    opts = { force = opts }
786  end
787
788  opts = opts or {}
789
790  if predicate_handlers[name] and not opts.force then
791    error(string.format('Overriding existing predicate %s', name))
792  end
793
794  predicate_handlers[name] = handler
795end
796
797--- Adds a new directive to be used in queries
798---
799--- Handlers can set match level data by setting directly on the
800--- metadata object `metadata.key = value`. Additionally, handlers
801--- can set node level data by using the capture id on the
802--- metadata table `metadata[capture_id].key = value`
803---
804---@param name string Name of the directive, without leading #
805---@param handler fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[], metadata: vim.treesitter.query.TSMetadata) #
806---   - match: A table mapping capture IDs to a list of captured nodes
807---   - pattern: the index of the matching pattern in the query file
808---   - predicate: list of strings containing the full directive being called, e.g.
809---     `(node (#set! conceal "-"))` would get the predicate `{ "#set!", "conceal", "-" }`
810---@param opts vim.treesitter.query.add_predicate.Opts
811function M.add_directive(name, handler, opts)
812  -- Backward compatibility: old signature had "force" as boolean argument
813  if type(opts) == 'boolean' then
814    opts = { force = opts }
815  end
816
817  opts = opts or {}
818
819  if directive_handlers[name] and not opts.force then
820    error(string.format('Overriding existing directive %s', name))
821  end
822
823  directive_handlers[name] = handler
824end
825
826--- Lists the currently available directives to use in queries.
827---@return string[] : Supported directives.
828function M.list_directives()
829  return vim.tbl_keys(directive_handlers)
830end
831
832--- Lists the currently available predicates to use in queries.
833---@return string[] : Supported predicates.
834function M.list_predicates()
835  return vim.tbl_keys(predicate_handlers)
836end
837
838---@private
839---@param pattern_i integer
840---@param predicates vim.treesitter.query.ProcessedPredicate[]
841---@param captures table<integer, TSNode[]>
842---@param source integer|string
843---@return boolean whether the predicates match
844function Query._match_predicates(predicates, pattern_i, captures, source)
845  for _, predicate in ipairs(predicates) do
846    local processed_name = predicate[1]
847    local should_match = predicate[2]
848    local orig_predicate = predicate[3]
849
850    local handler = predicate_handlers[processed_name]
851    if not handler then
852      error(string.format('No handler for %s', orig_predicate[1]))
853      return false
854    end
855
856    local does_match = handler(captures, pattern_i, source, orig_predicate)
857    if does_match ~= should_match then
858      return false
859    end
860  end
861  return true
862end
863
864---@private
865---@param pattern_i integer
866---@param directives vim.treesitter.query.ProcessedDirective[]
867---@param source integer|string
868---@param captures table<integer, TSNode[]>
869---@return vim.treesitter.query.TSMetadata metadata
870function Query._apply_directives(_, directives, pattern_i, captures, source)
871  ---@type vim.treesitter.query.TSMetadata
872  local metadata = {}
873
874  for _, directive in pairs(directives) do
875    local handler = directive_handlers[directive[1]]
876
877    if not handler then
878      error(string.format('No handler for %s', directive[1]))
879    end
880
881    handler(captures, pattern_i, source, directive, metadata)
882  end
883
884  return metadata
885end
886
887--- Returns the start and stop value if set else the node's range.
888-- When the node's range is used, the stop is incremented by 1
889-- to make the search inclusive.
890---@param start integer?
891---@param stop integer?
892---@param node TSNode
893---@return integer, integer
894local function value_or_node_range(start, stop, node)
895  if start == nil then
896    start = node:start()
897  end
898  if stop == nil then
899    stop = node:end_() + 1 -- Make stop inclusive
900  end
901
902  return start, stop
903end
904
905--- Iterates over all captures from all matches in {node}.
906---
907--- {source} is required if the query contains predicates; then the caller
908--- must ensure to use a freshly parsed tree consistent with the current
909--- text of the buffer (if relevant). {start} and {stop} can be used to limit
910--- matches inside a row range (this is typically used with root node
911--- as the {node}, i.e., to get syntax highlight matches in the current
912--- viewport). When omitted, the {start} and {stop} row values are used from the given node.
913---
914--- The iterator returns four values:
915--- 1. the numeric id identifying the capture
916--- 2. the captured node
917--- 3. metadata from any directives processing the match
918--- 4. the match itself
919---
920--- Example: how to get captures by name:
921--- ```lua
922--- for id, node, metadata, match in query:iter_captures(tree:root(), bufnr, first, last) do
923---   local name = query.captures[id] -- name of the capture in the query
924---   -- typically useful info about the node:
925---   local type = node:type() -- type of the captured node
926---   local row1, col1, row2, col2 = node:range() -- range of the capture
927---   -- ... use the info here ...
928--- end
929--- ```
930---
931---@param node TSNode under which the search will occur
932---@param source (integer|string) Source buffer or string to extract text from
933---@param start_row? integer Starting line for the search. Defaults to `node:start()`.
934---@param end_row? integer Stopping line for the search (end-inclusive, unless `stop_col` is provided). Defaults to `node:end_()`.
935---@param opts? table Optional keyword arguments:
936---   - end_col (integer) Stopping column for the search (end-exclusive).
937---   - match_limit (integer) Set the maximum number of in-progress matches (Default: none).
938---   - max_start_depth (integer) if non-zero, sets the maximum start depth
939---     for each match. This is used to prevent traversing too deep into a tree.
940---   - start_col (integer) Starting column for the search.
941---
942---@return (fun(end_line: integer|nil, end_col: integer|nil): integer, TSNode, vim.treesitter.query.TSMetadata, TSQueryMatch, TSTree):
943---        capture-id, capture-node, metadata, match, tree
944---
945---@note Captures are only returned if the query pattern of a specific capture contained predicates.
946function Query:iter_captures(node, source, start_row, end_row, opts)
947  opts = opts or {}
948
949  if type(source) == 'number' and source == 0 then
950    source = api.nvim_get_current_buf()
951  end
952
953  start_row, end_row = value_or_node_range(start_row, end_row, node)
954
955  local tree = node:tree()
956  local cursor = vim._create_ts_querycursor(node, self.query, {
957    start_row = start_row,
958    start_col = opts.start_col or 0,
959    end_row = end_row,
960    end_col = opts.end_col or 0,
961    max_start_depth = opts.max_start_depth,
962    match_limit = opts.match_limit,
963  })
964
965  -- For faster checks that a match is not in the cache.
966  local highest_cached_match_id = -1
967  ---@type table<integer, vim.treesitter.query.TSMetadata>
968  local match_cache = {}
969
970  ---@param end_line? integer
971  ---@param end_col? integer
972  local function iter(end_line, end_col)
973    local capture, captured_node, match = cursor:next_capture()
974
975    if not capture then
976      return
977    end
978
979    local match_id, pattern_i = match:info()
980
981    --- @type vim.treesitter.query.TSMetadata?
982    local metadata
983    if match_id <= highest_cached_match_id then
984      metadata = match_cache[match_id]
985    end
986
987    if not metadata then
988      metadata = {}
989
990      local processed_pattern = self._processed_patterns[pattern_i]
991      if processed_pattern then
992        local captures = match:captures()
993
994        local predicates = processed_pattern.predicates
995        if not self._match_predicates(predicates, pattern_i, captures, source) then
996          cursor:remove_match(match_id)
997
998          local row, col = captured_node:range()
999
1000          local outside = false
1001          if end_line then
1002            if end_col then
1003              outside = cmp_ge(row, col, end_line, end_col)
1004            else
1005              outside = row > end_line
1006            end
1007          end
1008
1009          if outside then
1010            return nil, captured_node, nil, nil
1011          end
1012
1013          return iter(end_line) -- tail call: try next match
1014        end
1015
1016        local directives = processed_pattern.directives
1017        metadata = self:_apply_directives(directives, pattern_i, captures, source)
1018      end
1019
1020      highest_cached_match_id = math.max(highest_cached_match_id, match_id)
1021      match_cache[match_id] = metadata
1022    end
1023
1024    return capture, captured_node, metadata, match, tree
1025  end
1026  return iter
1027end
1028
1029--- Iterates the matches of self on a given range.
1030---
1031--- Iterate over all matches within a {node}. The arguments are the same as for
1032--- |Query:iter_captures()| but the iterated values are different: an (1-based)
1033--- index of the pattern in the query, a table mapping capture indices to a list
1034--- of nodes, and metadata from any directives processing the match.
1035---
1036--- Example:
1037---
1038--- ```lua
1039--- for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, 0, -1) do
1040---   for id, nodes in pairs(match) do
1041---     local name = query.captures[id]
1042---     for _, node in ipairs(nodes) do
1043---       -- `node` was captured by the `name` capture in the match
1044---
1045---       local node_data = metadata[id] -- Node level metadata
1046---       -- ... use the info here ...
1047---     end
1048---   end
1049--- end
1050--- ```
1051---
1052---
1053---@param node TSNode under which the search will occur
1054---@param source (integer|string) Source buffer or string to search
1055---@param start? integer Starting line for the search. Defaults to `node:start()`.
1056---@param stop? integer Stopping line for the search (end-exclusive). Defaults to `node:end_()`.
1057---@param opts? table Optional keyword arguments:
1058---   - match_limit (integer) Set the maximum number of in-progress matches (Default: none).
1059---   - max_start_depth (integer) if non-zero, sets the maximum start depth
1060---     for each match. This is used to prevent traversing too deep into a tree.
1061---
1062---@return (fun(): integer, table<integer, TSNode[]>, vim.treesitter.query.TSMetadata, TSTree): pattern-id, match, metadata, tree
1063function Query:iter_matches(node, source, start, stop, opts)
1064  opts = opts or {}
1065
1066  if type(source) == 'number' and source == 0 then
1067    source = api.nvim_get_current_buf()
1068  end
1069
1070  start, stop = value_or_node_range(start, stop, node)
1071
1072  local tree = node:tree()
1073  local cursor = vim._create_ts_querycursor(node, self.query, {
1074    start_row = start,
1075    start_col = 0,
1076    end_row = stop,
1077    end_col = 0,
1078    max_start_depth = opts.max_start_depth,
1079    match_limit = opts.match_limit,
1080  })
1081
1082  local function iter()
1083    local match = cursor:next_match()
1084
1085    if not match then
1086      return
1087    end
1088
1089    local match_id, pattern_i = match:info()
1090    local processed_pattern = self._processed_patterns[pattern_i]
1091    local captures = match:captures()
1092
1093    --- @type vim.treesitter.query.TSMetadata
1094    local metadata = {}
1095    if processed_pattern then
1096      local predicates = processed_pattern.predicates
1097      if not self._match_predicates(predicates, pattern_i, captures, source) then
1098        cursor:remove_match(match_id)
1099        return iter() -- tail call: try next match
1100      end
1101      local directives = processed_pattern.directives
1102      metadata = self:_apply_directives(directives, pattern_i, captures, source)
1103    end
1104
1105    -- TODO(lewis6991): create a new function that returns {match, metadata}
1106    return pattern_i, captures, metadata, tree
1107  end
1108  return iter
1109end
1110
1111--- Optional keyword arguments:
1112--- @class vim.treesitter.query.lint.Opts
1113--- @inlinedoc
1114---
1115--- Language(s) to use for checking the query.
1116--- If multiple languages are specified, queries are validated for all of them
1117--- @field langs? string|string[]
1118---
1119--- Just clear current lint errors
1120--- @field clear? boolean
1121
1122--- Lint treesitter queries using installed parser, or clear lint errors.
1123---
1124--- Use |treesitter-parsers| in runtimepath to check the query file in {buf} for errors:
1125---
1126---   - verify that used nodes are valid identifiers in the grammar.
1127---   - verify that predicates and directives are valid.
1128---   - verify that top-level s-expressions are valid.
1129---
1130--- The found diagnostics are reported using |diagnostic-api|.
1131--- By default, the parser used for verification is determined by the containing folder
1132--- of the query file, e.g., if the path ends in `/lua/highlights.scm`, the parser for the
1133--- `lua` language will be used.
1134---@param buf (integer) Buffer handle
1135---@param opts? vim.treesitter.query.lint.Opts
1136function M.lint(buf, opts)
1137  if opts and opts.clear then
1138    vim.treesitter._query_linter.clear(buf)
1139  else
1140    vim.treesitter._query_linter.lint(buf, opts)
1141  end
1142end
1143
1144--- Omnifunc for completing node names and predicates in treesitter queries.
1145---
1146--- Use via
1147---
1148--- ```lua
1149--- vim.bo.omnifunc = vim.treesitter.query.omnifunc
1150--- ```
1151---
1152--- @param findstart 0|1
1153--- @param base string
1154function M.omnifunc(findstart, base)
1155  return vim.treesitter._query_linter.omnifunc(findstart, base)
1156end
1157
1158--- Opens a live editor to query the buffer you started from.
1159---
1160--- Can also be shown with the [:EditQuery]() command. `:EditQuery <tab>` completes available
1161--- parsers.
1162---
1163--- If you move the cursor to a capture name ("@foo"), text matching the capture is highlighted
1164--- with |hl-DiagnosticVirtualTextHint| in the source buffer. The query editor is a scratch buffer,
1165--- use `:write` to save it. You can find example queries at `$VIMRUNTIME/queries/`.
1166---
1167--- @param lang? string language to open the query editor for. If omitted, inferred from the current buffer's filetype.
1168function M.edit(lang)
1169  assert(vim.treesitter.dev.edit_query(lang))
1170end
1171
1172return M