robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
47.5 KiB1606 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local ts_t = require('test.functional.treesitter.testutil')
4
5local describe, it, before_each = t.describe, t.it, t.before_each
6local clear = n.clear
7local dedent = t.dedent
8local eq = t.eq
9local insert = n.insert
10local exec_lua = n.exec_lua
11local feed = n.feed
12local matches = t.matches
13local pcall_err = t.pcall_err
14local run_query = ts_t.run_query
15local assert_alive = n.assert_alive
16
17describe('treesitter parser API', function()
18  before_each(function()
19    clear()
20    exec_lua(function()
21      vim.g.__ts_debug = 1
22    end)
23  end)
24
25  it('parses buffer', function()
26    insert([[
27      int main() {
28        int x = 3;
29      }]])
30
31    exec_lua(function()
32      _G.parser = vim.treesitter.get_parser(0, 'c')
33      _G.tree = _G.parser:parse()[1]
34      _G.root = _G.tree:root()
35      _G.lang = vim.treesitter.language.inspect('c')
36    end)
37
38    eq('<tree>', exec_lua('return tostring(tree)'))
39    eq('<node translation_unit>', exec_lua('return tostring(root)'))
40    eq({ 0, 0, 3, 0 }, exec_lua('return {root:range()}'))
41
42    eq(1, exec_lua('return root:child_count()'))
43    exec_lua('child = root:child(0)')
44    eq('<node function_definition>', exec_lua('return tostring(child)'))
45    eq({ 0, 0, 2, 1 }, exec_lua('return {child:range()}'))
46
47    eq('function_definition', exec_lua('return child:type()'))
48    eq(true, exec_lua('return child:named()'))
49    eq('number', type(exec_lua('return child:symbol()')))
50    eq(true, exec_lua('return lang.symbols[child:type()]'))
51
52    exec_lua('anon = root:descendant_for_range(0,8,0,9)')
53    eq('(', exec_lua('return anon:type()'))
54    eq(false, exec_lua('return anon:named()'))
55    eq('number', type(exec_lua('return anon:symbol()')))
56    eq(false, exec_lua([=[return lang.symbols[string.format('"%s"', anon:type())]]=]))
57
58    exec_lua('descendant = root:descendant_for_range(1,2,1,12)')
59    eq('<node declaration>', exec_lua('return tostring(descendant)'))
60    eq({ 1, 2, 1, 12 }, exec_lua('return {descendant:range()}'))
61    eq(
62      '(declaration type: (primitive_type) declarator: (init_declarator declarator: (identifier) value: (number_literal)))',
63      exec_lua('return descendant:sexpr()')
64    )
65
66    feed('2G7|ay')
67    exec_lua(function()
68      _G.tree2 = _G.parser:parse()[1]
69      _G.root2 = _G.tree2:root()
70      _G.descendant2 = _G.root2:descendant_for_range(1, 2, 1, 13)
71    end)
72    eq(false, exec_lua('return tree2 == tree1'))
73    eq(false, exec_lua('return root2 == root'))
74    eq('<node declaration>', exec_lua('return tostring(descendant2)'))
75    eq({ 1, 2, 1, 13 }, exec_lua('return {descendant2:range()}'))
76
77    eq(true, exec_lua('return child == child'))
78    -- separate lua object, but represents same node
79    eq(true, exec_lua('return child == root:child(0)'))
80    eq(false, exec_lua('return child == descendant2'))
81    eq(false, exec_lua('return child == nil'))
82    eq(false, exec_lua('return child == tree'))
83
84    eq('string', exec_lua('return type(child:id())'))
85    eq(true, exec_lua('return child:id() == child:id()'))
86    -- separate lua object, but represents same node
87    eq(true, exec_lua('return child:id() == root:child(0):id()'))
88    eq(false, exec_lua('return child:id() == descendant2:id()'))
89    eq(false, exec_lua('return child:id() == nil'))
90    eq(false, exec_lua('return child:id() == tree'))
91
92    -- unchanged buffer: return the same tree
93    eq(true, exec_lua('return parser:parse()[1] == tree2'))
94  end)
95
96  it('preserves full-document included ranges', function()
97    insert([[
98      local _ = 1
99    ]])
100
101    eq(
102      {
103        { 0, 0, 0, 4294967295, 4294967295, 4294967295 },
104      },
105      exec_lua(function()
106        local parser = vim.treesitter.get_parser(0, 'lua')
107        local tree = parser:parse()[1]
108        return tree:included_ranges(true)
109      end)
110    )
111  end)
112
113  it('ignores repeated parser finalization', function()
114    matches(
115      'Parser has been deleted',
116      pcall_err(exec_lua, function()
117        vim.treesitter.language.add('c')
118
119        local parser = vim._create_ts_parser('c')
120        -- The parser metatable exposes __gc through __index, so this simulates a finalizer
121        -- running before all Lua references to the userdata are gone.
122        parser:__gc()
123        parser:__gc()
124
125        parser:parse(nil, 'int x;', false)
126      end)
127    )
128    assert_alive()
129  end)
130
131  it('respects eol settings when parsing buffer', function()
132    insert([[
133      int main() {
134        int x = 3;
135      } // :D]])
136
137    exec_lua(function()
138      vim.bo.eol = false
139      vim.bo.fixeol = false
140      _G.parser = vim.treesitter.get_parser(0, 'c')
141      _G.tree = _G.parser:parse()[1]
142      _G.root = _G.tree:root()
143      _G.lang = vim.treesitter.language.inspect('c')
144    end)
145
146    eq(
147      '<node translation_unit>',
148      exec_lua(function()
149        return tostring(_G.root)
150      end)
151    )
152    eq(
153      { 0, 0, 0, 2, 7, 33 },
154      exec_lua(function()
155        return { _G.root:range(true) }
156      end)
157    )
158
159    -- NOTE: Changing these settings marks the buffer as `modified` but does not fire `on_bytes`,
160    -- meaning this test case does not pass... is this intended?
161    -- exec_lua(function()
162    --   vim.bo.eol = true
163    --   vim.bo.fixeol = true
164    --   vim.cmd.update()
165    --   _G.parser = vim.treesitter.get_parser(0, 'c')
166    --   _G.tree = _G.parser:parse()[1]
167    --   _G.root = _G.tree:root()
168    --   _G.lang = vim.treesitter.language.inspect('c')
169    -- end)
170    --
171    -- eq(
172    --   '<node translation_unit>',
173    --   exec_lua(function()
174    --     return tostring(root)
175    --   end)
176    -- )
177    -- eq(
178    --   { 0, 0, 0, 3, 0, 34 },
179    --   exec_lua(function()
180    --     return { root:range(true) }
181    --   end)
182    -- )
183  end)
184
185  it('parses buffer asynchronously', function()
186    insert([[
187      int main() {
188        int x = 3;
189      }]])
190
191    exec_lua(function()
192      _G.parser = vim.treesitter.get_parser(0, 'c')
193      _G.lang = vim.treesitter.language.inspect('c')
194      _G.parser:parse(nil, function(_, trees)
195        _G.tree = trees[1]
196        _G.root = _G.tree:root()
197      end)
198      vim.wait(100, function() end)
199    end)
200
201    eq('<tree>', exec_lua('return tostring(tree)'))
202    eq('<node translation_unit>', exec_lua('return tostring(root)'))
203    eq({ 0, 0, 3, 0 }, exec_lua('return {root:range()}'))
204
205    eq(1, exec_lua('return root:child_count()'))
206    exec_lua('child = root:child(0)')
207    eq('<node function_definition>', exec_lua('return tostring(child)'))
208    eq({ 0, 0, 2, 1 }, exec_lua('return {child:range()}'))
209
210    eq('function_definition', exec_lua('return child:type()'))
211    eq(true, exec_lua('return child:named()'))
212    eq('number', type(exec_lua('return child:symbol()')))
213    eq(true, exec_lua('return lang.symbols[child:type()]'))
214
215    exec_lua('anon = root:descendant_for_range(0,8,0,9)')
216    eq('(', exec_lua('return anon:type()'))
217    eq(false, exec_lua('return anon:named()'))
218    eq('number', type(exec_lua('return anon:symbol()')))
219    eq(false, exec_lua([=[return lang.symbols[string.format('"%s"', anon:type())]]=]))
220
221    exec_lua('descendant = root:descendant_for_range(1,2,1,12)')
222    eq('<node declaration>', exec_lua('return tostring(descendant)'))
223    eq({ 1, 2, 1, 12 }, exec_lua('return {descendant:range()}'))
224    eq(
225      '(declaration type: (primitive_type) declarator: (init_declarator declarator: (identifier) value: (number_literal)))',
226      exec_lua('return descendant:sexpr()')
227    )
228
229    feed('2G7|ay')
230    exec_lua(function()
231      _G.parser:parse(nil, function(_, trees)
232        _G.tree2 = trees[1]
233        _G.root2 = _G.tree2:root()
234        _G.descendant2 = _G.root2:descendant_for_range(1, 2, 1, 13)
235      end)
236      vim.wait(100, function() end)
237    end)
238    eq(false, exec_lua('return tree2 == tree1'))
239    eq(false, exec_lua('return root2 == root'))
240    eq('<node declaration>', exec_lua('return tostring(descendant2)'))
241    eq({ 1, 2, 1, 13 }, exec_lua('return {descendant2:range()}'))
242
243    eq(true, exec_lua('return child == child'))
244    -- separate lua object, but represents same node
245    eq(true, exec_lua('return child == root:child(0)'))
246    eq(false, exec_lua('return child == descendant2'))
247    eq(false, exec_lua('return child == nil'))
248    eq(false, exec_lua('return child == tree'))
249
250    eq('string', exec_lua('return type(child:id())'))
251    eq(true, exec_lua('return child:id() == child:id()'))
252    -- separate lua object, but represents same node
253    eq(true, exec_lua('return child:id() == root:child(0):id()'))
254    eq(false, exec_lua('return child:id() == descendant2:id()'))
255    eq(false, exec_lua('return child:id() == nil'))
256    eq(false, exec_lua('return child:id() == tree'))
257
258    -- unchanged buffer: return the same tree
259    eq(true, exec_lua('return parser:parse()[1] == tree2'))
260  end)
261
262  it('does not crash when editing large files', function()
263    insert([[printf("%s", "some text");]])
264    feed('yy49999p')
265
266    exec_lua(function()
267      _G.parser = vim.treesitter.get_parser(0, 'c')
268      _G.done = false
269      vim.treesitter.start(0, 'c')
270      _G.parser:parse(nil, function()
271        _G.done = true
272      end)
273      while not _G.done do
274        -- Busy wait until async parsing has completed
275        vim.wait(100, function() end)
276      end
277    end)
278
279    eq(true, exec_lua([[return done]]))
280    exec_lua(function()
281      vim.api.nvim_input('Lxj')
282    end)
283    exec_lua(function()
284      vim.api.nvim_input('xj')
285    end)
286    exec_lua(function()
287      vim.api.nvim_input('xj')
288    end)
289    assert_alive()
290  end)
291
292  it('resets parsing state on tree changes', function()
293    insert([[vim.api.nvim_set_hl(0, 'test2', { bg = 'green' })]])
294    feed('yy1000p')
295
296    exec_lua(function()
297      vim.cmd('set ft=lua')
298
299      vim.treesitter.start(0)
300      local parser = assert(vim.treesitter.get_parser(0))
301
302      parser:parse(true, function() end)
303      vim.api.nvim_buf_set_lines(0, 1, -1, false, {})
304      parser:parse(true)
305    end)
306  end)
307
308  it('resets when buffer was editing during an async parse', function()
309    insert([[printf("%s", "some text");]])
310    feed('yy49999p')
311    feed('gg4jO// Comment<Esc>')
312
313    exec_lua(function()
314      _G.parser = vim.treesitter.get_parser(0, 'c')
315      _G.done = false
316      vim.treesitter.start(0, 'c')
317      _G.parser:parse(nil, function()
318        _G.done = true
319      end)
320    end)
321
322    exec_lua(function()
323      vim.api.nvim_input('ggdj')
324    end)
325
326    eq(false, exec_lua([[return done]]))
327    exec_lua(function()
328      while not _G.done do
329        -- Busy wait until async parsing finishes
330        vim.wait(100, function() end)
331      end
332    end)
333    eq(true, exec_lua([[return done]]))
334    eq('comment', exec_lua([[return parser:parse()[1]:root():named_child(2):type()]]))
335    eq({ 2, 0, 2, 10 }, exec_lua([[return {parser:parse()[1]:root():named_child(2):range()}]]))
336  end)
337
338  it('handles multiple async parse calls', function()
339    insert([[printf("%s", "some text");]])
340    feed('yy49999p')
341
342    exec_lua(function()
343      -- Spy on vim.schedule
344      local schedule = vim.schedule
345      vim.schedule = function(fn)
346        _G.schedules = _G.schedules + 1
347        schedule(fn)
348      end
349      _G.schedules = 0
350      _G.parser = vim.treesitter.get_parser(0, 'c')
351      for i = 1, 5 do
352        _G['done' .. i] = false
353        _G.parser:parse(nil, function()
354          _G['done' .. i] = true
355        end)
356      end
357      schedule(function()
358        _G.schedules_snapshot = _G.schedules
359      end)
360    end)
361
362    eq(2, exec_lua([[return schedules_snapshot]]))
363    eq(
364      { false, false, false, false, false },
365      exec_lua([[return { done1, done2, done3, done4, done5 }]])
366    )
367    exec_lua(function()
368      while not _G.done1 do
369        -- Busy wait until async parsing finishes
370        vim.wait(100, function() end)
371      end
372    end)
373    eq({ true, true, true, true, true }, exec_lua([[return { done1, done2, done3, done4, done5 }]]))
374  end)
375
376  local test_text = [[
377    void ui_refresh(void)
378    {
379      int width = INT_MAX, height = INT_MAX;
380      bool ext_widgets[kUIExtCount];
381      for (UIExtension i = 0; (int)i < kUIExtCount; i++) {
382        ext_widgets[i] = true;
383      }
384
385      bool inclusive = ui_override();
386      for (size_t i = 0; i < ui_count; i++) {
387        UI *ui = uis[i];
388        width = MIN(ui->width, width);
389        height = MIN(ui->height, height);
390        foo = BAR(ui->bazaar, bazaar);
391        for (UIExtension j = 0; (int)j < kUIExtCount; j++) {
392          ext_widgets[j] &= (ui->ui_ext[j] || inclusive);
393        }
394      }
395    }]]
396
397  it('can iterate over nodes children', function()
398    insert(test_text)
399
400    local res = exec_lua(function()
401      local parser = vim.treesitter.get_parser(0, 'c')
402
403      local func_node = parser:parse()[1]:root():child(0)
404
405      local res = {}
406      for node, field in func_node:iter_children() do
407        table.insert(res, { node:type(), field })
408      end
409      return res
410    end)
411
412    eq({
413      { 'primitive_type', 'type' },
414      { 'function_declarator', 'declarator' },
415      { 'compound_statement', 'body' },
416    }, res)
417  end)
418
419  it('does not get parser for empty filetype', function()
420    insert(test_text)
421
422    local parser, error = exec_lua(function()
423      return vim.treesitter.get_parser(0)
424    end)
425    eq(vim.NIL, parser)
426    eq('Parser not found for buffer 1: language could not be determined', error)
427
428    -- Must provide language for buffers with an empty filetype
429    exec_lua("vim.treesitter.get_parser(0, 'c')")
430  end)
431
432  it('can get a child by field', function()
433    insert(test_text)
434
435    local res = exec_lua(function()
436      local parser = vim.treesitter.get_parser(0, 'c')
437
438      _G.func_node = parser:parse()[1]:root():child(0)
439
440      local res = {}
441      for _, node in ipairs(_G.func_node:field('type')) do
442        table.insert(res, { node:type(), node:range() })
443      end
444      return res
445    end)
446
447    eq({ { 'primitive_type', 0, 0, 0, 4 } }, res)
448
449    local res_fail = exec_lua(function()
450      vim.treesitter.get_parser(0, 'c')
451
452      return #_G.func_node:field('foo') == 0
453    end)
454
455    assert(res_fail)
456  end)
457
458  it('can get text of multiline node', function()
459    insert(test_text)
460    local res = exec_lua(function()
461      local parser = vim.treesitter.get_parser(0, 'c')
462      local tree = parser:parse()[1]
463      return vim.treesitter.get_node_text(tree:root(), 0)
464    end)
465    eq(t.dedent(test_text) .. '\n', res)
466
467    local res2 = exec_lua(function()
468      local parser = vim.treesitter.get_parser(0, 'c')
469      local root = parser:parse()[1]:root()
470      return vim.treesitter.get_node_text(root:child(0):child(0), 0)
471    end)
472    eq('void', res2)
473  end)
474
475  it('can get text where start of node is one past EOF', function()
476    local text = [[
477      def run
478        a = <<~E
479      end]]
480    insert(text)
481    eq(
482      '',
483      exec_lua(function()
484        local fake_node = {}
485        function fake_node:start()
486          return 3, 0, 23
487        end
488        function fake_node:end_()
489          return 3, 0, 23
490        end
491        function fake_node:range(bytes)
492          if bytes then
493            return 3, 0, 23, 3, 0, 23
494          end
495          return 3, 0, 3, 0
496        end
497        return vim.treesitter.get_node_text(fake_node, 0)
498      end)
499    )
500  end)
501
502  it('can get empty text if node range is zero-width', function()
503    local text = [[
504      ```lua
505      {}
506      ```
507    ]]
508    insert(text)
509    local result = exec_lua(function()
510      local fake_node = {}
511      function fake_node:start()
512        return 1, 0, 7
513      end
514      function fake_node:end_()
515        return 1, 0, 7
516      end
517      function fake_node:range()
518        return 1, 0, 1, 0
519      end
520      return vim.treesitter.get_node_text(fake_node, 0) == ''
521    end)
522    eq(true, result)
523  end)
524
525  it('can set simple ranges', function()
526    insert(test_text)
527
528    local res = exec_lua(function()
529      _G.parser = vim.treesitter.get_parser(0, 'c')
530      return { _G.parser:parse()[1]:root():range() }
531    end)
532
533    eq({ 0, 0, 19, 0 }, res)
534
535    -- The following sets the included ranges for the current parser
536    -- As stated here, this only includes the function (thus the whole buffer, without the last line)
537    local res2 = exec_lua(function()
538      local root = _G.parser:parse()[1]:root()
539      _G.parser:set_included_regions({ { root:child(0) } })
540      _G.parser:invalidate()
541      return { _G.parser:parse(true)[1]:root():range() }
542    end)
543
544    eq({ 0, 0, 18, 1 }, res2)
545
546    eq({ { { 0, 0, 0, 18, 1, 512 } } }, exec_lua [[ return parser:included_regions() ]])
547
548    local range_tbl = exec_lua(function()
549      _G.parser:set_included_regions { { { 0, 0, 17, 1 } } }
550      _G.parser:parse()
551      return _G.parser:included_regions()
552    end)
553
554    eq({ { { 0, 0, 0, 17, 1, 508 } } }, range_tbl)
555  end)
556
557  it('can set complex ranges', function()
558    insert(test_text)
559
560    local res = exec_lua(function()
561      local parser = vim.treesitter.get_parser(0, 'c')
562      local query = vim.treesitter.query.parse('c', '(declaration) @decl')
563
564      local nodes = {}
565      for _, node in query:iter_captures(parser:parse()[1]:root(), 0) do
566        table.insert(nodes, node)
567      end
568
569      parser:set_included_regions({ nodes })
570
571      local root = parser:parse(true)[1]:root()
572
573      local res = {}
574      for i = 0, (root:named_child_count() - 1) do
575        table.insert(res, { root:named_child(i):range() })
576      end
577      return res
578    end)
579
580    eq({
581      { 2, 2, 2, 40 },
582      { 3, 2, 3, 32 },
583      { 4, 7, 4, 25 },
584      { 8, 2, 8, 33 },
585      { 9, 7, 9, 20 },
586      { 10, 4, 10, 20 },
587      { 14, 9, 14, 27 },
588    }, res)
589  end)
590
591  it('can create string parsers', function()
592    local ret = exec_lua(function()
593      local parser = vim.treesitter.get_string_parser('int foo = 42;', 'c')
594      return { parser:parse()[1]:root():range() }
595    end)
596
597    eq({ 0, 0, 0, 13 }, ret)
598  end)
599
600  it('can run async parses with string parsers', function()
601    local ret = exec_lua(function()
602      local parser = vim.treesitter.get_string_parser('int foo = 42;', 'c')
603      return { parser:parse(nil, function() end)[1]:root():range() }
604    end)
605
606    eq({ 0, 0, 0, 13 }, ret)
607  end)
608
609  it('can run queries with string parsers', function()
610    local txt = [[
611      int foo = 42;
612      int bar = 13;
613    ]]
614
615    local ret = exec_lua(function(str)
616      local parser = vim.treesitter.get_string_parser(str, 'c')
617
618      local nodes = {}
619      local query = vim.treesitter.query.parse('c', '((identifier) @id (#eq? @id "foo"))')
620
621      for _, node in query:iter_captures(parser:parse()[1]:root(), str) do
622        table.insert(nodes, { node:range() })
623      end
624
625      return nodes
626    end, txt)
627
628    eq({ { 0, 10, 0, 13 } }, ret)
629  end)
630
631  describe('creating a language tree', function()
632    local function get_ranges()
633      return exec_lua(function()
634        local result = {}
635        _G.parser:for_each_tree(function(tree)
636          table.insert(result, { tree:root():range() })
637        end)
638        return result
639      end)
640    end
641
642    before_each(function()
643      insert([[
644        int x = INT_MAX;
645        #define READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
646        #define READ_STRING_OK(x, y) (char *)read_string((x), (size_t)(y))
647        #define VALUE 123
648        #define VALUE1 123
649        #define VALUE2 123
650      ]])
651    end)
652
653    describe('parsing regions independently', function()
654      it('injects a language', function()
655        exec_lua(function()
656          _G.parser = vim.treesitter.get_parser(0, 'c', {
657            injections = {
658              c = (
659                '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c")) '
660                .. '(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))'
661              ),
662            },
663          })
664          _G.parser:parse(true)
665        end)
666
667        eq('table', exec_lua('return type(parser:children().c)'))
668        eq(5, exec_lua('return #parser:children().c:trees()'))
669        eq({
670          { 0, 0, 7, 0 }, -- root tree
671          { 1, 26, 1, 63 }, -- READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
672          { 2, 29, 2, 66 }, -- READ_STRING_OK(x, y) (char *)read_string((x), (size_t)(y))
673          { 3, 14, 3, 17 }, -- VALUE 123
674          { 4, 15, 4, 18 }, -- VALUE1 123
675          { 5, 15, 5, 18 }, -- VALUE2 123
676        }, get_ranges())
677
678        n.feed('ggo<esc>')
679        eq(5, exec_lua('return #parser:children().c:trees()'))
680        eq({
681          { 0, 0, 8, 0 }, -- root tree
682          { 2, 26, 2, 63 }, -- READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
683          { 3, 29, 3, 66 }, -- READ_STRING_OK(x, y) (char *)read_string((x), (size_t)(y))
684          { 4, 14, 4, 17 }, -- VALUE 123
685          { 5, 15, 5, 18 }, -- VALUE1 123
686          { 6, 15, 6, 18 }, -- VALUE2 123
687        }, get_ranges())
688      end)
689
690      it('notifies changedtree callbacks when replacing injection regions', function()
691        exec_lua(function()
692          _G.parser = vim.treesitter._create_parser(0, 'c', {
693            injections = {
694              c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c"))',
695            },
696          })
697          _G.parser:parse(true)
698
699          local child = _G.parser:children().c
700          vim.api.nvim_buf_set_lines(0, 3, 4, false, { '#define VALUE changed' })
701
702          _G.changedtree = 0
703          _G.precise_changedtree = true
704          child:register_cbs({
705            on_changedtree = function(changes, tree)
706              _G.changedtree = _G.changedtree + 1
707              _G.precise_changedtree = _G.precise_changedtree
708                and vim.deep_equal(changes, tree:included_ranges(true))
709            end,
710          })
711
712          _G.parser:parse({ 3, 4 })
713        end)
714
715        eq(true, exec_lua('return _G.changedtree > 0 and _G.precise_changedtree'))
716      end)
717    end)
718
719    describe('when parsing regions combined', function()
720      it('injects a language', function()
721        exec_lua(function()
722          _G.parser = vim.treesitter.get_parser(0, 'c', {
723            injections = {
724              c = (
725                '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c") (#set! injection.combined)) '
726                .. '(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c") (#set! injection.combined))'
727              ),
728            },
729          })
730          _G.parser:parse(true)
731        end)
732
733        eq('table', exec_lua('return type(parser:children().c)'))
734        eq(2, exec_lua('return #parser:children().c:trees()'))
735        eq({
736          { 0, 0, 7, 0 }, -- root tree
737          { 1, 26, 2, 66 }, -- READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
738          -- READ_STRING_OK(x, y) (char *)read_string((x), (size_t)(y))
739          { 3, 14, 5, 18 }, -- VALUE 123
740          -- VALUE1 123
741          -- VALUE2 123
742        }, get_ranges())
743
744        n.feed('ggo<esc>')
745        eq('table', exec_lua('return type(parser:children().c)'))
746        eq(2, exec_lua('return #parser:children().c:trees()'))
747        eq({
748          { 0, 0, 8, 0 }, -- root tree
749          { 2, 26, 3, 66 }, -- READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
750          -- READ_STRING_OK(x, y) (char *)read_string((x), (size_t)(y))
751          -- VALUE 123
752          { 4, 14, 6, 18 }, -- VALUE1 123
753          -- VALUE2 123
754        }, get_ranges())
755
756        n.feed('7ggI//<esc>')
757        exec_lua([[parser:parse(true)]])
758        eq('table', exec_lua('return type(parser:children().c)'))
759        eq(2, exec_lua('return #parser:children().c:trees()'))
760        eq({
761          { 0, 0, 8, 0 }, -- root tree
762          { 2, 26, 3, 66 }, -- READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
763          -- READ_STRING_OK(x, y) (char *)read_string((x), (size_t)(y))
764          -- VALUE 123
765          { 4, 14, 5, 18 }, -- VALUE1 123
766        }, get_ranges())
767      end)
768
769      it('scopes injections appropriately', function()
770        -- `injection.combined` are combined within a TSTree.
771        -- Lua injections on lines 2-4 should be combined within their
772        -- respective C injection trees, and lua injections on lines 0 and 6
773        -- are separate from each other and other lua injections on lines 2-4.
774
775        exec_lua(function()
776          local lines = {
777            [[func('int a = func("local a = [=[");')]],
778            [[]],
779            [[func('int a = func("local a = 6") + func("+ 3");')]],
780            [[func('int a = func("local a = 6") + func("+ 3");')]],
781            [[func('int a = func("local a = 6") + func("+ 3");')]],
782            [[]],
783            [[func('int a = func("]=]");')]],
784          }
785          vim.api.nvim_buf_set_lines(0, 0, -1, true, lines)
786          _G.parser = vim.treesitter.get_parser(0, 'lua', {
787            injections = {
788              lua = [[
789                ((function_call
790                  arguments: (arguments
791                    (string (string_content) @injection.content)))
792                  (#set! injection.language "c"))
793              ]],
794              c = [[
795                ((call_expression
796                  arguments: (argument_list
797                    (string_literal (string_content) @injection.content)))
798                  (#set! injection.combined)
799                  (#set! injection.language "lua"))
800              ]],
801            },
802          })
803
804          function _G.langtree_regions(parser)
805            local result_regions = {}
806
807            local regions = parser:included_regions()
808            for region_i, region in pairs(regions) do
809              local result_region = {}
810
811              for _, range in ipairs(region) do
812                table.insert(result_region, {
813                  range[1],
814                  range[2],
815                  range[4],
816                  range[5],
817                })
818              end
819
820              result_regions[region_i] = result_region
821            end
822
823            return result_regions
824          end
825          function _G.all_regions(parser)
826            local this_regions = _G.langtree_regions(parser)
827            local child_regions = {}
828            for lang, child in pairs(parser:children()) do
829              child_regions[lang] = _G.all_regions(child)
830            end
831            return { regions = this_regions, children = child_regions }
832          end
833        end)
834
835        local expected_regions = {
836          children = {}, -- nothing is parsed
837          regions = {
838            {}, -- root tree's regions is the entire buffer
839          },
840        }
841        eq(expected_regions, exec_lua('return all_regions(_G.parser)'))
842
843        exec_lua('_G.parser:parse({ 3, 0, 3, 45 })')
844
845        expected_regions = {
846          children = {
847            c = {
848              children = {
849                lua = {
850                  children = {},
851                  regions = {
852                    { { 3, 20, 3, 31 }, { 3, 42, 3, 45 } },
853                  },
854                },
855              },
856              regions = {
857                { { 3, 6, 3, 48 } },
858              },
859            },
860          },
861          regions = {
862            {},
863          },
864        }
865        eq(expected_regions, exec_lua('return all_regions(_G.parser)'))
866
867        exec_lua('_G.parser:parse(true)')
868        expected_regions = {
869          children = {
870            c = {
871              children = {
872                lua = {
873                  children = {},
874                  regions = {
875                    { { 0, 20, 0, 33 } },
876                    { { 2, 20, 2, 31 }, { 2, 42, 2, 45 } },
877                    { { 3, 20, 3, 31 }, { 3, 42, 3, 45 } },
878                    { { 4, 20, 4, 31 }, { 4, 42, 4, 45 } },
879                    { { 6, 20, 6, 23 } },
880                  },
881                },
882              },
883              regions = {
884                { { 0, 6, 0, 36 } },
885                { { 2, 6, 2, 48 } },
886                { { 3, 6, 3, 48 } },
887                { { 4, 6, 4, 48 } },
888                { { 6, 6, 6, 26 } },
889              },
890            },
891          },
892          regions = {
893            {},
894          },
895        }
896        eq(expected_regions, exec_lua('return all_regions(_G.parser)'))
897      end)
898    end)
899
900    describe('when using injection.self', function()
901      it('injects the source language', function()
902        exec_lua(function()
903          _G.parser = vim.treesitter.get_parser(0, 'c', {
904            injections = {
905              c = (
906                '(preproc_def (preproc_arg) @injection.content (#set! injection.self)) '
907                .. '(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.self))'
908              ),
909            },
910          })
911          _G.parser:parse(true)
912        end)
913
914        eq('table', exec_lua('return type(parser:children().c)'))
915        eq(5, exec_lua('return #parser:children().c:trees()'))
916        eq({
917          { 0, 0, 7, 0 }, -- root tree
918          { 1, 26, 1, 63 }, -- READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
919          { 2, 29, 2, 66 }, -- READ_STRING_OK(x, y) (char *)read_string((x), (size_t)(y))
920          { 3, 14, 3, 17 }, -- VALUE 123
921          { 4, 15, 4, 18 }, -- VALUE1 123
922          { 5, 15, 5, 18 }, -- VALUE2 123
923        }, get_ranges())
924
925        n.feed('ggo<esc>')
926        eq(5, exec_lua('return #parser:children().c:trees()'))
927        eq({
928          { 0, 0, 8, 0 }, -- root tree
929          { 2, 26, 2, 63 }, -- READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
930          { 3, 29, 3, 66 }, -- READ_STRING_OK(x, y) (char *)read_string((x), (size_t)(y))
931          { 4, 14, 4, 17 }, -- VALUE 123
932          { 5, 15, 5, 18 }, -- VALUE1 123
933          { 6, 15, 6, 18 }, -- VALUE2 123
934        }, get_ranges())
935      end)
936    end)
937
938    describe('when using the offset directive', function()
939      it('shifts the range by the directive amount', function()
940        exec_lua(function()
941          _G.parser = vim.treesitter.get_parser(0, 'c', {
942            injections = {
943              c = (
944                '(preproc_def ((preproc_arg) @injection.content (#set! injection.language "c") (#offset! @injection.content 0 2 0 -1))) '
945                .. '(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))'
946              ),
947            },
948          })
949          _G.parser:parse(true)
950        end)
951
952        eq('table', exec_lua('return type(parser:children().c)'))
953        eq({
954          { 0, 0, 7, 0 }, -- root tree
955          { 1, 26, 1, 63 }, -- READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
956          { 2, 29, 2, 66 }, -- READ_STRING_OK(x, y) (char *)read_string((x), (size_t)(y))
957          { 3, 16, 3, 16 }, -- VALUE 123
958          { 4, 17, 4, 17 }, -- VALUE1 123
959          { 5, 17, 5, 17 }, -- VALUE2 123
960        }, get_ranges())
961      end)
962      it('applies offsets to quantified captures', function()
963        local function get_ltree_ranges()
964          return exec_lua(function()
965            local result = {}
966            _G.parser:for_each_tree(function(_, ltree)
967              table.insert(result, ltree:included_regions())
968            end)
969            return result
970          end)
971        end
972
973        exec_lua(function()
974          _G.parser = vim.treesitter.get_parser(0, 'c', {
975            injections = {
976              c = '((preproc_def (preproc_arg) @injection.content)+ (#set! injection.language "c") (#offset! @injection.content 0 1 0 -1))',
977            },
978          })
979          _G.parser:parse(true)
980        end)
981
982        eq('table', exec_lua('return type(parser:children().c)'))
983        eq({
984          { {} }, -- root tree
985          {
986            {
987              { 3, 15, 163, 3, 16, 164 }, -- VALUE 123
988              { 4, 16, 182, 4, 17, 183 }, -- VALUE1 123
989              { 5, 16, 201, 5, 17, 202 }, -- VALUE2 123
990            },
991          },
992        }, get_ltree_ranges())
993      end)
994      it('lists all directives', function()
995        local res_list = exec_lua(function()
996          local query = vim.treesitter.query
997
998          local list = query.list_directives()
999
1000          table.sort(list)
1001
1002          return list
1003        end)
1004
1005        eq({ 'gsub!', 'offset!', 'set!', 'trim!' }, res_list)
1006      end)
1007    end)
1008
1009    it('normalizes hyphens to underscores in injection.language', function()
1010      exec_lua(function()
1011        -- register "c" as the parser for "shell_session" (normalized form of "shell-session")
1012        vim.treesitter.language.register('c', 'shell_session')
1013        _G.parser = vim.treesitter.get_parser(0, 'c', {
1014          injections = {
1015            c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "shell-session"))',
1016          },
1017        })
1018        _G.parser:parse(true)
1019      end)
1020
1021      -- injection.language "shell-session" should normalize to "shell_session",
1022      -- which resolves via the registered alias to the "c" parser
1023      eq('table', exec_lua('return type(parser:children().c)'))
1024    end)
1025  end)
1026
1027  it('clips nested injections #34098', function()
1028    insert([=[
1029      ```lua
1030      vim.cmd([[
1031      set noswapfile
1032      set noswapfile
1033      set noswapfile
1034      ]])
1035      ```
1036    ]=])
1037
1038    local result = exec_lua(function()
1039      local parser = vim.treesitter.get_parser(0, 'markdown')
1040      parser:parse(true)
1041
1042      return parser._children.lua._children.vim:included_regions()
1043    end)
1044
1045    local expected = {
1046      {
1047        { 1, 10, 17, 2, 0, 18 },
1048        { 2, 0, 18, 3, 0, 33 },
1049        { 3, 0, 33, 4, 0, 48 },
1050        { 4, 0, 48, 5, 0, 63 },
1051      },
1052    }
1053    eq(expected, result)
1054  end)
1055
1056  describe('when getting the language for a range', function()
1057    before_each(function()
1058      insert([[
1059        int x = INT_MAX;
1060        #define VALUE 123456789
1061      ]])
1062    end)
1063
1064    it('returns the correct language tree', function()
1065      local result = exec_lua(function()
1066        local parser = vim.treesitter.get_parser(0, 'c', {
1067          injections = {
1068            c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c"))',
1069          },
1070        })
1071        parser:parse(true)
1072
1073        local sub_tree = parser:language_for_range({ 1, 18, 1, 19 })
1074
1075        return sub_tree == parser:children().c
1076      end)
1077
1078      eq(true, result)
1079    end)
1080  end)
1081
1082  describe('when setting the node for an injection', function()
1083    before_each(function()
1084      insert([[
1085        print()
1086      ]])
1087    end)
1088
1089    it('ignores optional captures #23100', function()
1090      local result = exec_lua(function()
1091        local parser = vim.treesitter.get_parser(0, 'lua', {
1092          injections = {
1093            lua = (
1094              '(function_call '
1095              .. '(arguments '
1096              .. '(string)? @injection.content '
1097              .. '(number)? @injection.content '
1098              .. '(#offset! @injection.content 0 1 0 -1) '
1099              .. '(#set! injection.language "c")))'
1100            ),
1101          },
1102        })
1103        parser:parse(true)
1104
1105        return parser:is_valid()
1106      end)
1107
1108      eq(true, result)
1109    end)
1110  end)
1111
1112  describe('when getting/setting match data', function()
1113    describe('when setting for the whole match', function()
1114      it('sets/gets the data correctly', function()
1115        insert([[
1116          int x = 3;
1117        ]])
1118
1119        local result = exec_lua(function()
1120          local query =
1121            vim.treesitter.query.parse('c', '((number_literal) @number (#set! "key" "value"))')
1122          local parser = vim.treesitter.get_parser(0, 'c')
1123
1124          local _, _, metadata = query:iter_matches(parser:parse()[1]:root(), 0, 0, -1)()
1125          return metadata.key
1126        end)
1127
1128        eq('value', result)
1129      end)
1130
1131      describe('when setting a key on a capture', function()
1132        it('creates the nested table', function()
1133          insert([[
1134            int x = 3;
1135          ]])
1136
1137          local result = exec_lua(function()
1138            local query = vim.treesitter.query.parse(
1139              'c',
1140              '((number_literal) @number (#set! @number "key" "value"))'
1141            )
1142            local parser = vim.treesitter.get_parser(0, 'c')
1143
1144            local _, _, metadata = query:iter_matches(parser:parse()[1]:root(), 0, 0, -1)()
1145            local _, nested_tbl = next(metadata)
1146            return nested_tbl.key
1147          end)
1148
1149          eq('value', result)
1150        end)
1151
1152        it('does not overwrite the nested table', function()
1153          insert([[
1154            int x = 3;
1155          ]])
1156
1157          local result = exec_lua(function()
1158            local query = vim.treesitter.query.parse(
1159              'c',
1160              '((number_literal) @number (#set! @number "key" "value") (#set! @number "key2" "value2"))'
1161            )
1162            local parser = vim.treesitter.get_parser(0, 'c')
1163
1164            local _, _, metadata = query:iter_matches(parser:parse()[1]:root(), 0, 0, -1)()
1165            local _, nested_tbl = next(metadata)
1166            return nested_tbl
1167          end)
1168          local expected = {
1169            ['key'] = 'value',
1170            ['key2'] = 'value2',
1171          }
1172
1173          eq(expected, result)
1174        end)
1175      end)
1176    end)
1177  end)
1178
1179  describe('trim! directive', function()
1180    it('can trim all whitespace', function()
1181      exec_lua(function()
1182        local lines = {
1183          '        print([[',
1184          '',
1185          '            f',
1186          '     helllo',
1187          '  there',
1188          '  asdf',
1189          '  asdfassd   ',
1190          '',
1191          '',
1192          '',
1193          '  ]])',
1194          '  print([[',
1195          '        ',
1196          '        ',
1197          '        ',
1198          '  ]])',
1199          '',
1200          '  print([[]])',
1201          '',
1202          '  print([[',
1203          '  ]])',
1204          '',
1205          '  print([[     hello 😃    ]])',
1206        }
1207        vim.api.nvim_buf_set_lines(0, 0, -1, true, lines)
1208      end)
1209      exec_lua(function()
1210        vim.treesitter.start(0, 'lua')
1211      end)
1212
1213      local query_text = [[
1214       ; query
1215        ((string_content) @str)
1216      ]]
1217      eq({
1218        { 'str', { 0, 16, 10, 2 } },
1219        { 'str', { 11, 10, 15, 2 } },
1220        { 'str', { 17, 10, 17, 10 } },
1221        { 'str', { 19, 10, 20, 2 } },
1222        { 'str', { 22, 10, 22, 29 } },
1223      }, run_query('lua', query_text))
1224
1225      local trim_query_text = [[
1226        ; query
1227        ((string_content) @str
1228          (#trim! @str 1 1 1 1))
1229      ]]
1230
1231      eq({
1232        { 'str', { 2, 12, 6, 10 } },
1233        { 'str', { 11, 10, 11, 10 } },
1234        { 'str', { 17, 10, 17, 10 } },
1235        { 'str', { 19, 10, 19, 10 } },
1236        { 'str', { 22, 15, 22, 25 } },
1237      }, run_query('lua', trim_query_text))
1238    end)
1239
1240    it('trims only empty lines by default (backwards compatible)', function()
1241      insert(dedent [[
1242      ## Heading
1243
1244      With some text
1245
1246      ## And another
1247
1248      With some more here]])
1249
1250      local query_text = [[
1251        ; query
1252        ((section) @fold
1253          (#trim! @fold))
1254      ]]
1255
1256      exec_lua(function()
1257        vim.treesitter.start(0, 'markdown')
1258      end)
1259
1260      eq({
1261        { 'fold', { 0, 0, 2, 14 } },
1262        { 'fold', { 4, 0, 6, 19 } },
1263      }, run_query('markdown', query_text))
1264    end)
1265
1266    it('can trim lines', function()
1267      insert(dedent [[
1268      - Fold list
1269        - Fold list
1270          - Fold list
1271          - Fold list
1272        - Fold list
1273      - Fold list
1274      ]])
1275
1276      local query_text = [[
1277        ; query
1278        ((list_item
1279          (list)) @fold
1280          (#trim! @fold 1 1 1 1))
1281      ]]
1282
1283      exec_lua(function()
1284        vim.treesitter.start(0, 'markdown')
1285      end)
1286
1287      eq({
1288        { 'fold', { 0, 0, 4, 13 } },
1289        { 'fold', { 1, 2, 3, 15 } },
1290      }, run_query('markdown', query_text))
1291    end)
1292  end)
1293
1294  it('tracks the root range properly (#22911)', function()
1295    insert([[
1296      int main() {
1297        int x = 3;
1298      }]])
1299
1300    local query0 = [[
1301      (declaration) @declaration
1302      (function_definition) @function
1303    ]]
1304
1305    exec_lua(function()
1306      vim.treesitter.start(0, 'c')
1307    end)
1308
1309    eq({
1310      { 'function', { 0, 0, 2, 1 } },
1311      { 'declaration', { 1, 2, 1, 12 } },
1312    }, run_query('c', query0))
1313
1314    n.command 'normal ggO'
1315    insert('int a;')
1316
1317    eq({
1318      { 'declaration', { 0, 0, 0, 6 } },
1319      { 'function', { 1, 0, 3, 1 } },
1320      { 'declaration', { 2, 2, 2, 12 } },
1321    }, run_query('c', query0))
1322  end)
1323
1324  it('handles ranges when source is a multiline string (#20419)', function()
1325    local source = [==[
1326      vim.cmd[[
1327        set number
1328        set cmdheight=2
1329        set lastsatus=2
1330      ]]
1331
1332      set query = [[;; query
1333        ((function_call
1334          name: [
1335            (identifier) @_cdef_identifier
1336            (_ _ (identifier) @_cdef_identifier)
1337          ]
1338          arguments: (arguments (string content: _ @injection.content)))
1339          (#set! injection.language "c")
1340          (#eq? @_cdef_identifier "cdef"))
1341      ]]
1342    ]==]
1343
1344    local r = exec_lua(function()
1345      local parser = vim.treesitter.get_string_parser(source, 'lua')
1346      parser:parse(true)
1347      local ranges = {}
1348      parser:for_each_tree(function(tstree, tree)
1349        ranges[tree:lang()] = { tstree:root():range(true) }
1350      end)
1351      return ranges
1352    end)
1353
1354    eq({
1355      lua = { 0, 6, 6, 16, 4, 438 },
1356      query = { 6, 20, 113, 15, 6, 431 },
1357      vim = { 1, 0, 16, 4, 6, 89 },
1358    }, r)
1359
1360    -- The above ranges are provided directly from treesitter, however query directives may mutate
1361    -- the ranges but only provide a Range4. Strip the byte entries from the ranges and make sure
1362    -- add_bytes() produces the same result.
1363
1364    local rb = exec_lua(function()
1365      local add_bytes = require('vim.treesitter._range').add_bytes
1366      for lang, range in pairs(r) do
1367        r[lang] = { range[1], range[2], range[4], range[5] }
1368        r[lang] = add_bytes(source, r[lang])
1369      end
1370      return r
1371    end)
1372
1373    eq(rb, r)
1374  end)
1375
1376  it('does not produce empty injection ranges (#23409)', function()
1377    insert [[
1378      Examples: >lua
1379        local a = {}
1380<
1381    ]]
1382
1383    -- This is not a valid injection since (code) has children and include-children is not set
1384    exec_lua(function()
1385      _G.parser1 = require('vim.treesitter.languagetree').new(0, 'vimdoc', {
1386        injections = {
1387          vimdoc = '((codeblock (language) @injection.language (code) @injection.content))',
1388        },
1389      })
1390      _G.parser1:parse(true)
1391    end)
1392
1393    eq(0, exec_lua('return #vim.tbl_keys(parser1:children())'))
1394
1395    exec_lua(function()
1396      _G.parser2 = require('vim.treesitter.languagetree').new(0, 'vimdoc', {
1397        injections = {
1398          vimdoc = '((codeblock (language) @injection.language (code) @injection.content) (#set! injection.include-children))',
1399        },
1400      })
1401      _G.parser2:parse(true)
1402    end)
1403
1404    eq(1, exec_lua('return #vim.tbl_keys(parser2:children())'))
1405    eq({ { { 1, 0, 21, 2, 0, 42 } } }, exec_lua('return parser2:children().lua:included_regions()'))
1406  end)
1407
1408  it('parses injections incrementally', function()
1409    insert(dedent [[
1410      >lua
1411        local a = {}
1412      <
1413
1414      >lua
1415        local b = {}
1416      <
1417
1418      >lua
1419        local c = {}
1420      <
1421
1422      >lua
1423        local d = {}
1424      <
1425
1426      >lua
1427        local e = {}
1428      <
1429
1430      >lua
1431        local f = {}
1432      <
1433
1434      >lua
1435        local g = {}
1436      <
1437    ]])
1438
1439    exec_lua(function()
1440      _G.parser = require('vim.treesitter.languagetree').new(0, 'vimdoc', {
1441        injections = {
1442          vimdoc = '((codeblock (language) @injection.language (code) @injection.content) (#set! injection.include-children))',
1443        },
1444      })
1445    end)
1446
1447    --- Do not parse injections by default
1448    eq(
1449      0,
1450      exec_lua(function()
1451        _G.parser:parse()
1452        return #vim.tbl_keys(_G.parser:children())
1453      end)
1454    )
1455
1456    --- Only parse injections between lines 0, 2
1457    eq(
1458      1,
1459      exec_lua(function()
1460        _G.parser:parse({ 0, 2 })
1461        return #_G.parser:children().lua:trees()
1462      end)
1463    )
1464
1465    eq(
1466      1,
1467      exec_lua(function()
1468        _G.parser:parse({ 2, 6 })
1469        return #_G.parser:children().lua:trees()
1470      end)
1471    )
1472
1473    eq(
1474      7,
1475      exec_lua(function()
1476        _G.parser:parse(true)
1477        return #_G.parser:children().lua:trees()
1478      end)
1479    )
1480  end)
1481
1482  describe('languagetree is_valid()', function()
1483    before_each(function()
1484      insert(dedent [[
1485        Treesitter integration                                 *treesitter*
1486
1487        Nvim integrates the `tree-sitter` library for incremental parsing of buffers:
1488        https://tree-sitter.github.io/tree-sitter/
1489
1490      ]])
1491
1492      feed(':set ft=help<cr>')
1493
1494      exec_lua(function()
1495        vim.treesitter
1496          .get_parser(0, 'vimdoc', {
1497            injections = {
1498              vimdoc = '((codeblock (language) @injection.language (code) @injection.content) (#set! injection.include-children))',
1499            },
1500          })
1501          :parse()
1502      end)
1503    end)
1504
1505    it('is valid excluding, invalid including children initially', function()
1506      eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1507      eq(false, exec_lua('return vim.treesitter.get_parser():is_valid()'))
1508    end)
1509
1510    it('is fully valid after a full parse', function()
1511      exec_lua('vim.treesitter.get_parser():parse(true)')
1512      eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1513      eq(true, exec_lua('return vim.treesitter.get_parser():is_valid()'))
1514    end)
1515
1516    it('is valid within a range on parsed tree after parsing it', function()
1517      exec_lua('vim.treesitter.get_parser():parse({5, 7})')
1518      eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1519      eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(nil, {5, 7})'))
1520    end)
1521
1522    describe('when adding content with injections', function()
1523      before_each(function()
1524        feed('G')
1525        insert(dedent [[
1526          >lua
1527            local a = {}
1528          <
1529
1530        ]])
1531      end)
1532
1533      it('is fully invalid after changes', function()
1534        eq(false, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1535        eq(false, exec_lua('return vim.treesitter.get_parser():is_valid()'))
1536      end)
1537
1538      it('is valid excluding, invalid including children after a rangeless parse', function()
1539        exec_lua('vim.treesitter.get_parser():parse()')
1540        eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1541        eq(false, exec_lua('return vim.treesitter.get_parser():is_valid()'))
1542      end)
1543
1544      it('is valid within a range on parsed tree after parsing it', function()
1545        exec_lua('vim.treesitter.get_parser():parse({5, 7})')
1546        eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1547        eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(nil, {5, 7})'))
1548      end)
1549
1550      it(
1551        'is valid excluding, invalid including children after a range parse that does not lead to parsing non-parsed injections',
1552        function()
1553          exec_lua('vim.treesitter.get_parser():parse({2, 4})')
1554          eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1555          eq(false, exec_lua('return vim.treesitter.get_parser():is_valid()'))
1556        end
1557      )
1558    end)
1559
1560    describe('when removing content with injections', function()
1561      before_each(function()
1562        feed('G')
1563        insert(dedent [[
1564          >lua
1565            local a = {}
1566          <
1567
1568          >lua
1569            local a = {}
1570          <
1571
1572        ]])
1573
1574        exec_lua('vim.treesitter.get_parser():parse(true)')
1575
1576        feed('Gd3k')
1577      end)
1578
1579      it('is fully invalid after changes', function()
1580        eq(false, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1581        eq(false, exec_lua('return vim.treesitter.get_parser():is_valid()'))
1582      end)
1583
1584      it('is valid excluding, invalid including children after a rangeless parse', function()
1585        exec_lua('vim.treesitter.get_parser():parse()')
1586        eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1587        eq(false, exec_lua('return vim.treesitter.get_parser():is_valid()'))
1588      end)
1589
1590      it('is valid within a range parse that leads to parsing modified child tree', function()
1591        exec_lua('vim.treesitter.get_parser():parse({5, 7})')
1592        eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1593        eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(nil, {5, 7})'))
1594      end)
1595
1596      it(
1597        'is valid excluding, invalid including children after a range parse that does not lead to parsing modified child tree',
1598        function()
1599          exec_lua('vim.treesitter.get_parser():parse({2, 4})')
1600          eq(true, exec_lua('return vim.treesitter.get_parser():is_valid(true)'))
1601          eq(false, exec_lua('return vim.treesitter.get_parser():is_valid()'))
1602        end
1603      )
1604    end)
1605  end)
1606end)