robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
27.0 KiB950 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local describe, it, before_each = t.describe, t.it, t.before_each
5local clear = n.clear
6local dedent = t.dedent
7local eq = t.eq
8local insert = n.insert
9local exec_lua = n.exec_lua
10local pcall_err = t.pcall_err
11local api = n.api
12
13local function get_query_result(query_text)
14  local cquery = vim.treesitter.query.parse('c', query_text)
15  local parser = vim.treesitter.get_parser(0, 'c')
16  local tree = parser:parse()[1]
17  local res = {}
18  for cid, node in cquery:iter_captures(tree:root(), 0) do
19    -- can't transmit node over RPC. just check the name, range, and text
20    local text = vim.treesitter.get_node_text(node, 0)
21    local range = { node:range() }
22    table.insert(res, { cquery.captures[cid], node:type(), range, text })
23  end
24  return res
25end
26
27describe('treesitter query API', function()
28  before_each(function()
29    clear()
30    exec_lua(function()
31      vim.g.__ts_debug = 1
32    end)
33  end)
34
35  local test_text = [[
36void ui_refresh(void)
37{
38  int width = INT_MAX, height = INT_MAX;
39  bool ext_widgets[kUIExtCount];
40  for (UIExtension i = 0; (int)i < kUIExtCount; i++) {
41    ext_widgets[i] = true;
42  }
43
44  bool inclusive = ui_override();
45  for (size_t i = 0; i < ui_count; i++) {
46    UI *ui = uis[i];
47    width = MIN(ui->width, width);
48    height = MIN(ui->height, height);
49    foo = BAR(ui->bazaar, bazaar);
50    for (UIExtension j = 0; (int)j < kUIExtCount; j++) {
51      ext_widgets[j] &= (ui->ui_ext[j] || inclusive);
52    }
53  }
54}]]
55
56  local test_query = [[
57    ((call_expression
58      function: (identifier) @minfunc
59      (argument_list (identifier) @min_id))
60      (#eq? @minfunc "MIN")
61    )
62
63    "for" @keyword
64
65    (primitive_type) @type
66
67    (field_expression argument: (identifier) @fieldarg)
68  ]]
69
70  it('supports runtime queries', function()
71    ---@type string[]
72    local ret = exec_lua(function()
73      return vim.treesitter.query.get('c', 'highlights').captures
74    end)
75
76    -- see $VIMRUNTIME/queries/c/highlights.scm
77    eq('variable', ret[1])
78    eq('keyword', ret[2])
79  end)
80
81  it('supports caching queries', function()
82    local long_query = test_query:rep(100)
83    ---@return number
84    local function q(_n)
85      return exec_lua(function()
86        local before = vim.api.nvim__stats().ts_query_parse_count
87        collectgarbage('stop')
88        for _ = 1, _n, 1 do
89          vim.treesitter.query.parse('c', long_query)
90        end
91        collectgarbage('restart')
92        collectgarbage('collect')
93        local after = vim.api.nvim__stats().ts_query_parse_count
94        return after - before
95      end)
96    end
97
98    eq(1, q(1))
99    -- cache is retained even after garbage collection
100    eq(0, q(100))
101  end)
102
103  it('cache is cleared upon runtimepath changes, or setting query manually', function()
104    ---@return number
105    exec_lua(function()
106      _G.query_parse_count = _G.query_parse_count or 0
107      local parse = vim.treesitter.query.parse
108      vim.treesitter.query.parse = function(...)
109        _G.query_parse_count = _G.query_parse_count + 1
110        return parse(...)
111      end
112    end)
113
114    local function q(_n)
115      return exec_lua(function()
116        for _ = 1, _n, 1 do
117          vim.treesitter.query.get('c', 'highlights')
118        end
119        return _G.query_parse_count
120      end)
121    end
122
123    eq(1, q(10))
124    exec_lua(function()
125      vim.opt.rtp:prepend('/another/dir')
126    end)
127    eq(2, q(100))
128    exec_lua(function()
129      vim.treesitter.query.set('c', 'highlights', [[; test]])
130    end)
131    eq(3, q(100))
132  end)
133
134  it('supports query and iter by capture (iter_captures)', function()
135    insert(test_text)
136
137    local res = exec_lua(function()
138      local cquery = vim.treesitter.query.parse('c', test_query)
139      local parser = vim.treesitter.get_parser(0, 'c')
140      local tree = parser:parse()[1]
141      local res = {}
142      for cid, node in cquery:iter_captures(tree:root(), 0, 7, 14) do
143        -- can't transmit node over RPC. just check the name and range
144        table.insert(res, { '@' .. cquery.captures[cid], node:type(), node:range() })
145      end
146      return res
147    end)
148
149    eq({
150      { '@type', 'primitive_type', 8, 2, 8, 6 }, -- bool
151      { '@keyword', 'for', 9, 2, 9, 5 }, -- for
152      { '@type', 'primitive_type', 9, 7, 9, 13 }, -- size_t
153      { '@minfunc', 'identifier', 11, 12, 11, 15 }, -- "MIN"(ui->width, width);
154      { '@fieldarg', 'identifier', 11, 16, 11, 18 }, --      ui
155      { '@min_id', 'identifier', 11, 27, 11, 32 }, -- width
156      { '@minfunc', 'identifier', 12, 13, 12, 16 }, -- "MIN"(ui->height, height);
157      { '@fieldarg', 'identifier', 12, 17, 12, 19 }, --      ui
158      { '@min_id', 'identifier', 12, 29, 12, 35 }, -- height
159      { '@fieldarg', 'identifier', 13, 14, 13, 16 }, -- ui   ; in BAR(..)
160    }, res)
161  end)
162
163  it('supports query and iter by match (iter_matches)', function()
164    insert(test_text)
165
166    ---@type table
167    local res = exec_lua(function()
168      local cquery = vim.treesitter.query.parse('c', test_query)
169      local parser = vim.treesitter.get_parser(0, 'c')
170      local tree = parser:parse()[1]
171      local res = {}
172      for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14) do
173        -- can't transmit node over RPC. just check the name and range
174        local mrepr = {}
175        for cid, nodes in pairs(match) do
176          for _, node in ipairs(nodes) do
177            table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
178          end
179        end
180        table.insert(res, { pattern, mrepr })
181      end
182      return res
183    end)
184
185    eq({
186      { 3, { { '@type', 'primitive_type', 8, 2, 8, 6 } } },
187      { 2, { { '@keyword', 'for', 9, 2, 9, 5 } } },
188      { 3, { { '@type', 'primitive_type', 9, 7, 9, 13 } } },
189      { 4, { { '@fieldarg', 'identifier', 11, 16, 11, 18 } } },
190      {
191        1,
192        {
193          { '@minfunc', 'identifier', 11, 12, 11, 15 },
194          { '@min_id', 'identifier', 11, 27, 11, 32 },
195        },
196      },
197      { 4, { { '@fieldarg', 'identifier', 12, 17, 12, 19 } } },
198      {
199        1,
200        {
201          { '@minfunc', 'identifier', 12, 13, 12, 16 },
202          { '@min_id', 'identifier', 12, 29, 12, 35 },
203        },
204      },
205      { 4, { { '@fieldarg', 'identifier', 13, 14, 13, 16 } } },
206    }, res)
207  end)
208
209  it('supports query and iter by capture for quantifiers', function()
210    insert(test_text)
211
212    local res = exec_lua(function()
213      local cquery = vim.treesitter.query.parse(
214        'c',
215        '(expression_statement (assignment_expression (call_expression)))+ @funccall'
216      )
217      local parser = vim.treesitter.get_parser(0, 'c')
218      local tree = parser:parse()[1]
219      local res = {}
220      for cid, node in cquery:iter_captures(tree:root(), 0, 7, 14) do
221        -- can't transmit node over RPC. just check the name and range
222        table.insert(res, { '@' .. cquery.captures[cid], node:type(), node:range() })
223      end
224      return res
225    end)
226
227    eq({
228      { '@funccall', 'expression_statement', 11, 4, 11, 34 },
229      { '@funccall', 'expression_statement', 12, 4, 12, 37 },
230      { '@funccall', 'expression_statement', 13, 4, 13, 34 },
231    }, res)
232  end)
233
234  it('supports query and iter by match for quantifiers', function()
235    insert(test_text)
236
237    local res = exec_lua(function()
238      local cquery = vim.treesitter.query.parse(
239        'c',
240        '(expression_statement (assignment_expression (call_expression)))+ @funccall'
241      )
242      local parser = vim.treesitter.get_parser(0, 'c')
243      local tree = parser:parse()[1]
244      local res = {}
245      for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14) do
246        -- can't transmit node over RPC. just check the name and range
247        local mrepr = {}
248        for cid, nodes in pairs(match) do
249          for _, node in ipairs(nodes) do
250            table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
251          end
252        end
253        table.insert(res, { pattern, mrepr })
254      end
255      return res
256    end, '(expression_statement (assignment_expression (call_expression)))+ @funccall')
257
258    eq({
259      {
260        1,
261        {
262          { '@funccall', 'expression_statement', 11, 4, 11, 34 },
263          { '@funccall', 'expression_statement', 12, 4, 12, 37 },
264          { '@funccall', 'expression_statement', 13, 4, 13, 34 },
265        },
266      },
267    }, res)
268  end)
269
270  it('returns quantified matches in order of range #29344', function()
271    insert([[
272    int main() {
273      int a, b, c, d, e, f, g, h, i;
274      a = MIN(0, 1);
275      b = MIN(0, 1);
276      c = MIN(0, 1);
277      d = MIN(0, 1);
278      e = MIN(0, 1);
279      f = MIN(0, 1);
280      g = MIN(0, 1);
281      h = MIN(0, 1);
282      i = MIN(0, 1);
283    }
284    ]])
285
286    local res = exec_lua(function()
287      local cquery = vim.treesitter.query.parse(
288        'c',
289        '(expression_statement (assignment_expression (call_expression)))+ @funccall'
290      )
291      local parser = vim.treesitter.get_parser(0, 'c')
292      local tree = parser:parse()[1]
293      local res = {}
294      for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14) do
295        -- can't transmit node over RPC. just check the name and range
296        local mrepr = {}
297        for cid, nodes in pairs(match) do
298          for _, node in ipairs(nodes) do
299            table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
300          end
301        end
302        table.insert(res, { pattern, mrepr })
303      end
304      return res
305    end)
306
307    eq({
308      {
309        1,
310        {
311          { '@funccall', 'expression_statement', 2, 2, 2, 16 },
312          { '@funccall', 'expression_statement', 3, 2, 3, 16 },
313          { '@funccall', 'expression_statement', 4, 2, 4, 16 },
314          { '@funccall', 'expression_statement', 5, 2, 5, 16 },
315          { '@funccall', 'expression_statement', 6, 2, 6, 16 },
316          { '@funccall', 'expression_statement', 7, 2, 7, 16 },
317          { '@funccall', 'expression_statement', 8, 2, 8, 16 },
318          { '@funccall', 'expression_statement', 9, 2, 9, 16 },
319          { '@funccall', 'expression_statement', 10, 2, 10, 16 },
320        },
321      },
322    }, res)
323  end)
324
325  it('can match special regex characters like \\ * + ( with `vim-match?`', function()
326    insert('char* astring = "\\n"; (1 + 1) * 2 != 2;')
327
328    ---@type table
329    local res = exec_lua(function()
330      local query = (
331        '([_] @plus (#vim-match? @plus "^\\\\+$"))'
332        .. '([_] @times (#vim-match? @times "^\\\\*$"))'
333        .. '([_] @paren (#vim-match? @paren "^\\\\($"))'
334        .. '([_] @escape (#vim-match? @escape "^\\\\\\\\n$"))'
335        .. '([_] @string (#vim-match? @string "^\\"\\\\\\\\n\\"$"))'
336      )
337      local cquery = vim.treesitter.query.parse('c', query)
338      local parser = vim.treesitter.get_parser(0, 'c')
339      local tree = parser:parse()[1]
340      local res = {}
341      for pattern, match in cquery:iter_matches(tree:root(), 0, 0, -1) do
342        -- can't transmit node over RPC. just check the name and range
343        local mrepr = {}
344        for cid, nodes in pairs(match) do
345          for _, node in ipairs(nodes) do
346            table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
347          end
348        end
349        table.insert(res, { pattern, mrepr })
350      end
351      return res
352    end)
353
354    eq({
355      { 2, { { '@times', '*', 0, 4, 0, 5 } } },
356      { 5, { { '@string', 'string_literal', 0, 16, 0, 20 } } },
357      { 4, { { '@escape', 'escape_sequence', 0, 17, 0, 19 } } },
358      { 3, { { '@paren', '(', 0, 22, 0, 23 } } },
359      { 1, { { '@plus', '+', 0, 25, 0, 26 } } },
360      { 2, { { '@times', '*', 0, 30, 0, 31 } } },
361    }, res)
362  end)
363
364  it('supports builtin query predicate any-of?', function()
365    insert([[
366      #include <stdio.h>
367
368      int main(void) {
369        int i;
370        for(i=1; i<=100; i++) {
371          if(((i%3)||(i%5))== 0)
372            printf("number= %d FizzBuzz\n", i);
373          else if((i%3)==0)
374            printf("number= %d Fizz\n", i);
375          else if((i%5)==0)
376            printf("number= %d Buzz\n", i);
377          else
378            printf("number= %d\n",i);
379        }
380        return 0;
381      }
382    ]])
383
384    local res0 = exec_lua(
385      get_query_result,
386      [[((primitive_type) @c-keyword (#any-of? @c-keyword "int" "float"))]]
387    )
388    eq({
389      { 'c-keyword', 'primitive_type', { 2, 0, 2, 3 }, 'int' },
390      { 'c-keyword', 'primitive_type', { 3, 2, 3, 5 }, 'int' },
391    }, res0)
392
393    local res1 = exec_lua(
394      get_query_result,
395      [[
396        ((string_literal) @fizzbuzz-strings (#any-of? @fizzbuzz-strings
397          "\"number= %d FizzBuzz\\n\""
398          "\"number= %d Fizz\\n\""
399          "\"number= %d Buzz\\n\""
400        ))
401      ]]
402    )
403    eq({
404      { 'fizzbuzz-strings', 'string_literal', { 6, 13, 6, 36 }, '"number= %d FizzBuzz\\n"' },
405      { 'fizzbuzz-strings', 'string_literal', { 8, 13, 8, 32 }, '"number= %d Fizz\\n"' },
406      { 'fizzbuzz-strings', 'string_literal', { 10, 13, 10, 32 }, '"number= %d Buzz\\n"' },
407    }, res1)
408  end)
409
410  it('supports builtin predicate has-ancestor?', function()
411    insert([[
412      int x = 123;
413      enum C { y = 124 };
414      int main() { int z = 125; }]])
415
416    local result = exec_lua(
417      get_query_result,
418      [[((number_literal) @literal (#has-ancestor? @literal "function_definition"))]]
419    )
420    eq({ { 'literal', 'number_literal', { 2, 21, 2, 24 }, '125' } }, result)
421
422    result = exec_lua(
423      get_query_result,
424      [[((number_literal) @literal (#has-ancestor? @literal "function_definition" "enum_specifier"))]]
425    )
426    eq({
427      { 'literal', 'number_literal', { 1, 13, 1, 16 }, '124' },
428      { 'literal', 'number_literal', { 2, 21, 2, 24 }, '125' },
429    }, result)
430
431    result = exec_lua(
432      get_query_result,
433      [[((number_literal) @literal (#not-has-ancestor? @literal "enum_specifier"))]]
434    )
435    eq({
436      { 'literal', 'number_literal', { 0, 8, 0, 11 }, '123' },
437      { 'literal', 'number_literal', { 2, 21, 2, 24 }, '125' },
438    }, result)
439
440    result = exec_lua(
441      get_query_result,
442      [[((number_literal) @literal (#has-ancestor? @literal "enumerator"))]]
443    )
444    eq({
445      { 'literal', 'number_literal', { 1, 13, 1, 16 }, '124' },
446    }, result)
447
448    result = exec_lua(
449      get_query_result,
450      [[((number_literal) @literal (#has-ancestor? @literal "number_literal"))]]
451    )
452    eq({}, result)
453  end)
454
455  it('supports builtin predicate has-parent?', function()
456    insert([[
457      int x = 123;
458      enum C { y = 124 };]])
459
460    local result = exec_lua(
461      get_query_result,
462      [[((number_literal) @literal (#has-parent? @literal "init_declarator"))]]
463    )
464    eq({ { 'literal', 'number_literal', { 0, 8, 0, 11 }, '123' } }, result)
465
466    -- The root node has no parent: the predicate does not match, rather than
467    -- erroring on the nil parent.
468    result = exec_lua(
469      get_query_result,
470      [[((translation_unit) @root (#has-parent? @root "translation_unit"))]]
471    )
472    eq({}, result)
473  end)
474
475  it('allows loading query with escaped quotes and capture them `#{lua,vim}-match`?', function()
476    insert('char* astring = "Hello World!";')
477
478    local res = exec_lua(function()
479      local cquery = vim.treesitter.query.parse(
480        'c',
481        '([_] @quote (#vim-match? @quote "^\\"$")) ([_] @quote (#lua-match? @quote "^\\"$"))'
482      )
483      local parser = vim.treesitter.get_parser(0, 'c')
484      local tree = parser:parse()[1]
485      local res = {}
486      for pattern, match in cquery:iter_matches(tree:root(), 0, 0, -1) do
487        -- can't transmit node over RPC. just check the name and range
488        local mrepr = {}
489        for cid, nodes in pairs(match) do
490          for _, node in ipairs(nodes) do
491            table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
492          end
493        end
494        table.insert(res, { pattern, mrepr })
495      end
496      return res
497    end)
498
499    eq({
500      { 1, { { '@quote', '"', 0, 16, 0, 17 } } },
501      { 2, { { '@quote', '"', 0, 16, 0, 17 } } },
502      { 1, { { '@quote', '"', 0, 29, 0, 30 } } },
503      { 2, { { '@quote', '"', 0, 29, 0, 30 } } },
504    }, res)
505  end)
506
507  it('allows to add predicates', function()
508    insert([[
509    int main(void) {
510      return 0;
511    }
512    ]])
513
514    local custom_query = '((identifier) @main (#is-main? @main))'
515
516    do
517      local res = exec_lua(function()
518        local query = vim.treesitter.query
519
520        local function is_main(match, _pattern, bufnr, predicate)
521          local nodes = match[predicate[2]]
522          for _, node in ipairs(nodes) do
523            if vim.treesitter.get_node_text(node, bufnr) == 'main' then
524              return true
525            end
526          end
527          return false
528        end
529
530        local parser = vim.treesitter.get_parser(0, 'c')
531
532        query.add_predicate('is-main?', is_main)
533
534        local query0 = query.parse('c', custom_query)
535
536        local nodes = {}
537        for _, node in query0:iter_captures(parser:parse()[1]:root(), 0) do
538          table.insert(nodes, { node:range() })
539        end
540
541        return nodes
542      end)
543
544      eq({ { 0, 4, 0, 8 } }, res)
545    end
546
547    do
548      local res = exec_lua(function()
549        local query = vim.treesitter.query
550
551        local r = {}
552        for _, v in ipairs(query.list_predicates()) do
553          r[v] = true
554        end
555
556        return r
557      end)
558
559      eq(true, res['is-main?'])
560    end
561  end)
562
563  it('supports "all" and "any" semantics for predicates on quantified captures #24738', function()
564    local query_all = [[
565      (((comment (comment_content))+) @bar
566        (#lua-match? @bar "Yes"))
567    ]]
568
569    local query_any = [[
570      (((comment (comment_content))+) @bar
571        (#any-lua-match? @bar "Yes"))
572    ]]
573
574    local function test(input, query)
575      api.nvim_buf_set_lines(0, 0, -1, true, vim.split(dedent(input), '\n'))
576      return exec_lua(function()
577        local parser = vim.treesitter.get_parser(0, 'lua')
578        local query0 = vim.treesitter.query.parse('lua', query)
579        local nodes = {}
580        for _, node in query0:iter_captures(parser:parse()[1]:root(), 0) do
581          nodes[#nodes + 1] = { node:range() }
582        end
583        return nodes
584      end)
585    end
586
587    eq(
588      {},
589      test(
590        [[
591      -- Yes
592      -- No
593      -- Yes
594    ]],
595        query_all
596      )
597    )
598
599    eq(
600      {
601        { 0, 0, 0, 6 },
602        { 1, 0, 1, 6 },
603        { 2, 0, 2, 6 },
604      },
605      test(
606        [[
607      -- Yes
608      -- Yes
609      -- Yes
610    ]],
611        query_all
612      )
613    )
614
615    eq(
616      {},
617      test(
618        [[
619      -- No
620      -- No
621      -- No
622    ]],
623        query_any
624      )
625    )
626
627    eq(
628      {
629        { 0, 0, 0, 5 },
630        { 1, 0, 1, 6 },
631        { 2, 0, 2, 5 },
632      },
633      test(
634        [[
635      -- No
636      -- Yes
637      -- No
638    ]],
639        query_any
640      )
641    )
642  end)
643
644  it('supports any- prefix to match any capture when using quantifiers #24738', function()
645    insert([[
646      -- Comment
647      -- Comment
648      -- Comment
649    ]])
650
651    local result = exec_lua(function()
652      local parser = vim.treesitter.get_parser(0, 'lua')
653      local query = vim.treesitter.query.parse(
654        'lua',
655        [[
656      (((comment (comment_content))+) @bar
657        (#lua-match? @bar "Comment"))
658    ]]
659      )
660      local nodes = {}
661      for _, node in query:iter_captures(parser:parse()[1]:root(), 0) do
662        nodes[#nodes + 1] = { node:range() }
663      end
664      return nodes
665    end)
666
667    eq({
668      { 0, 0, 0, 10 },
669      { 1, 0, 1, 10 },
670      { 2, 0, 2, 10 },
671    }, result)
672  end)
673
674  it('should use node range when omitted', function()
675    local txt = [[
676      int foo = 42;
677      int bar = 13;
678    ]]
679
680    local ret = exec_lua(function()
681      local parser = vim.treesitter.get_string_parser(txt, 'c')
682
683      local nodes = {}
684      local query = vim.treesitter.query.parse('c', '((identifier) @foo)')
685      local first_child = assert(parser:parse()[1]:root():child(1))
686
687      for _, node in query:iter_captures(first_child, txt) do
688        table.insert(nodes, { node:range() })
689      end
690
691      return nodes
692    end)
693
694    eq({ { 1, 10, 1, 13 } }, ret)
695  end)
696
697  it('iter_captures supports columns', function()
698    local txt = table.concat({
699      'int aaa = 1, bbb = 2;',
700      'int foo = 1, bar = 2;',
701      'int baz = 3, qux = 4;',
702      'int ccc = 1, ddd = 2;',
703    }, '\n')
704
705    local function test(opts)
706      local parser = vim.treesitter.get_string_parser(txt, 'c')
707
708      local nodes = {}
709      local query = vim.treesitter.query.parse('c', '((identifier) @foo)')
710      local root = assert(parser:parse()[1]:root())
711      local iter = query:iter_captures(root, txt, 1, 2, opts)
712
713      while true do
714        local capture, node = iter()
715        if not capture then
716          break
717        end
718        table.insert(nodes, { node:range() })
719      end
720
721      return nodes
722    end
723
724    local ret
725    ret = exec_lua(test, { start_col = 7, end_col = 13 })
726    eq({ { 1, 13, 1, 16 }, { 2, 4, 2, 7 } }, ret)
727
728    ret = exec_lua(test, { start_col = 7 })
729    eq({ { 1, 13, 1, 16 } }, ret)
730
731    ret = exec_lua(test, { end_col = 13 })
732    eq({ { 1, 4, 1, 7 }, { 1, 13, 1, 16 }, { 2, 4, 2, 7 } }, ret)
733
734    ret = exec_lua(test, {})
735    eq({ { 1, 4, 1, 7 }, { 1, 13, 1, 16 } }, ret)
736  end)
737
738  it('fails to load queries', function()
739    local function test(exp, cquery)
740      eq(exp, pcall_err(exec_lua, "vim.treesitter.query.parse('c', ...)", cquery))
741    end
742
743    -- Invalid node types
744    test(
745      '.../query.lua:0: Query error at 1:2. Invalid node type ">\\">>":\n'
746        .. '">\\">>" @operator\n'
747        .. ' ^',
748      '">\\">>" @operator'
749    )
750    test(
751      '.../query.lua:0: Query error at 1:2. Invalid node type "\\\\":\n'
752        .. '"\\\\" @operator\n'
753        .. ' ^',
754      '"\\\\" @operator'
755    )
756    test(
757      '.../query.lua:0: Query error at 1:2. Invalid node type ">>>":\n'
758        .. '">>>" @operator\n'
759        .. ' ^',
760      '">>>" @operator'
761    )
762    test(
763      '.../query.lua:0: Query error at 1:2. Invalid node type "dentifier":\n'
764        .. '(dentifier) @variable\n'
765        .. ' ^',
766      '(dentifier) @variable'
767    )
768
769    -- Impossible pattern
770    test(
771      '.../query.lua:0: Query error at 1:13. Impossible pattern:\n'
772        .. '(identifier (identifier) @variable)\n'
773        .. '            ^',
774      '(identifier (identifier) @variable)'
775    )
776
777    -- Invalid syntax
778    test(
779      '.../query.lua:0: Query error at 1:13. Invalid syntax:\n'
780        .. '(identifier @variable\n'
781        .. '            ^',
782      '(identifier @variable'
783    )
784
785    -- Invalid field name
786    test(
787      '.../query.lua:0: Query error at 1:15. Invalid field name "invalid_field":\n'
788        .. '((identifier) invalid_field: (identifier))\n'
789        .. '              ^',
790      '((identifier) invalid_field: (identifier))'
791    )
792
793    -- Invalid capture name
794    test(
795      '.../query.lua:0: Query error at 3:2. Invalid capture name "ok.capture":\n'
796        .. '@ok.capture\n'
797        .. ' ^',
798      '((identifier) @id \n(#eq? @id\n@ok.capture\n))'
799    )
800  end)
801
802  it('supports "; extends" modeline in custom queries', function()
803    insert('int zeero = 0;')
804    local result = exec_lua(function()
805      vim.treesitter.query.set(
806        'c',
807        'highlights',
808        [[; extends
809        (identifier) @spell]]
810      )
811      local query = vim.treesitter.query.get('c', 'highlights')
812      local parser = vim.treesitter.get_parser(0, 'c')
813      local root = parser:parse()[1]:root()
814      local res = {}
815      for id, node in query:iter_captures(root, 0) do
816        table.insert(res, { query.captures[id], vim.treesitter.get_node_text(node, 0) })
817      end
818      return res
819    end)
820    eq({
821      { 'type.builtin', 'int' },
822      { 'variable', 'zeero' },
823      { 'spell', 'zeero' },
824      { 'operator', '=' },
825      { 'number', '0' },
826      { 'punctuation.delimiter', ';' },
827    }, result)
828  end)
829
830  describe('Query:iter_captures', function()
831    it('includes metadata for all captured nodes #23664', function()
832      insert([[
833        const char *sql = "SELECT * FROM Students WHERE name = 'Robert'); DROP TABLE Students;--";
834      ]])
835
836      local result = exec_lua(function()
837        local query = vim.treesitter.query.parse(
838          'c',
839          [[
840        (declaration
841          type: (_)
842          declarator: (init_declarator
843            declarator: (pointer_declarator
844              declarator: (identifier)) @_id
845            value: (string_literal
846              (string_content) @injection.content))
847          (#set! injection.language "sql")
848          (#contains? @_id "sql"))
849      ]]
850        )
851        local parser = vim.treesitter.get_parser(0, 'c')
852        local root = parser:parse()[1]:root()
853        local res = {}
854        for id, _, metadata in query:iter_captures(root, 0) do
855          res[query.captures[id]] = metadata
856        end
857        return res
858      end)
859
860      eq({
861        ['_id'] = { ['injection.language'] = 'sql' },
862        ['injection.content'] = { ['injection.language'] = 'sql' },
863      }, result)
864    end)
865
866    it('only evaluates predicates once per match', function()
867      insert([[
868        void foo(int x, int y);
869      ]])
870      local query = [[
871        (declaration
872          type: (_)
873          declarator: (function_declarator
874            declarator: (identifier) @function.name
875            parameters: (parameter_list
876              (parameter_declaration
877                type: (_)
878                declarator: (identifier) @argument)))
879          (#eq? @function.name "foo"))
880      ]]
881
882      local result = exec_lua(function()
883        local query0 = vim.treesitter.query.parse('c', query)
884        local match_preds = query0._match_predicates
885        local called = 0
886        function query0._match_predicates(...)
887          called = called + 1
888          return match_preds(...)
889        end
890        local parser = vim.treesitter.get_parser(0, 'c')
891        local root = parser:parse()[1]:root()
892        local captures = {}
893        for id in query0:iter_captures(root, 0) do
894          captures[#captures + 1] = id
895        end
896        return { called, captures }
897      end)
898
899      eq({ 2, { 1, 1, 2, 2 } }, result)
900    end)
901  end)
902
903  describe('TSQuery', function()
904    local source = [[
905      void foo(int x, int y);
906    ]]
907
908    local query_text = [[
909      ((identifier) @func
910        (#eq? @func "foo"))
911      ((identifier) @param
912        (#eq? @param "x"))
913      ((identifier) @param
914        (#eq? @param "y"))
915    ]]
916
917    ---@param query string
918    ---@param disabled { capture: string?, pattern: integer? }
919    local function get_patterns(query, disabled)
920      local q = vim.treesitter.query.parse('c', query)
921      if disabled.capture then
922        q.query:disable_capture(disabled.capture)
923      end
924      if disabled.pattern then
925        q.query:disable_pattern(disabled.pattern)
926      end
927
928      local parser = vim.treesitter.get_parser(0, 'c')
929      local root = parser:parse()[1]:root()
930      local captures = {} ---@type {id: number, pattern: number}[]
931      for id, _, _, match in q:iter_captures(root, 0) do
932        local _, pattern = match:info()
933        captures[#captures + 1] = { id = id, pattern = pattern }
934      end
935      return captures
936    end
937
938    it('supports disabling patterns', function()
939      insert(source)
940      local result = exec_lua(get_patterns, query_text, { pattern = 2 })
941      eq({ { id = 1, pattern = 1 }, { id = 2, pattern = 3 } }, result)
942    end)
943
944    it('supports disabling captures', function()
945      insert(source)
946      local result = exec_lua(get_patterns, query_text, { capture = 'param' })
947      eq({ { id = 1, pattern = 1 } }, result)
948    end)
949  end)
950end)