test: allow exec_lua to handle functions

Problem:

Tests have lots of exec_lua calls which input blocks of code
provided as unformatted strings.

Solution:

Teach exec_lua how to handle functions.
This commit is contained in:
Lewis Russell
2024-07-29 11:20:15 +01:00
committed by Lewis Russell
parent f32557ca67
commit 7d24c4d6b0
16 changed files with 4122 additions and 3891 deletions

View File

@@ -145,10 +145,10 @@ describe('luaeval(vim.api.…)', function()
eq(true, fn.luaeval('vim.api.nvim__id(vim.api.nvim__id)(true)'))
eq(
42,
exec_lua [[
local f = vim.api.nvim__id({42, vim.api.nvim__id})
return f[2](f[1])
]]
exec_lua(function()
local f = vim.api.nvim__id({ 42, vim.api.nvim__id })
return f[2](f[1])
end)
)
end)

View File

@@ -27,30 +27,35 @@ local origlines = {
before_each(function()
clear()
exec_lua [[
local evname = ...
exec_lua(function()
local events = {}
function test_register(bufnr, evname, id, changedtick, utf_sizes, preview)
function _G.test_register(bufnr, evname, id, changedtick, utf_sizes, preview)
local function callback(...)
table.insert(events, {id, ...})
if test_unreg == id then
table.insert(events, { id, ... })
if _G.test_unreg == id then
return true
end
end
local opts = {[evname]=callback, on_detach=callback, on_reload=callback, utf_sizes=utf_sizes, preview=preview}
local opts = {
[evname] = callback,
on_detach = callback,
on_reload = callback,
utf_sizes = utf_sizes,
preview = preview,
}
if changedtick then
opts.on_changedtick = callback
end
vim.api.nvim_buf_attach(bufnr, false, opts)
end
function get_events()
function _G.get_events()
local ret_events = events
events = {}
return ret_events
end
]]
end)
end)
describe('lua buffer event callbacks: on_lines', function()
@@ -257,13 +262,13 @@ describe('lua buffer event callbacks: on_lines', function()
it('has valid cursor position while shifting', function()
api.nvim_buf_set_lines(0, 0, -1, true, { 'line1' })
exec_lua([[
exec_lua(function()
vim.api.nvim_buf_attach(0, false, {
on_lines = function()
vim.api.nvim_set_var('listener_cursor_line', vim.api.nvim_win_get_cursor(0)[1])
end,
})
]])
end)
feed('>>')
eq(1, api.nvim_get_var('listener_cursor_line'))
end)
@@ -302,13 +307,13 @@ describe('lua buffer event callbacks: on_lines', function()
it('#12718 lnume', function()
api.nvim_buf_set_lines(0, 0, -1, true, { '1', '2', '3' })
exec_lua([[
exec_lua(function()
vim.api.nvim_buf_attach(0, false, {
on_lines = function(...)
vim.api.nvim_set_var('linesev', { ... })
end,
})
]])
end)
feed('1G0')
feed('y<C-v>2j')
feed('G0')
@@ -326,13 +331,13 @@ describe('lua buffer event callbacks: on_lines', function()
end)
it('nvim_buf_call() from callback does not cause wrong Normal mode CTRL-A #16729', function()
exec_lua([[
exec_lua(function()
vim.api.nvim_buf_attach(0, false, {
on_lines = function(...)
on_lines = function()
vim.api.nvim_buf_call(0, function() end)
end,
})
]])
end)
feed('itest123<Esc><C-A>')
eq('test124', api.nvim_get_current_line())
end)
@@ -342,19 +347,19 @@ describe('lua buffer event callbacks: on_lines', function()
screen:attach()
api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa', 'bbb', 'ccc' })
exec_lua([[
exec_lua(function()
local ns = vim.api.nvim_create_namespace('')
vim.api.nvim_buf_attach(0, false, {
on_lines = function(_, _, _, row, _, end_row)
vim.api.nvim_buf_clear_namespace(0, ns, row, end_row)
for i = row, end_row - 1 do
local id = vim.api.nvim_buf_set_extmark(0, ns, i, 0, {
virt_text = {{ 'NEW' .. tostring(i), 'WarningMsg' }},
vim.api.nvim_buf_set_extmark(0, ns, i, 0, {
virt_text = { { 'NEW' .. tostring(i), 'WarningMsg' } },
})
end
end,
})
]])
end)
feed('o')
screen:expect({
@@ -383,7 +388,7 @@ describe('lua buffer event callbacks: on_lines', function()
it('line lengths are correct when pressing TAB with folding #29119', function()
api.nvim_buf_set_lines(0, 0, -1, true, { 'a', 'b' })
exec_lua([[
exec_lua(function()
_G.res = {}
vim.o.foldmethod = 'indent'
vim.o.softtabstop = -1
@@ -391,9 +396,9 @@ describe('lua buffer event callbacks: on_lines', function()
on_lines = function(_, bufnr, _, row, _, end_row)
local lines = vim.api.nvim_buf_get_lines(bufnr, row, end_row, true)
table.insert(_G.res, lines)
end
end,
})
]])
end)
feed('i<Tab>')
eq({ '\ta' }, exec_lua('return _G.res[#_G.res]'))

View File

@@ -178,13 +178,15 @@ describe(':lua', function()
eq('hello', exec_capture(':lua = x()'))
exec_lua('x = {a = 1, b = 2}')
eq('{\n a = 1,\n b = 2\n}', exec_capture(':lua =x'))
exec_lua([[function x(success)
if success then
return true, "Return value"
else
return false, nil, "Error message"
exec_lua(function()
function _G.x(success)
if success then
return true, 'Return value'
else
return false, nil, 'Error message'
end
end
end]])
end)
eq(
dedent [[
true

File diff suppressed because it is too large Load Diff

View File

@@ -18,90 +18,82 @@ describe('vim.filetype', function()
before_each(function()
clear()
exec_lua [[
exec_lua(function()
local bufnr = vim.api.nvim_create_buf(true, false)
vim.api.nvim_set_current_buf(bufnr)
]]
end)
end)
it('works with extensions', function()
eq(
'radicalscript',
exec_lua [[
vim.filetype.add({
extension = {
rs = 'radicalscript',
},
})
return vim.filetype.match({ filename = 'main.rs' })
]]
exec_lua(function()
vim.filetype.add({
extension = {
rs = 'radicalscript',
},
})
return vim.filetype.match({ filename = 'main.rs' })
end)
)
end)
it('prioritizes filenames over extensions', function()
eq(
'somethingelse',
exec_lua [[
vim.filetype.add({
extension = {
rs = 'radicalscript',
},
filename = {
['main.rs'] = 'somethingelse',
},
})
return vim.filetype.match({ filename = 'main.rs' })
]]
exec_lua(function()
vim.filetype.add({
extension = {
rs = 'radicalscript',
},
filename = {
['main.rs'] = 'somethingelse',
},
})
return vim.filetype.match({ filename = 'main.rs' })
end)
)
end)
it('works with filenames', function()
eq(
'nim',
exec_lua [[
vim.filetype.add({
filename = {
['s_O_m_e_F_i_l_e'] = 'nim',
},
})
return vim.filetype.match({ filename = 's_O_m_e_F_i_l_e' })
]]
exec_lua(function()
vim.filetype.add({
filename = {
['s_O_m_e_F_i_l_e'] = 'nim',
},
})
return vim.filetype.match({ filename = 's_O_m_e_F_i_l_e' })
end)
)
eq(
'dosini',
exec_lua(
[[
local root = ...
vim.filetype.add({
filename = {
['config'] = 'toml',
[root .. '/.config/fun/config'] = 'dosini',
},
})
return vim.filetype.match({ filename = root .. '/.config/fun/config' })
]],
root
)
exec_lua(function(root0)
vim.filetype.add({
filename = {
['config'] = 'toml',
[root0 .. '/.config/fun/config'] = 'dosini',
},
})
return vim.filetype.match({ filename = root0 .. '/.config/fun/config' })
end, root)
)
end)
it('works with patterns', function()
eq(
'markdown',
exec_lua(
[[
local root = ...
vim.env.HOME = '/a-funky+home%dir'
vim.filetype.add({
pattern = {
['~/blog/.*%.txt'] = 'markdown',
}
})
return vim.filetype.match({ filename = '~/blog/why_neovim_is_awesome.txt' })
]],
root
)
exec_lua(function()
vim.env.HOME = '/a-funky+home%dir'
vim.filetype.add({
pattern = {
['~/blog/.*%.txt'] = 'markdown',
},
})
return vim.filetype.match({ filename = '~/blog/why_neovim_is_awesome.txt' })
end)
)
end)
@@ -110,43 +102,43 @@ describe('vim.filetype', function()
command('file relevant_to_me')
eq(
'foss',
exec_lua [[
vim.filetype.add({
pattern = {
["relevant_to_(%a+)"] = function(path, bufnr, capture)
if capture == "me" then
return "foss"
end
end,
}
})
return vim.filetype.match({ buf = 0 })
]]
exec_lua(function()
vim.filetype.add({
pattern = {
['relevant_to_(%a+)'] = function(_, _, capture)
if capture == 'me' then
return 'foss'
end
end,
},
})
return vim.filetype.match({ buf = 0 })
end)
)
end)
it('works with contents #22180', function()
eq(
'sh',
exec_lua [[
-- Needs to be set so detect#sh doesn't fail
vim.g.ft_ignore_pat = '\\.\\(Z\\|gz\\|bz2\\|zip\\|tgz\\)$'
return vim.filetype.match({ contents = { '#!/usr/bin/env bash' } })
]]
exec_lua(function()
-- Needs to be set so detect#sh doesn't fail
vim.g.ft_ignore_pat = '\\.\\(Z\\|gz\\|bz2\\|zip\\|tgz\\)$'
return vim.filetype.match({ contents = { '#!/usr/bin/env bash' } })
end)
)
end)
it('considers extension mappings when matching from hashbang', function()
eq(
'fooscript',
exec_lua [[
vim.filetype.add({
extension = {
foo = 'fooscript',
}
})
return vim.filetype.match({ contents = { '#!/usr/bin/env foo' } })
]]
exec_lua(function()
vim.filetype.add({
extension = {
foo = 'fooscript',
},
})
return vim.filetype.match({ contents = { '#!/usr/bin/env foo' } })
end)
)
end)

View File

@@ -141,19 +141,14 @@ describe('vim.fs', function()
it('works', function()
eq(
true,
exec_lua(
[[
local dir, nvim = ...
for name, type in vim.fs.dir(dir) do
if name == nvim and type == 'file' then
return true
exec_lua(function(dir, nvim)
for name, type in vim.fs.dir(dir) do
if name == nvim and type == 'file' then
return true
end
end
end
return false
]],
nvim_dir,
nvim_prog_basename
)
return false
end, nvim_dir, nvim_prog_basename)
)
end)
@@ -172,27 +167,21 @@ describe('vim.fs', function()
io.open('testd/a/b/c/c4', 'w'):close()
local function run(dir, depth, skip)
local r = exec_lua(
[[
local dir, depth, skip = ...
local r = exec_lua(function(dir0, depth0, skip0)
local r = {}
local skip_f
if skip then
skip_f = function(n)
if vim.tbl_contains(skip or {}, n) then
if skip0 then
skip_f = function(n0)
if vim.tbl_contains(skip0 or {}, n0) then
return false
end
end
end
for name, type_ in vim.fs.dir(dir, { depth = depth, skip = skip_f }) do
for name, type_ in vim.fs.dir(dir0, { depth = depth0, skip = skip_f }) do
r[name] = type_
end
return r
]],
dir,
depth,
skip
)
end, dir, depth, skip)
return r
end
@@ -263,13 +252,9 @@ describe('vim.fs', function()
opts = { path = test_source_path .. '/contrib', limit = math.huge }
eq(
exec_lua(
[[
local dir = ...
return vim.tbl_map(vim.fs.basename, vim.fn.glob(dir..'/contrib/*', false, true))
]],
test_source_path
),
exec_lua(function(dir)
return vim.tbl_map(vim.fs.basename, vim.fn.glob(dir .. '/contrib/*', false, true))
end, test_source_path),
vim.tbl_map(
vim.fs.basename,
vim.fs.find(function(_, d)
@@ -299,11 +284,11 @@ describe('vim.fs', function()
it('works with a function', function()
---@type string
local result = exec_lua([[
return vim.fs.root(0, function(name, path)
local result = exec_lua(function()
return vim.fs.root(0, function(name, _)
return name:match('%.txt$')
end)
]])
end)
eq(vim.fs.joinpath(test_source_path, 'test/functional/fixtures'), result)
end)
@@ -352,13 +337,10 @@ describe('vim.fs', function()
local xdg_config_home = test_build_dir .. '/.config'
eq(
xdg_config_home .. '/nvim',
exec_lua(
[[
vim.env.XDG_CONFIG_HOME = ...
return vim.fs.normalize('$XDG_CONFIG_HOME/nvim')
]],
xdg_config_home
)
exec_lua(function(...)
vim.env.XDG_CONFIG_HOME = ...
return vim.fs.normalize('$XDG_CONFIG_HOME/nvim')
end, xdg_config_home)
)
end)

View File

@@ -9,14 +9,9 @@ describe('glob', function()
after_each(n.clear)
local match = function(...)
return exec_lua(
[[
local pattern = select(1, ...)
local str = select(2, ...)
return require("vim.glob").to_lpeg(pattern):match(str) ~= nil
]],
...
)
return exec_lua(function(pattern, str)
return require('vim.glob').to_lpeg(pattern):match(str) ~= nil
end, ...)
end
describe('glob matching', function()

File diff suppressed because it is too large Load Diff

View File

@@ -48,13 +48,13 @@ void ui_refresh(void)
end
local function get_fold_levels()
return exec_lua([[
local res = {}
for i = 1, vim.api.nvim_buf_line_count(0) do
res[i] = vim.treesitter.foldexpr(i)
end
return res
]])
return exec_lua(function()
local res = {}
for i = 1, vim.api.nvim_buf_line_count(0) do
res[i] = vim.treesitter.foldexpr(i)
end
return res
end)
end
it('can compute fold levels', function()
@@ -246,9 +246,13 @@ function f()
end
-- comment]])
exec_lua(
[[vim.treesitter.query.set('lua', 'folds', '[(function_declaration) (parameters) (arguments)] @fold')]]
)
exec_lua(function()
vim.treesitter.query.set(
'lua',
'folds',
'[(function_declaration) (parameters) (arguments)] @fold'
)
end)
parse('lua')
eq({
@@ -290,9 +294,13 @@ function f()
)
end]])
exec_lua(
[[vim.treesitter.query.set('lua', 'folds', '[(function_declaration) (function_definition) (parameters) (arguments)] @fold')]]
)
exec_lua(function()
vim.treesitter.query.set(
'lua',
'folds',
'[(function_declaration) (function_definition) (parameters) (arguments)] @fold'
)
end)
parse('lua')
-- If fold1.stop = fold2.start, then move fold1's stop up so that fold2.start gets proper level.
@@ -333,9 +341,13 @@ function f(a)
end
end]])
exec_lua(
[[vim.treesitter.query.set('lua', 'folds', '[(if_statement) (function_declaration) (parameters) (arguments) (table_constructor)] @fold')]]
)
exec_lua(function()
vim.treesitter.query.set(
'lua',
'folds',
'[(if_statement) (function_declaration) (parameters) (arguments) (table_constructor)] @fold'
)
end)
parse('lua')
eq({

View File

@@ -156,7 +156,7 @@ local injection_grid_expected_c = [[
]]
describe('treesitter highlighting (C)', function()
local screen
local screen --- @type test.functional.ui.screen
before_each(function()
clear()
@@ -176,7 +176,6 @@ describe('treesitter highlighting (C)', function()
[11] = { foreground = Screen.colors.Cyan4 },
}
exec_lua([[ hl_query = ... ]], hl_query_c)
command [[ hi link @error ErrorMsg ]]
command [[ hi link @warning WarningMsg ]]
end)
@@ -188,22 +187,28 @@ describe('treesitter highlighting (C)', function()
-- legacy syntax highlighting is used by default
screen:expect(hl_grid_legacy_c)
exec_lua([[
exec_lua(function(hl_query)
vim.treesitter.query.set('c', 'highlights', hl_query)
vim.treesitter.start()
]])
end, hl_query_c)
-- treesitter highlighting is used
screen:expect(hl_grid_ts_c)
exec_lua('vim.treesitter.stop()')
exec_lua(function()
vim.treesitter.stop()
end)
-- legacy syntax highlighting is used
screen:expect(hl_grid_legacy_c)
exec_lua('vim.treesitter.start()')
exec_lua(function()
vim.treesitter.start()
end)
-- treesitter highlighting is used
screen:expect(hl_grid_ts_c)
exec_lua('vim.treesitter.stop()')
exec_lua(function()
vim.treesitter.stop()
end)
-- legacy syntax highlighting is used
screen:expect(hl_grid_legacy_c)
end)
@@ -233,11 +238,11 @@ describe('treesitter highlighting (C)', function()
]],
}
exec_lua [[
local parser = vim.treesitter.get_parser(0, "c")
exec_lua(function(hl_query)
local parser = vim.treesitter.get_parser(0, 'c')
local highlighter = vim.treesitter.highlighter
test_hl = highlighter.new(parser, {queries = {c = hl_query}})
]]
highlighter.new(parser, { queries = { c = hl_query } })
end, hl_query_c)
screen:expect(hl_grid_ts_c)
feed('5Goc<esc>dd')
@@ -364,10 +369,10 @@ describe('treesitter highlighting (C)', function()
it('is updated with :sort', function()
insert(test_text_c)
exec_lua [[
local parser = vim.treesitter.get_parser(0, "c")
test_hl = vim.treesitter.highlighter.new(parser, {queries = {c = hl_query}})
]]
exec_lua(function(hl_query)
local parser = vim.treesitter.get_parser(0, 'c')
vim.treesitter.highlighter.new(parser, { queries = { c = hl_query } })
end, hl_query_c)
screen:expect {
grid = [[
{3:int} width = {5:INT_MAX}, height = {5:INT_MAX}; |
@@ -470,19 +475,19 @@ describe('treesitter highlighting (C)', function()
]],
}
exec_lua [[
parser = vim.treesitter.get_parser(0, "c")
query = vim.treesitter.query.parse("c", "(declaration) @decl")
exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c')
local query = vim.treesitter.query.parse('c', '(declaration) @decl')
local nodes = {}
for _, node in query:iter_captures(parser:parse()[1]:root(), 0, 0, 19) do
table.insert(nodes, node)
end
parser:set_included_regions({nodes})
parser:set_included_regions({ nodes })
local hl = vim.treesitter.highlighter.new(parser, {queries = {c = "(identifier) @type"}})
]]
vim.treesitter.highlighter.new(parser, { queries = { c = '(identifier) @type' } })
end)
screen:expect {
grid = [[
@@ -513,13 +518,15 @@ describe('treesitter highlighting (C)', function()
screen:expect { grid = injection_grid_c }
exec_lua [[
local parser = vim.treesitter.get_parser(0, "c", {
injections = {c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c")) (preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))'}
exec_lua(function(hl_query)
local parser = vim.treesitter.get_parser(0, 'c', {
injections = {
c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c")) (preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))',
},
})
local highlighter = vim.treesitter.highlighter
test_hl = highlighter.new(parser, {queries = {c = hl_query}})
]]
highlighter.new(parser, { queries = { c = hl_query } })
end, hl_query_c)
screen:expect { grid = injection_grid_expected_c }
end)
@@ -529,14 +536,16 @@ describe('treesitter highlighting (C)', function()
screen:expect { grid = injection_grid_c }
exec_lua [[
vim.treesitter.language.register("c", "foo")
local parser = vim.treesitter.get_parser(0, "c", {
injections = {c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "foo")) (preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "foo"))'}
exec_lua(function(hl_query)
vim.treesitter.language.register('c', 'foo')
local parser = vim.treesitter.get_parser(0, 'c', {
injections = {
c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "foo")) (preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "foo"))',
},
})
local highlighter = vim.treesitter.highlighter
test_hl = highlighter.new(parser, {queries = {c = hl_query}})
]]
highlighter.new(parser, { queries = { c = hl_query } })
end, hl_query_c)
screen:expect { grid = injection_grid_expected_c }
end)
@@ -550,13 +559,14 @@ describe('treesitter highlighting (C)', function()
}
]])
exec_lua [[
local injection_query = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c")) (preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))'
vim.treesitter.query.set("c", "highlights", hl_query)
vim.treesitter.query.set("c", "injections", injection_query)
exec_lua(function(hl_query)
local injection_query =
'(preproc_def (preproc_arg) @injection.content (#set! injection.language "c")) (preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))'
vim.treesitter.query.set('c', 'highlights', hl_query)
vim.treesitter.query.set('c', 'injections', injection_query)
vim.treesitter.highlighter.new(vim.treesitter.get_parser(0, "c"))
]]
vim.treesitter.highlighter.new(vim.treesitter.get_parser(0, 'c'))
end, hl_query_c)
screen:expect {
grid = [[
@@ -576,10 +586,10 @@ describe('treesitter highlighting (C)', function()
insert(hl_text_c)
feed('gg')
exec_lua [[
local parser = vim.treesitter.get_parser(0, "c")
test_hl = vim.treesitter.highlighter.new(parser, {queries = {c = hl_query}})
]]
exec_lua(function(hl_query)
local parser = vim.treesitter.get_parser(0, 'c')
vim.treesitter.highlighter.new(parser, { queries = { c = hl_query } })
end, hl_query_c)
screen:expect(hl_grid_ts_c)
@@ -619,10 +629,14 @@ describe('treesitter highlighting (C)', function()
}
]])
exec_lua [[
local parser = vim.treesitter.get_parser(0, "c")
test_hl = vim.treesitter.highlighter.new(parser, {queries = {c = hl_query..'\n((translation_unit) @constant (#set! "priority" 101))\n'}})
]]
exec_lua(function(hl_query)
local parser = vim.treesitter.get_parser(0, 'c')
vim.treesitter.highlighter.new(parser, {
queries = {
c = hl_query .. '\n((translation_unit) @constant (#set! "priority" 101))\n',
},
})
end, hl_query_c)
-- expect everything to have Constant highlight
screen:expect {
grid = [[
@@ -669,11 +683,14 @@ describe('treesitter highlighting (C)', function()
hi link @foo.bar Type
hi link @foo String
]]
exec_lua [[
local parser = vim.treesitter.get_parser(0, "c", {})
local highlighter = vim.treesitter.highlighter
test_hl = highlighter.new(parser, {queries = {c = "(primitive_type) @foo.bar (string_literal) @foo"}})
]]
exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c', {})
local highlighter = vim.treesitter.highlighter
highlighter.new(
parser,
{ queries = { c = '(primitive_type) @foo.bar (string_literal) @foo' } }
)
end)
screen:expect {
grid = [[
@@ -701,10 +718,12 @@ describe('treesitter highlighting (C)', function()
insert(hl_text_c)
-- conceal can be empty or a single cchar.
exec_lua [=[
exec_lua(function()
vim.opt.cole = 2
local parser = vim.treesitter.get_parser(0, "c")
test_hl = vim.treesitter.highlighter.new(parser, {queries = {c = [[
local parser = vim.treesitter.get_parser(0, 'c')
vim.treesitter.highlighter.new(parser, {
queries = {
c = [[
("static" @keyword
(#set! conceal "R"))
@@ -717,8 +736,10 @@ describe('treesitter highlighting (C)', function()
arguments: (argument_list) @arguments)
(#eq? @function "multiqueue_put")
(#set! @function conceal "V"))
]]}})
]=]
]],
},
})
end)
screen:expect {
grid = [[
@@ -775,11 +796,11 @@ describe('treesitter highlighting (C)', function()
int z = 6;
]])
exec_lua([[
exec_lua(function()
local query = '((declaration)+ @string)'
vim.treesitter.query.set('c', 'highlights', query)
vim.treesitter.highlighter.new(vim.treesitter.get_parser(0, 'c'))
]])
end)
screen:expect {
grid = [[
@@ -805,14 +826,10 @@ describe('treesitter highlighting (C)', function()
declarator: (pointer_declarator) @variable.parameter)
]]
exec_lua(
[[
local query = ...
vim.treesitter.query.set('c', 'highlights', query)
exec_lua(function(query_str)
vim.treesitter.query.set('c', 'highlights', query_str)
vim.treesitter.highlighter.new(vim.treesitter.get_parser(0, 'c'))
]],
query
)
end, query)
screen:expect {
grid = [[
@@ -847,10 +864,10 @@ describe('treesitter highlighting (lua)', function()
ffi.cdef("int (*fun)(int, char *);")
]]
exec_lua [[
exec_lua(function()
vim.bo.filetype = 'lua'
vim.treesitter.start()
]]
end)
screen:expect {
grid = [[
@@ -888,10 +905,10 @@ describe('treesitter highlighting (help)', function()
<
]]
exec_lua [[
exec_lua(function()
vim.bo.filetype = 'help'
vim.treesitter.start()
]]
end)
screen:expect {
grid = [[
@@ -943,15 +960,15 @@ describe('treesitter highlighting (help)', function()
]]
]=])
exec_lua [[
parser = vim.treesitter.get_parser(0, "lua", {
exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'lua', {
injections = {
lua = '(string content: (_) @injection.content (#set! injection.language lua))'
}
lua = '(string content: (_) @injection.content (#set! injection.language lua))',
},
})
vim.treesitter.highlighter.new(parser)
]]
end)
screen:expect {
grid = [=[
@@ -967,7 +984,7 @@ describe('treesitter highlighting (help)', function()
end)
describe('treesitter highlighting (nested injections)', function()
local screen
local screen --- @type test.functional.ui.screen
before_each(function()
clear()
@@ -996,11 +1013,11 @@ vim.cmd([[
]])
]=]
exec_lua [[
exec_lua(function()
vim.opt.scrolloff = 0
vim.bo.filetype = 'lua'
vim.treesitter.start()
]]
end)
-- invalidate the language tree
feed('ggi--[[<ESC>04x')
@@ -1041,10 +1058,10 @@ describe('treesitter highlighting (markdown)', function()
clear()
screen = Screen.new(40, 6)
screen:attach()
exec_lua([[
exec_lua(function()
vim.bo.filetype = 'markdown'
vim.treesitter.start()
]])
end)
end)
it('supports hyperlinks', function()

View File

@@ -22,10 +22,10 @@ describe('vim.treesitter.inspect_tree', function()
print()
]])
exec_lua([[
exec_lua(function()
vim.treesitter.start(0, 'lua')
vim.treesitter.inspect_tree()
]])
end)
expect_tree [[
(chunk ; [0, 0] - [2, 0]
@@ -40,10 +40,10 @@ describe('vim.treesitter.inspect_tree', function()
print('hello')
]])
exec_lua([[
exec_lua(function()
vim.treesitter.start(0, 'lua')
vim.treesitter.inspect_tree()
]])
end)
feed('a')
expect_tree [[
@@ -67,11 +67,11 @@ describe('vim.treesitter.inspect_tree', function()
```
]])
exec_lua([[
exec_lua(function()
vim.treesitter.start(0, 'markdown')
vim.treesitter.get_parser():parse()
vim.treesitter.inspect_tree()
]])
end)
expect_tree [[
(document ; [0, 0] - [4, 0]
@@ -96,11 +96,11 @@ describe('vim.treesitter.inspect_tree', function()
```
]])
exec_lua([[
exec_lua(function()
vim.treesitter.start(0, 'markdown')
vim.treesitter.get_parser():parse()
vim.treesitter.inspect_tree()
]])
end)
feed('I')
expect_tree [[
@@ -125,28 +125,28 @@ describe('vim.treesitter.inspect_tree', function()
]])
-- setup two windows for the source buffer
exec_lua([[
source_win = vim.api.nvim_get_current_win()
exec_lua(function()
_G.source_win = vim.api.nvim_get_current_win()
vim.api.nvim_open_win(0, false, {
win = 0,
split = 'left'
split = 'left',
})
]])
end)
-- setup three windows for the tree buffer
exec_lua([[
exec_lua(function()
vim.treesitter.start(0, 'lua')
vim.treesitter.inspect_tree()
tree_win = vim.api.nvim_get_current_win()
tree_win_copy_1 = vim.api.nvim_open_win(0, false, {
_G.tree_win = vim.api.nvim_get_current_win()
_G.tree_win_copy_1 = vim.api.nvim_open_win(0, false, {
win = 0,
split = 'left'
split = 'left',
})
tree_win_copy_2 = vim.api.nvim_open_win(0, false, {
_G.tree_win_copy_2 = vim.api.nvim_open_win(0, false, {
win = 0,
split = 'left'
split = 'left',
})
]])
end)
-- close original source window
exec_lua('vim.api.nvim_win_close(source_win, false)')

View File

@@ -54,10 +54,10 @@ describe('treesitter language API', function()
end)
it('inspects language', function()
local keys, fields, symbols = unpack(exec_lua([[
local keys, fields, symbols = unpack(exec_lua(function()
local lang = vim.treesitter.language.inspect('c')
local keys, symbols = {}, {}
for k,_ in pairs(lang) do
for k, _ in pairs(lang) do
keys[k] = true
end
@@ -66,8 +66,8 @@ describe('treesitter language API', function()
for _, v in pairs(lang.symbols) do
table.insert(symbols, v)
end
return {keys, lang.fields, symbols}
]]))
return { keys, lang.fields, symbols }
end))
eq({ fields = true, symbols = true, _abi_version = true }, keys)
@@ -113,12 +113,14 @@ describe('treesitter language API', function()
int x = 3;
}]])
exec_lua([[
langtree = vim.treesitter.get_parser(0, "c")
tree = langtree:tree_for_range({1, 3, 1, 3})
]])
eq('<node translation_unit>', exec_lua('return tostring(tree:root())'))
eq(
'<node translation_unit>',
exec_lua(function()
local langtree = vim.treesitter.get_parser(0, 'c')
local tree = langtree:tree_for_range({ 1, 3, 1, 3 })
return tostring(tree:root())
end)
)
end)
it('retrieve the tree given a range when range is out of bounds relative to buffer', function()
@@ -127,12 +129,14 @@ describe('treesitter language API', function()
int x = 3;
}]])
exec_lua([[
langtree = vim.treesitter.get_parser(0, "c")
tree = langtree:tree_for_range({10, 10, 10, 10})
]])
eq('<node translation_unit>', exec_lua('return tostring(tree:root())'))
eq(
'<node translation_unit>',
exec_lua(function()
local langtree = vim.treesitter.get_parser(0, 'c')
local tree = langtree:tree_for_range({ 10, 10, 10, 10 })
return tostring(tree:root())
end)
)
end)
it('retrieve the node given a range', function()
@@ -141,12 +145,14 @@ describe('treesitter language API', function()
int x = 3;
}]])
exec_lua([[
langtree = vim.treesitter.get_parser(0, "c")
node = langtree:named_node_for_range({1, 3, 1, 3})
]])
eq('<node primitive_type>', exec_lua('return tostring(node)'))
eq(
'<node primitive_type>',
exec_lua(function()
local langtree = vim.treesitter.get_parser(0, 'c')
local node = langtree:named_node_for_range({ 1, 3, 1, 3 })
return tostring(node)
end)
)
end)
it('retrieve an anonymous node given a range', function()

View File

@@ -18,39 +18,39 @@ describe('treesitter node API', function()
it('double free tree', function()
insert('F')
exec_lua([[
exec_lua(function()
vim.treesitter.start(0, 'lua')
vim.treesitter.get_node():tree()
vim.treesitter.get_node():tree()
collectgarbage()
]])
end)
assert_alive()
end)
it('double free tree 2', function()
exec_lua([[
parser = vim.treesitter.get_parser(0, "c")
exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c')
local x = parser:parse()[1]:root():tree()
vim.api.nvim_buf_set_text(0, 0,0, 0,0, {'y'})
vim.api.nvim_buf_set_text(0, 0, 0, 0, 0, { 'y' })
parser:parse()
vim.api.nvim_buf_set_text(0, 0,0, 0,1, {'z'})
vim.api.nvim_buf_set_text(0, 0, 0, 0, 1, { 'z' })
parser:parse()
collectgarbage()
x:root()
]])
end)
assert_alive()
end)
it('get_node() with lang given', function()
-- this buffer doesn't have filetype set!
insert('local foo = function() end')
exec_lua([[
node = vim.treesitter.get_node({
exec_lua(function()
_G.node = vim.treesitter.get_node({
bufnr = 0,
pos = { 0, 6 }, -- on "foo"
pos = { 0, 6 }, -- on "foo"
lang = 'lua',
})
]])
end)
eq('foo', lua_eval('vim.treesitter.get_node_text(node, 0)'))
eq('identifier', lua_eval('node:type()'))
end)
@@ -79,16 +79,16 @@ describe('treesitter node API', function()
}
]])
exec_lua([[
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
root = tree:root()
lang = vim.treesitter.language.inspect('c')
exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
_G.root = tree:root()
vim.treesitter.language.inspect('c')
function node_text(node)
function _G.node_text(node)
return vim.treesitter.get_node_text(node, 0)
end
]])
end)
exec_lua 'node = root:descendant_for_range(0, 11, 0, 16)'
eq('int x', lua_eval('node_text(node)'))
@@ -118,13 +118,13 @@ describe('treesitter node API', function()
int x = 3;
}]])
local len = exec_lua([[
tree = vim.treesitter.get_parser(0, "c"):parse()[1]
node = tree:root():child(0)
children = node:named_children()
local len = exec_lua(function()
local tree = vim.treesitter.get_parser(0, 'c'):parse()[1]
local node = tree:root():child(0)
_G.children = node:named_children()
return #children
]])
return #_G.children
end)
eq(3, len)
eq('<node compound_statement>', lua_eval('tostring(children[3])'))
@@ -136,11 +136,11 @@ describe('treesitter node API', function()
int x = 3;
}]])
exec_lua([[
tree = vim.treesitter.get_parser(0, "c"):parse()[1]
root = tree:root()
node = root:child(0):child(2)
]])
exec_lua(function()
local tree = vim.treesitter.get_parser(0, 'c'):parse()[1]
_G.root = tree:root()
_G.node = _G.root:child(0):child(2)
end)
eq(lua_eval('tostring(root)'), lua_eval('tostring(node:root())'))
end)
@@ -151,11 +151,11 @@ describe('treesitter node API', function()
int x = 3;
}]])
exec_lua([[
tree = vim.treesitter.get_parser(0, "c"):parse()[1]
root = tree:root()
child = root:child(0):child(0)
]])
exec_lua(function()
local tree = vim.treesitter.get_parser(0, 'c'):parse()[1]
_G.root = tree:root()
_G.child = _G.root:child(0):child(0)
end)
eq(28, lua_eval('root:byte_length()'))
eq(3, lua_eval('child:byte_length()'))
@@ -167,15 +167,15 @@ describe('treesitter node API', function()
int x = 3;
}]])
exec_lua([[
tree = vim.treesitter.get_parser(0, "c"):parse()[1]
root = tree:root()
main = root:child(0)
body = main:child(2)
statement = body:child(1)
declarator = statement:child(1)
value = declarator:child(1)
]])
exec_lua(function()
local tree = vim.treesitter.get_parser(0, 'c'):parse()[1]
_G.root = tree:root()
_G.main = _G.root:child(0)
_G.body = _G.main:child(2)
_G.statement = _G.body:child(1)
_G.declarator = _G.statement:child(1)
_G.value = _G.declarator:child(1)
end)
eq(lua_eval('main:type()'), lua_eval('root:child_containing_descendant(value):type()'))
eq(lua_eval('body:type()'), lua_eval('main:child_containing_descendant(value):type()'))

View File

@@ -12,9 +12,9 @@ local feed = n.feed
describe('treesitter parser API', function()
before_each(function()
clear()
exec_lua [[
exec_lua(function()
vim.g.__ts_debug = 1
]]
end)
end)
it('parses buffer', function()
@@ -23,12 +23,12 @@ describe('treesitter parser API', function()
int x = 3;
}]])
exec_lua([[
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
root = tree:root()
lang = vim.treesitter.language.inspect('c')
]])
exec_lua(function()
_G.parser = vim.treesitter.get_parser(0, 'c')
_G.tree = _G.parser:parse()[1]
_G.root = _G.tree:root()
_G.lang = vim.treesitter.language.inspect('c')
end)
eq('<tree>', exec_lua('return tostring(tree)'))
eq('<node translation_unit>', exec_lua('return tostring(root)'))
@@ -59,11 +59,11 @@ describe('treesitter parser API', function()
)
feed('2G7|ay')
exec_lua([[
tree2 = parser:parse()[1]
root2 = tree2:root()
descendant2 = root2:descendant_for_range(1,2,1,13)
]])
exec_lua(function()
_G.tree2 = _G.parser:parse()[1]
_G.root2 = _G.tree2:root()
_G.descendant2 = _G.root2:descendant_for_range(1, 2, 1, 13)
end)
eq(false, exec_lua('return tree2 == tree1'))
eq(false, exec_lua('return root2 == root'))
eq('<node declaration>', exec_lua('return tostring(descendant2)'))
@@ -112,17 +112,17 @@ void ui_refresh(void)
it('allows to iterate over nodes children', function()
insert(test_text)
local res = exec_lua([[
parser = vim.treesitter.get_parser(0, "c")
local res = exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c')
func_node = parser:parse()[1]:root():child(0)
local func_node = parser:parse()[1]:root():child(0)
res = {}
local res = {}
for node, field in func_node:iter_children() do
table.insert(res, { node:type(), field })
end
return res
]])
end)
eq({
{ 'primitive_type', 'type' },
@@ -148,43 +148,43 @@ void ui_refresh(void)
it('allows to get a child by field', function()
insert(test_text)
local res = exec_lua([[
parser = vim.treesitter.get_parser(0, "c")
local res = exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c')
func_node = parser:parse()[1]:root():child(0)
_G.func_node = parser:parse()[1]:root():child(0)
local res = {}
for _, node in ipairs(func_node:field("type")) do
for _, node in ipairs(_G.func_node:field('type')) do
table.insert(res, { node:type(), node:range() })
end
return res
]])
end)
eq({ { 'primitive_type', 0, 0, 0, 4 } }, res)
local res_fail = exec_lua([[
parser = vim.treesitter.get_parser(0, "c")
local res_fail = exec_lua(function()
vim.treesitter.get_parser(0, 'c')
return #func_node:field("foo") == 0
]])
return #_G.func_node:field('foo') == 0
end)
assert(res_fail)
end)
it('supports getting text of multiline node', function()
insert(test_text)
local res = exec_lua([[
local parser = vim.treesitter.get_parser(0, "c")
local res = exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
return vim.treesitter.get_node_text(tree:root(), 0)
]])
end)
eq(test_text, res)
local res2 = exec_lua([[
local parser = vim.treesitter.get_parser(0, "c")
local res2 = exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c')
local root = parser:parse()[1]:root()
return vim.treesitter.get_node_text(root:child(0):child(0), 0)
]])
end)
eq('void', res2)
end)
@@ -196,7 +196,7 @@ end]]
insert(text)
eq(
'',
exec_lua [[
exec_lua(function()
local fake_node = {}
function fake_node:start()
return 3, 0, 23
@@ -211,7 +211,7 @@ end]]
return 3, 0, 3, 0
end
return vim.treesitter.get_node_text(fake_node, 0)
]]
end)
)
end)
@@ -221,7 +221,7 @@ end]]
{}
```]]
insert(text)
local result = exec_lua([[
local result = exec_lua(function()
local fake_node = {}
function fake_node:start()
return 1, 0, 7
@@ -233,38 +233,38 @@ end]]
return 1, 0, 1, 0
end
return vim.treesitter.get_node_text(fake_node, 0) == ''
]])
end)
eq(true, result)
end)
it('allows to set simple ranges', function()
insert(test_text)
local res = exec_lua [[
parser = vim.treesitter.get_parser(0, "c")
return { parser:parse()[1]:root():range() }
]]
local res = exec_lua(function()
_G.parser = vim.treesitter.get_parser(0, 'c')
return { _G.parser:parse()[1]:root():range() }
end)
eq({ 0, 0, 19, 0 }, res)
-- The following sets the included ranges for the current parser
-- As stated here, this only includes the function (thus the whole buffer, without the last line)
local res2 = exec_lua [[
local root = parser:parse()[1]:root()
parser:set_included_regions({{root:child(0)}})
parser:invalidate()
return { parser:parse(true)[1]:root():range() }
]]
local res2 = exec_lua(function()
local root = _G.parser:parse()[1]:root()
_G.parser:set_included_regions({ { root:child(0) } })
_G.parser:invalidate()
return { _G.parser:parse(true)[1]:root():range() }
end)
eq({ 0, 0, 18, 1 }, res2)
eq({ { { 0, 0, 0, 18, 1, 512 } } }, exec_lua [[ return parser:included_regions() ]])
local range_tbl = exec_lua [[
parser:set_included_regions { { { 0, 0, 17, 1 } } }
parser:parse()
return parser:included_regions()
]]
local range_tbl = exec_lua(function()
_G.parser:set_included_regions { { { 0, 0, 17, 1 } } }
_G.parser:parse()
return _G.parser:included_regions()
end)
eq({ { { 0, 0, 0, 17, 1, 508 } } }, range_tbl)
end)
@@ -272,25 +272,25 @@ end]]
it('allows to set complex ranges', function()
insert(test_text)
local res = exec_lua [[
parser = vim.treesitter.get_parser(0, "c")
query = vim.treesitter.query.parse("c", "(declaration) @decl")
local res = exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c')
local query = vim.treesitter.query.parse('c', '(declaration) @decl')
local nodes = {}
for _, node in query:iter_captures(parser:parse()[1]:root(), 0) do
table.insert(nodes, node)
end
local nodes = {}
for _, node in query:iter_captures(parser:parse()[1]:root(), 0) do
table.insert(nodes, node)
end
parser:set_included_regions({nodes})
parser:set_included_regions({ nodes })
local root = parser:parse(true)[1]:root()
local root = parser:parse(true)[1]:root()
local res = {}
for i=0,(root:named_child_count() - 1) do
table.insert(res, { root:named_child(i):range() })
end
return res
]]
local res = {}
for i = 0, (root:named_child_count() - 1) do
table.insert(res, { root:named_child(i):range() })
end
return res
end)
eq({
{ 2, 2, 2, 40 },
@@ -304,10 +304,10 @@ end]]
end)
it('allows to create string parsers', function()
local ret = exec_lua [[
local parser = vim.treesitter.get_string_parser("int foo = 42;", "c")
local ret = exec_lua(function()
local parser = vim.treesitter.get_string_parser('int foo = 42;', 'c')
return { parser:parse()[1]:root():range() }
]]
end)
eq({ 0, 0, 0, 13 }, ret)
end)
@@ -318,33 +318,31 @@ end]]
int bar = 13;
]]
local ret = exec_lua(
[[
local str = ...
local parser = vim.treesitter.get_string_parser(str, "c")
local ret = exec_lua(function(str)
local parser = vim.treesitter.get_string_parser(str, 'c')
local nodes = {}
local query = vim.treesitter.query.parse("c", '((identifier) @id (#eq? @id "foo"))')
local nodes = {}
local query = vim.treesitter.query.parse('c', '((identifier) @id (#eq? @id "foo"))')
for _, node in query:iter_captures(parser:parse()[1]:root(), str) do
table.insert(nodes, { node:range() })
end
for _, node in query:iter_captures(parser:parse()[1]:root(), str) do
table.insert(nodes, { node:range() })
end
return nodes
]],
txt
)
return nodes
end, txt)
eq({ { 0, 10, 0, 13 } }, ret)
end)
describe('when creating a language tree', function()
local function get_ranges()
return exec_lua [[
return exec_lua(function()
local result = {}
parser:for_each_tree(function(tree) table.insert(result, {tree:root():range()}) end)
_G.parser:for_each_tree(function(tree)
table.insert(result, { tree:root():range() })
end)
return result
]]
end)
end
before_each(function()
@@ -360,16 +358,17 @@ int x = INT_MAX;
describe('when parsing regions independently', function()
it('should inject a language', function()
exec_lua([[
parser = vim.treesitter.get_parser(0, "c", {
exec_lua(function()
_G.parser = vim.treesitter.get_parser(0, 'c', {
injections = {
c = (
'(preproc_def (preproc_arg) @injection.content (#set! injection.language "c")) ' ..
'(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))'
)
}})
parser:parse(true)
]])
'(preproc_def (preproc_arg) @injection.content (#set! injection.language "c")) '
.. '(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))'
),
},
})
_G.parser:parse(true)
end)
eq('table', exec_lua('return type(parser:children().c)'))
eq(5, exec_lua('return #parser:children().c:trees()'))
@@ -397,16 +396,17 @@ int x = INT_MAX;
describe('when parsing regions combined', function()
it('should inject a language', function()
exec_lua([[
parser = vim.treesitter.get_parser(0, "c", {
exec_lua(function()
_G.parser = vim.treesitter.get_parser(0, 'c', {
injections = {
c = (
'(preproc_def (preproc_arg) @injection.content (#set! injection.language "c") (#set! injection.combined)) ' ..
'(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c") (#set! injection.combined))'
)
}})
parser:parse(true)
]])
'(preproc_def (preproc_arg) @injection.content (#set! injection.language "c") (#set! injection.combined)) '
.. '(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c") (#set! injection.combined))'
),
},
})
_G.parser:parse(true)
end)
eq('table', exec_lua('return type(parser:children().c)'))
eq(2, exec_lua('return #parser:children().c:trees()'))
@@ -447,16 +447,17 @@ int x = INT_MAX;
describe('when using injection.self', function()
it('should inject the source language', function()
exec_lua([[
parser = vim.treesitter.get_parser(0, "c", {
exec_lua(function()
_G.parser = vim.treesitter.get_parser(0, 'c', {
injections = {
c = (
'(preproc_def (preproc_arg) @injection.content (#set! injection.self)) ' ..
'(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.self))'
)
}})
parser:parse(true)
]])
'(preproc_def (preproc_arg) @injection.content (#set! injection.self)) '
.. '(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.self))'
),
},
})
_G.parser:parse(true)
end)
eq('table', exec_lua('return type(parser:children().c)'))
eq(5, exec_lua('return #parser:children().c:trees()'))
@@ -484,16 +485,17 @@ int x = INT_MAX;
describe('when using the offset directive', function()
it('should shift the range by the directive amount', function()
exec_lua([[
parser = vim.treesitter.get_parser(0, "c", {
exec_lua(function()
_G.parser = vim.treesitter.get_parser(0, 'c', {
injections = {
c = (
'(preproc_def ((preproc_arg) @injection.content (#set! injection.language "c") (#offset! @injection.content 0 2 0 -1))) ' ..
'(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))'
)
}})
parser:parse(true)
]])
'(preproc_def ((preproc_arg) @injection.content (#set! injection.language "c") (#offset! @injection.content 0 2 0 -1))) '
.. '(preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))'
),
},
})
_G.parser:parse(true)
end)
eq('table', exec_lua('return type(parser:children().c)'))
eq({
@@ -506,7 +508,7 @@ int x = INT_MAX;
}, get_ranges())
end)
it('should list all directives', function()
local res_list = exec_lua [[
local res_list = exec_lua(function()
local query = vim.treesitter.query
local list = query.list_directives()
@@ -514,7 +516,7 @@ int x = INT_MAX;
table.sort(list)
return list
]]
end)
eq({ 'gsub!', 'offset!', 'set!', 'trim!' }, res_list)
end)
@@ -530,18 +532,18 @@ int x = INT_MAX;
end)
it('should return the correct language tree', function()
local result = exec_lua([[
parser = vim.treesitter.get_parser(0, "c", {
local result = exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c', {
injections = {
c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c"))'
}
c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c"))',
},
})
parser:parse(true)
local sub_tree = parser:language_for_range({1, 18, 1, 19})
local sub_tree = parser:language_for_range({ 1, 18, 1, 19 })
return sub_tree == parser:children().c
]])
end)
eq(true, result)
end)
@@ -555,23 +557,23 @@ print()
end)
it('ignores optional captures #23100', function()
local result = exec_lua([[
parser = vim.treesitter.get_parser(0, "lua", {
local result = exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'lua', {
injections = {
lua = (
'(function_call ' ..
'(arguments ' ..
'(string)? @injection.content ' ..
'(number)? @injection.content ' ..
'(#offset! @injection.content 0 1 0 -1) ' ..
'(#set! injection.language "c")))'
)
}
'(function_call '
.. '(arguments '
.. '(string)? @injection.content '
.. '(number)? @injection.content '
.. '(#offset! @injection.content 0 1 0 -1) '
.. '(#set! injection.language "c")))'
),
},
})
parser:parse(true)
return parser:is_valid()
]])
end)
eq(true, result)
end)
@@ -584,18 +586,15 @@ print()
int x = 3;
]])
local result = exec_lua([[
local result
local result = exec_lua(function()
local query =
vim.treesitter.query.parse('c', '((number_literal) @number (#set! "key" "value"))')
local parser = vim.treesitter.get_parser(0, 'c')
query = vim.treesitter.query.parse("c", '((number_literal) @number (#set! "key" "value"))')
parser = vim.treesitter.get_parser(0, "c")
for pattern, match, metadata in query:iter_matches(parser:parse()[1]:root(), 0, 0, -1, { all = true }) do
result = metadata.key
end
return result
]])
local _, _, metadata =
query:iter_matches(parser:parse()[1]:root(), 0, 0, -1, { all = true })()
return metadata.key
end)
eq('value', result)
end)
@@ -606,19 +605,18 @@ print()
int x = 3;
]])
local result = exec_lua([[
local query = vim.treesitter.query
local value
local result = exec_lua(function()
local query = vim.treesitter.query.parse(
'c',
'((number_literal) @number (#set! @number "key" "value"))'
)
local parser = vim.treesitter.get_parser(0, 'c')
query = vim.treesitter.query.parse("c", '((number_literal) @number (#set! @number "key" "value"))')
parser = vim.treesitter.get_parser(0, "c")
for pattern, match, metadata in query:iter_matches(parser:parse()[1]:root(), 0, 0, -1, { all = true }) do
for _, nested_tbl in pairs(metadata) do
return nested_tbl.key
end
end
]])
local _, _, metadata =
query:iter_matches(parser:parse()[1]:root(), 0, 0, -1, { all = true })()
local _, nested_tbl = next(metadata)
return nested_tbl.key
end)
eq('value', result)
end)
@@ -628,19 +626,18 @@ print()
int x = 3;
]])
local result = exec_lua([[
local query = vim.treesitter.query
local result
local result = exec_lua(function()
local query = vim.treesitter.query.parse(
'c',
'((number_literal) @number (#set! @number "key" "value") (#set! @number "key2" "value2"))'
)
local parser = vim.treesitter.get_parser(0, 'c')
query = vim.treesitter.query.parse("c", '((number_literal) @number (#set! @number "key" "value") (#set! @number "key2" "value2"))')
parser = vim.treesitter.get_parser(0, "c")
for pattern, match, metadata in query:iter_matches(parser:parse()[1]:root(), 0, 0, -1, { all = true }) do
for _, nested_tbl in pairs(metadata) do
return nested_tbl
end
end
]])
local _, _, metadata =
query:iter_matches(parser:parse()[1]:root(), 0, 0, -1, { all = true })()
local _, nested_tbl = next(metadata)
return nested_tbl
end)
local expected = {
['key'] = 'value',
['key2'] = 'value2',
@@ -663,24 +660,21 @@ print()
(function_definition) @function
]]
exec_lua([[
exec_lua(function()
vim.treesitter.start(0, 'c')
]])
end)
local function run_query()
return exec_lua(
[[
local query = vim.treesitter.query.parse("c", ...)
parser = vim.treesitter.get_parser()
tree = parser:parse()[1]
res = {}
for id, node in query:iter_captures(tree:root()) do
table.insert(res, {query.captures[id], node:range()})
end
return res
]],
query0
)
return exec_lua(function(query_str)
local query = vim.treesitter.query.parse('c', query_str)
local parser = vim.treesitter.get_parser()
local tree = parser:parse()[1]
local res = {}
for id, node in query:iter_captures(tree:root()) do
table.insert(res, { query.captures[id], node:range() })
end
return res
end, query0)
end
eq({
@@ -718,18 +712,15 @@ print()
]]
]==]
local r = exec_lua(
[[
local parser = vim.treesitter.get_string_parser(..., 'lua')
parser:parse(true)
local ranges = {}
parser:for_each_tree(function(tstree, tree)
ranges[tree:lang()] = { tstree:root():range(true) }
end)
return ranges
]],
source
)
local r = exec_lua(function(src)
local parser = vim.treesitter.get_string_parser(src, 'lua')
parser:parse(true)
local ranges = {}
parser:for_each_tree(function(tstree, tree)
ranges[tree:lang()] = { tstree:root():range(true) }
end)
return ranges
end, source)
eq({
lua = { 0, 6, 6, 16, 4, 438 },
@@ -741,19 +732,14 @@ print()
-- the ranges but only provide a Range4. Strip the byte entries from the ranges and make sure
-- add_bytes() produces the same result.
local rb = exec_lua(
[[
local r, source = ...
local add_bytes = require('vim.treesitter._range').add_bytes
for lang, range in pairs(r) do
r[lang] = {range[1], range[2], range[4], range[5]}
r[lang] = add_bytes(source, r[lang])
end
return r
]],
r,
source
)
local rb = exec_lua(function(r0, source0)
local add_bytes = require('vim.treesitter._range').add_bytes
for lang, range in pairs(r0) do
r0[lang] = { range[1], range[2], range[4], range[5] }
r0[lang] = add_bytes(source0, r0[lang])
end
return r0
end, r, source)
eq(rb, r)
end)
@@ -766,25 +752,25 @@ print()
]]
-- This is not a valid injection since (code) has children and include-children is not set
exec_lua [[
parser1 = require('vim.treesitter.languagetree').new(0, "vimdoc", {
exec_lua(function()
_G.parser1 = require('vim.treesitter.languagetree').new(0, 'vimdoc', {
injections = {
vimdoc = "((codeblock (language) @injection.language (code) @injection.content))"
}
vimdoc = '((codeblock (language) @injection.language (code) @injection.content))',
},
})
parser1:parse(true)
]]
_G.parser1:parse(true)
end)
eq(0, exec_lua('return #vim.tbl_keys(parser1:children())'))
exec_lua [[
parser2 = require('vim.treesitter.languagetree').new(0, "vimdoc", {
exec_lua(function()
_G.parser2 = require('vim.treesitter.languagetree').new(0, 'vimdoc', {
injections = {
vimdoc = "((codeblock (language) @injection.language (code) @injection.content) (#set! injection.include-children))"
}
vimdoc = '((codeblock (language) @injection.language (code) @injection.content) (#set! injection.include-children))',
},
})
parser2:parse(true)
]]
_G.parser2:parse(true)
end)
eq(1, exec_lua('return #vim.tbl_keys(parser2:children())'))
eq({ { { 1, 0, 21, 2, 0, 42 } } }, exec_lua('return parser2:children().lua:included_regions()'))
@@ -821,46 +807,46 @@ print()
<
]])
exec_lua [[
parser = require('vim.treesitter.languagetree').new(0, "vimdoc", {
exec_lua(function()
_G.parser = require('vim.treesitter.languagetree').new(0, 'vimdoc', {
injections = {
vimdoc = "((codeblock (language) @injection.language (code) @injection.content) (#set! injection.include-children))"
}
vimdoc = '((codeblock (language) @injection.language (code) @injection.content) (#set! injection.include-children))',
},
})
]]
end)
--- Do not parse injections by default
eq(
0,
exec_lua [[
parser:parse()
return #vim.tbl_keys(parser:children())
]]
exec_lua(function()
_G.parser:parse()
return #vim.tbl_keys(_G.parser:children())
end)
)
--- Only parse injections between lines 0, 2
eq(
1,
exec_lua [[
parser:parse({0, 2})
return #parser:children().lua:trees()
]]
exec_lua(function()
_G.parser:parse({ 0, 2 })
return #_G.parser:children().lua:trees()
end)
)
eq(
2,
exec_lua [[
parser:parse({2, 6})
return #parser:children().lua:trees()
]]
exec_lua(function()
_G.parser:parse({ 2, 6 })
return #_G.parser:children().lua:trees()
end)
)
eq(
7,
exec_lua [[
parser:parse(true)
return #parser:children().lua:trees()
]]
exec_lua(function()
_G.parser:parse(true)
return #_G.parser:children().lua:trees()
end)
)
end)
@@ -876,13 +862,13 @@ print()
feed(':set ft=help<cr>')
exec_lua [[
vim.treesitter.get_parser(0, "vimdoc", {
exec_lua(function()
vim.treesitter.get_parser(0, 'vimdoc', {
injections = {
vimdoc = "((codeblock (language) @injection.language (code) @injection.content) (#set! injection.include-children))"
}
vimdoc = '((codeblock (language) @injection.language (code) @injection.content) (#set! injection.include-children))',
},
})
]]
end)
end)
it('is valid excluding, invalid including children initially', function()

View File

@@ -10,28 +10,26 @@ local pcall_err = t.pcall_err
local api = n.api
local fn = n.fn
local get_query_result_code = [[
function get_query_result(query_text)
cquery = vim.treesitter.query.parse("c", query_text)
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
res = {}
for cid, node in cquery:iter_captures(tree:root(), 0) do
-- can't transmit node over RPC. just check the name, range, and text
local text = vim.treesitter.get_node_text(node, 0)
local range = {node:range()}
table.insert(res, { cquery.captures[cid], node:type(), range, text })
end
return res
local function get_query_result(query_text)
local cquery = vim.treesitter.query.parse('c', query_text)
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
local res = {}
for cid, node in cquery:iter_captures(tree:root(), 0) do
-- can't transmit node over RPC. just check the name, range, and text
local text = vim.treesitter.get_node_text(node, 0)
local range = { node:range() }
table.insert(res, { cquery.captures[cid], node:type(), range, text })
end
]]
return res
end
describe('treesitter query API', function()
before_each(function()
clear()
exec_lua [[
exec_lua(function()
vim.g.__ts_debug = 1
]]
end)
end)
local test_text = [[
@@ -71,9 +69,9 @@ void ui_refresh(void)
it('supports runtime queries', function()
---@type string[]
local ret = exec_lua [[
return vim.treesitter.query.get("c", "highlights").captures
]]
local ret = exec_lua(function()
return vim.treesitter.query.get('c', 'highlights').captures
end)
-- see $VIMRUNTIME/queries/c/highlights.scm
eq('variable', ret[1])
@@ -84,22 +82,17 @@ void ui_refresh(void)
local long_query = test_query:rep(100)
---@return number
local function q(_n)
return exec_lua(
[[
local query, n = ...
local before = vim.api.nvim__stats().ts_query_parse_count
collectgarbage("stop")
for i=1, n, 1 do
cquery = vim.treesitter.query.parse("c", ...)
end
collectgarbage("restart")
collectgarbage("collect")
local after = vim.api.nvim__stats().ts_query_parse_count
return after - before
]],
long_query,
_n
)
return exec_lua(function(query, n0)
local before = vim.api.nvim__stats().ts_query_parse_count
collectgarbage('stop')
for _ = 1, n0, 1 do
vim.treesitter.query.parse('c', query, n0)
end
collectgarbage('restart')
collectgarbage('collect')
local after = vim.api.nvim__stats().ts_query_parse_count
return after - before
end, long_query, _n)
end
eq(1, q(1))
@@ -110,20 +103,17 @@ void ui_refresh(void)
it('supports query and iter by capture (iter_captures)', function()
insert(test_text)
local res = exec_lua(
[[
cquery = vim.treesitter.query.parse("c", ...)
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
res = {}
for cid, node in cquery:iter_captures(tree:root(), 0, 7, 14) do
-- can't transmit node over RPC. just check the name and range
table.insert(res, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
return res
]],
test_query
)
local res = exec_lua(function(test_query0)
local cquery = vim.treesitter.query.parse('c', test_query0)
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
local res = {}
for cid, node in cquery:iter_captures(tree:root(), 0, 7, 14) do
-- can't transmit node over RPC. just check the name and range
table.insert(res, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
return res
end, test_query)
eq({
{ '@type', 'primitive_type', 8, 2, 8, 6 }, -- bool
@@ -143,26 +133,23 @@ void ui_refresh(void)
insert(test_text)
---@type table
local res = exec_lua(
[[
cquery = vim.treesitter.query.parse("c", ...)
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
res = {}
for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14, { all = true }) do
-- can't transmit node over RPC. just check the name and range
local mrepr = {}
for cid, nodes in pairs(match) do
for _, node in ipairs(nodes) do
table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
local res = exec_lua(function(test_query0)
local cquery = vim.treesitter.query.parse('c', test_query0)
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
local res = {}
for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14, { all = true }) do
-- can't transmit node over RPC. just check the name and range
local mrepr = {}
for cid, nodes in pairs(match) do
for _, node in ipairs(nodes) do
table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
table.insert(res, { pattern, mrepr })
end
return res
]],
test_query
)
table.insert(res, { pattern, mrepr })
end
return res
end, test_query)
eq({
{ 3, { { '@type', 'primitive_type', 8, 2, 8, 6 } } },
@@ -191,20 +178,20 @@ void ui_refresh(void)
it('supports query and iter by capture for quantifiers', function()
insert(test_text)
local res = exec_lua(
[[
cquery = vim.treesitter.query.parse("c", ...)
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
res = {}
for cid, node in cquery:iter_captures(tree:root(), 0, 7, 14) do
-- can't transmit node over RPC. just check the name and range
table.insert(res, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
return res
]],
'(expression_statement (assignment_expression (call_expression)))+ @funccall'
)
local res = exec_lua(function()
local cquery = vim.treesitter.query.parse(
'c',
'(expression_statement (assignment_expression (call_expression)))+ @funccall'
)
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
local res = {}
for cid, node in cquery:iter_captures(tree:root(), 0, 7, 14) do
-- can't transmit node over RPC. just check the name and range
table.insert(res, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
return res
end)
eq({
{ '@funccall', 'expression_statement', 11, 4, 11, 34 },
@@ -216,26 +203,26 @@ void ui_refresh(void)
it('supports query and iter by match for quantifiers', function()
insert(test_text)
local res = exec_lua(
[[
cquery = vim.treesitter.query.parse("c", ...)
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
res = {}
for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14, { all = true }) do
-- can't transmit node over RPC. just check the name and range
local mrepr = {}
for cid, nodes in pairs(match) do
for _, node in ipairs(nodes) do
table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
local res = exec_lua(function()
local cquery = vim.treesitter.query.parse(
'c',
'(expression_statement (assignment_expression (call_expression)))+ @funccall'
)
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
local res = {}
for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14, { all = true }) do
-- can't transmit node over RPC. just check the name and range
local mrepr = {}
for cid, nodes in pairs(match) do
for _, node in ipairs(nodes) do
table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
table.insert(res, {pattern, mrepr})
end
return res
]],
'(expression_statement (assignment_expression (call_expression)))+ @funccall'
)
table.insert(res, { pattern, mrepr })
end
return res
end, '(expression_statement (assignment_expression (call_expression)))+ @funccall')
eq({
{
@@ -265,26 +252,26 @@ void ui_refresh(void)
}
]])
local res = exec_lua(
[[
cquery = vim.treesitter.query.parse("c", ...)
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
res = {}
for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14, { all = true }) do
-- can't transmit node over RPC. just check the name and range
local mrepr = {}
for cid, nodes in pairs(match) do
for _, node in ipairs(nodes) do
table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
local res = exec_lua(function()
local cquery = vim.treesitter.query.parse(
'c',
'(expression_statement (assignment_expression (call_expression)))+ @funccall'
)
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
local res = {}
for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14, { all = true }) do
-- can't transmit node over RPC. just check the name and range
local mrepr = {}
for cid, nodes in pairs(match) do
for _, node in ipairs(nodes) do
table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
table.insert(res, {pattern, mrepr})
end
return res
]],
'(expression_statement (assignment_expression (call_expression)))+ @funccall'
)
table.insert(res, { pattern, mrepr })
end
return res
end)
eq({
{
@@ -308,18 +295,18 @@ void ui_refresh(void)
insert('char* astring = "\\n"; (1 + 1) * 2 != 2;')
---@type table
local res = exec_lua([[
query = (
'([_] @plus (#vim-match? @plus "^\\\\+$"))' ..
'([_] @times (#vim-match? @times "^\\\\*$"))' ..
'([_] @paren (#vim-match? @paren "^\\\\($"))' ..
'([_] @escape (#vim-match? @escape "^\\\\\\\\n$"))' ..
'([_] @string (#vim-match? @string "^\\"\\\\\\\\n\\"$"))'
local res = exec_lua(function()
local query = (
'([_] @plus (#vim-match? @plus "^\\\\+$"))'
.. '([_] @times (#vim-match? @times "^\\\\*$"))'
.. '([_] @paren (#vim-match? @paren "^\\\\($"))'
.. '([_] @escape (#vim-match? @escape "^\\\\\\\\n$"))'
.. '([_] @string (#vim-match? @string "^\\"\\\\\\\\n\\"$"))'
)
cquery = vim.treesitter.query.parse("c", query)
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
res = {}
local cquery = vim.treesitter.query.parse('c', query)
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
local res = {}
for pattern, match in cquery:iter_matches(tree:root(), 0, 0, -1, { all = true }) do
-- can't transmit node over RPC. just check the name and range
local mrepr = {}
@@ -331,7 +318,7 @@ void ui_refresh(void)
table.insert(res, { pattern, mrepr })
end
return res
]])
end)
eq({
{ 2, { { '@times', '*', 0, 4, 0, 5 } } },
@@ -362,10 +349,9 @@ void ui_refresh(void)
return 0;
}
]])
exec_lua(get_query_result_code)
local res0 = exec_lua(
[[return get_query_result(...)]],
get_query_result,
[[((primitive_type) @c-keyword (#any-of? @c-keyword "int" "float"))]]
)
eq({
@@ -374,7 +360,7 @@ void ui_refresh(void)
}, res0)
local res1 = exec_lua(
[[return get_query_result(...)]],
get_query_result,
[[
((string_literal) @fizzbuzz-strings (#any-of? @fizzbuzz-strings
"\"number= %d FizzBuzz\\n\""
@@ -395,16 +381,15 @@ void ui_refresh(void)
int x = 123;
enum C { y = 124 };
int main() { int z = 125; }]])
exec_lua(get_query_result_code)
local result = exec_lua(
[[return get_query_result(...)]],
get_query_result,
[[((number_literal) @literal (#has-ancestor? @literal "function_definition"))]]
)
eq({ { 'literal', 'number_literal', { 2, 21, 2, 24 }, '125' } }, result)
result = exec_lua(
[[return get_query_result(...)]],
get_query_result,
[[((number_literal) @literal (#has-ancestor? @literal "function_definition" "enum_specifier"))]]
)
eq({
@@ -413,7 +398,7 @@ void ui_refresh(void)
}, result)
result = exec_lua(
[[return get_query_result(...)]],
get_query_result,
[[((number_literal) @literal (#not-has-ancestor? @literal "enum_specifier"))]]
)
eq({
@@ -425,11 +410,14 @@ void ui_refresh(void)
it('allows loading query with escaped quotes and capture them `#{lua,vim}-match`?', function()
insert('char* astring = "Hello World!";')
local res = exec_lua([[
cquery = vim.treesitter.query.parse("c", '([_] @quote (#vim-match? @quote "^\\"$")) ([_] @quote (#lua-match? @quote "^\\"$"))')
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
res = {}
local res = exec_lua(function()
local cquery = vim.treesitter.query.parse(
'c',
'([_] @quote (#vim-match? @quote "^\\"$")) ([_] @quote (#lua-match? @quote "^\\"$"))'
)
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
local res = {}
for pattern, match in cquery:iter_matches(tree:root(), 0, 0, -1, { all = true }) do
-- can't transmit node over RPC. just check the name and range
local mrepr = {}
@@ -441,7 +429,7 @@ void ui_refresh(void)
table.insert(res, { pattern, mrepr })
end
return res
]])
end)
eq({
{ 1, { { '@quote', '"', 0, 16, 0, 17 } } },
@@ -461,70 +449,64 @@ void ui_refresh(void)
local custom_query = '((identifier) @main (#is-main? @main))'
do
local res = exec_lua(
[[
local query = vim.treesitter.query
local res = exec_lua(function(custom_query0)
local query = vim.treesitter.query
local function is_main(match, pattern, bufnr, predicate)
local nodes = match[ predicate[2] ]
for _, node in ipairs(nodes) do
if vim.treesitter.get_node_text(node, bufnr) == 'main' then
return true
end
local function is_main(match, _pattern, bufnr, predicate)
local nodes = match[predicate[2]]
for _, node in ipairs(nodes) do
if vim.treesitter.get_node_text(node, bufnr) == 'main' then
return true
end
return false
end
return false
end
local parser = vim.treesitter.get_parser(0, "c")
local parser = vim.treesitter.get_parser(0, 'c')
-- Time bomb: update this in 0.12
if vim.fn.has('nvim-0.12') == 1 then
return 'Update this test to remove this message and { all = true } from add_predicate'
end
query.add_predicate("is-main?", is_main, { all = true })
-- Time bomb: update this in 0.12
if vim.fn.has('nvim-0.12') == 1 then
return 'Update this test to remove this message and { all = true } from add_predicate'
end
query.add_predicate('is-main?', is_main, { all = true })
local query = query.parse("c", ...)
local query0 = query.parse('c', custom_query0)
local nodes = {}
for _, node in query:iter_captures(parser:parse()[1]:root(), 0) do
table.insert(nodes, {node:range()})
end
local nodes = {}
for _, node in query0:iter_captures(parser:parse()[1]:root(), 0) do
table.insert(nodes, { node:range() })
end
return nodes
]],
custom_query
)
return nodes
end, custom_query)
eq({ { 0, 4, 0, 8 } }, res)
end
-- Once with the old API. Remove this whole 'do' block in 0.12
do
local res = exec_lua(
[[
local query = vim.treesitter.query
local res = exec_lua(function(custom_query0)
local query = vim.treesitter.query
local function is_main(match, pattern, bufnr, predicate)
local node = match[ predicate[2] ]
local function is_main(match, _pattern, bufnr, predicate)
local node = match[predicate[2]]
return vim.treesitter.get_node_text(node, bufnr) == 'main'
end
return vim.treesitter.get_node_text(node, bufnr) == 'main'
end
local parser = vim.treesitter.get_parser(0, "c")
local parser = vim.treesitter.get_parser(0, 'c')
query.add_predicate("is-main?", is_main, true)
query.add_predicate('is-main?', is_main, true)
local query = query.parse("c", ...)
local query0 = query.parse('c', custom_query0)
local nodes = {}
for _, node in query:iter_captures(parser:parse()[1]:root(), 0) do
table.insert(nodes, {node:range()})
end
local nodes = {}
for _, node in query0:iter_captures(parser:parse()[1]:root(), 0) do
table.insert(nodes, { node:range() })
end
return nodes
]],
custom_query
)
return nodes
end, custom_query)
-- Remove this 'do' block in 0.12
eq(0, fn.has('nvim-0.12'))
@@ -532,16 +514,16 @@ void ui_refresh(void)
end
do
local res = exec_lua [[
local res = exec_lua(function()
local query = vim.treesitter.query
local t = {}
local r = {}
for _, v in ipairs(query.list_predicates()) do
t[v] = true
r[v] = true
end
return t
]]
return r
end)
eq(true, res['is-main?'])
end
@@ -560,18 +542,15 @@ void ui_refresh(void)
local function test(input, query)
api.nvim_buf_set_lines(0, 0, -1, true, vim.split(dedent(input), '\n'))
return exec_lua(
[[
local parser = vim.treesitter.get_parser(0, "lua")
local query = vim.treesitter.query.parse("lua", ...)
local nodes = {}
for _, node in query:iter_captures(parser:parse()[1]:root(), 0) do
nodes[#nodes+1] = { node:range() }
end
return nodes
]],
query
)
return exec_lua(function(query_str)
local parser = vim.treesitter.get_parser(0, 'lua')
local query0 = vim.treesitter.query.parse('lua', query_str)
local nodes = {}
for _, node in query0:iter_captures(parser:parse()[1]:root(), 0) do
nodes[#nodes + 1] = { node:range() }
end
return nodes
end, query)
end
eq(
@@ -638,23 +617,21 @@ void ui_refresh(void)
-- Comment
]])
local query = [[
local result = exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'lua')
local query = vim.treesitter.query.parse(
'lua',
[[
(((comment (comment_content))+) @bar
(#lua-match? @bar "Comment"))
]]
local result = exec_lua(
[[
local parser = vim.treesitter.get_parser(0, "lua")
local query = vim.treesitter.query.parse("lua", ...)
local nodes = {}
for _, node in query:iter_captures(parser:parse()[1]:root(), 0) do
nodes[#nodes+1] = { node:range() }
end
return nodes
]],
query
)
)
local nodes = {}
for _, node in query:iter_captures(parser:parse()[1]:root(), 0) do
nodes[#nodes + 1] = { node:range() }
end
return nodes
end)
eq({
{ 0, 2, 0, 12 },
@@ -668,23 +645,20 @@ void ui_refresh(void)
eq(0, fn.has('nvim-0.12'))
insert(test_text)
local res = exec_lua(
[[
cquery = vim.treesitter.query.parse("c", ...)
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
res = {}
for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14) do
local mrepr = {}
for cid, node in pairs(match) do
table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
table.insert(res, { pattern, mrepr })
local res = exec_lua(function(test_query0)
local cquery = vim.treesitter.query.parse('c', test_query0)
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
local res = {}
for pattern, match in cquery:iter_matches(tree:root(), 0, 7, 14) do
local mrepr = {}
for cid, node in pairs(match) do
table.insert(mrepr, { '@' .. cquery.captures[cid], node:type(), node:range() })
end
return res
]],
test_query
)
table.insert(res, { pattern, mrepr })
end
return res
end, test_query)
eq({
{ 3, { { '@type', 'primitive_type', 8, 2, 8, 6 } } },
@@ -716,23 +690,19 @@ void ui_refresh(void)
int bar = 13;
]]
local ret = exec_lua(
[[
local str = ...
local parser = vim.treesitter.get_string_parser(str, "c")
local ret = exec_lua(function(str)
local parser = vim.treesitter.get_string_parser(str, 'c')
local nodes = {}
local query = vim.treesitter.query.parse("c", '((identifier) @foo)')
local first_child = parser:parse()[1]:root():child(1)
local nodes = {}
local query = vim.treesitter.query.parse('c', '((identifier) @foo)')
local first_child = parser:parse()[1]:root():child(1)
for _, node in query:iter_captures(first_child, str) do
table.insert(nodes, { node:range() })
end
for _, node in query:iter_captures(first_child, str) do
table.insert(nodes, { node:range() })
end
return nodes
]],
txt
)
return nodes
end, txt)
eq({ { 1, 10, 1, 13 } }, ret)
end)
@@ -789,7 +759,10 @@ void ui_refresh(void)
const char *sql = "SELECT * FROM Students WHERE name = 'Robert'); DROP TABLE Students;--";
]])
local query = [[
local result = exec_lua(function()
local query = vim.treesitter.query.parse(
'c',
[[
(declaration
type: (_)
declarator: (init_declarator
@@ -800,20 +773,15 @@ void ui_refresh(void)
(#set! injection.language "sql")
(#contains? @_id "sql"))
]]
local result = exec_lua(
[=[
local query = vim.treesitter.query.parse("c", ...)
local parser = vim.treesitter.get_parser(0, "c")
)
local parser = vim.treesitter.get_parser(0, 'c')
local root = parser:parse()[1]:root()
local t = {}
for id, node, metadata in query:iter_captures(root, 0) do
t[query.captures[id]] = metadata
local res = {}
for id, _, metadata in query:iter_captures(root, 0) do
res[query.captures[id]] = metadata
end
return t
]=],
query
)
return res
end)
eq({
['_id'] = { ['injection.language'] = 'sql' },
@@ -837,25 +805,22 @@ void ui_refresh(void)
(#eq? @function.name "foo"))
]]
local result = exec_lua(
[[
local query = vim.treesitter.query.parse("c", ...)
local match_preds = query.match_preds
local result = exec_lua(function(query_str)
local query0 = vim.treesitter.query.parse('c', query_str)
local match_preds = query0.match_preds
local called = 0
function query:match_preds(...)
function query0:match_preds(...)
called = called + 1
return match_preds(self, ...)
end
local parser = vim.treesitter.get_parser(0, "c")
local parser = vim.treesitter.get_parser(0, 'c')
local root = parser:parse()[1]:root()
local captures = {}
for id, node in query:iter_captures(root, 0) do
for id in query0:iter_captures(root, 0) do
captures[#captures + 1] = id
end
return { called, captures }
]],
query
)
end, query)
eq({ 2, { 1, 1, 2, 2 } }, result)
end)

View File

@@ -17,26 +17,26 @@ describe('treesitter utils', function()
int x = 3;
}]])
exec_lua([[
parser = vim.treesitter.get_parser(0, "c")
tree = parser:parse()[1]
root = tree:root()
ancestor = root:child(0)
child = ancestor:child(0)
]])
exec_lua(function()
local parser = vim.treesitter.get_parser(0, 'c')
local tree = parser:parse()[1]
local root = tree:root()
_G.ancestor = root:child(0)
_G.child = _G.ancestor:child(0)
end)
eq(true, exec_lua('return vim.treesitter.is_ancestor(ancestor, child)'))
eq(false, exec_lua('return vim.treesitter.is_ancestor(child, ancestor)'))
eq(true, exec_lua('return vim.treesitter.is_ancestor(_G.ancestor, _G.child)'))
eq(false, exec_lua('return vim.treesitter.is_ancestor(_G.child, _G.ancestor)'))
end)
it('can detect if a position is contained in a node', function()
exec_lua([[
node = {
exec_lua(function()
_G.node = {
range = function()
return 0, 4, 0, 8
end,
}
]])
end)
eq(false, exec_lua('return vim.treesitter.is_in_node_range(node, 0, 3)'))
for i = 4, 7 do