refactor(lua): fix some luals warnings

This commit is contained in:
Christian Clason 2025-04-27 16:08:59 +02:00
parent bdc2e01958
commit 53d7118483
12 changed files with 61 additions and 61 deletions

3
.gitattributes vendored Normal file
View file

@ -0,0 +1,3 @@
runtime/queries/**/*.scm linguist-language=Tree-sitter-Query
doc/*.txt linguist-documentation
SUPPORTED_LANGUAGES.md linguist-generated

View file

@ -13,7 +13,7 @@ local config = {
} }
---Setup call for users to override configuration configurations. ---Setup call for users to override configuration configurations.
---@param user_data TSConfig|nil user configuration table ---@param user_data TSConfig? user configuration table
function M.setup(user_data) function M.setup(user_data)
if user_data then if user_data then
if user_data.install_dir then if user_data.install_dir then

View file

@ -93,7 +93,8 @@ local function install_health()
end end
health.start('OS Info') health.start('OS Info')
for k, v in pairs(vim.uv.os_uname()) do local osinfo = vim.uv.os_uname() ---@type table<string,string>
for k, v in pairs(osinfo) do
health.info(k .. ': ' .. v) health.info(k .. ': ' .. v)
end end
@ -107,9 +108,7 @@ local function install_health()
end end
if if
vim.iter(vim.api.nvim_list_runtime_paths()):any(function(p) vim.iter(vim.api.nvim_list_runtime_paths()):any(function(p)
if installdir == vim.fs.normalize(p) .. '/' then return installdir == vim.fs.normalize(p) .. '/'
return true
end
end) end)
then then
health.ok('is in runtimepath.') health.ok('is in runtimepath.')

View file

@ -26,7 +26,7 @@ end
---@param root TSNode ---@param root TSNode
---@param lnum integer ---@param lnum integer
---@param col? integer ---@param col? integer
---@return TSNode ---@return TSNode?
local function get_first_node_at_line(root, lnum, col) local function get_first_node_at_line(root, lnum, col)
col = col or get_indentcols_at_line(lnum) col = col or get_indentcols_at_line(lnum)
return root:descendant_for_range(lnum - 1, col, lnum - 1, col + 1) return root:descendant_for_range(lnum - 1, col, lnum - 1, col + 1)
@ -35,7 +35,7 @@ end
---@param root TSNode ---@param root TSNode
---@param lnum integer ---@param lnum integer
---@param col? integer ---@param col? integer
---@return TSNode ---@return TSNode?
local function get_last_node_at_line(root, lnum, col) local function get_last_node_at_line(root, lnum, col)
col = col or (#getline(lnum) - 1) col = col or (#getline(lnum) - 1)
return root:descendant_for_range(lnum - 1, col, lnum - 1, col + 1) return root:descendant_for_range(lnum - 1, col, lnum - 1, col + 1)
@ -52,8 +52,8 @@ end
---@param bufnr integer ---@param bufnr integer
---@param node TSNode ---@param node TSNode
---@param delimiter string ---@param delimiter string
---@return TSNode|nil child ---@return TSNode? child
---@return boolean|nil is_end ---@return boolean? is_end
local function find_delimiter(bufnr, node, delimiter) local function find_delimiter(bufnr, node, delimiter)
for child, _ in node:iter_children() do for child, _ in node:iter_children() do
if child:type() == delimiter then if child:type() == delimiter then
@ -89,6 +89,7 @@ local function memoize(fn, hash_fn)
end end
local get_indents = memoize(function(bufnr, root, lang) local get_indents = memoize(function(bufnr, root, lang)
---@type table<string,table<string,table>>
local map = { local map = {
['indent.auto'] = {}, ['indent.auto'] = {},
['indent.begin'] = {}, ['indent.begin'] = {},
@ -154,19 +155,19 @@ function M.get_indent(lnum)
end end
local q = get_indents(vim.api.nvim_get_current_buf(), root, lang_tree:lang()) local q = get_indents(vim.api.nvim_get_current_buf(), root, lang_tree:lang())
local node ---@type TSNode local node ---@type TSNode?
if getline(lnum):find('^%s*$') then if getline(lnum):find('^%s*$') then
local prevlnum = vim.fn.prevnonblank(lnum) local prevlnum = vim.fn.prevnonblank(lnum)
local indentcols = get_indentcols_at_line(prevlnum) local indentcols = get_indentcols_at_line(prevlnum)
local prevline = vim.trim(getline(prevlnum)) local prevline = vim.trim(getline(prevlnum))
-- The final position can be trailing spaces, which should not affect indentation -- The final position can be trailing spaces, which should not affect indentation
node = get_last_node_at_line(root, prevlnum, indentcols + #prevline - 1) node = get_last_node_at_line(root, prevlnum, indentcols + #prevline - 1)
if node:type():match('comment') then if node and node:type():match('comment') then
-- The final node we capture of the previous line can be a comment node, which should also be ignored -- The final node we capture of the previous line can be a comment node, which should also be ignored
-- Unless the last line is an entire line of comment, ignore the comment range and find the last node again -- Unless the last line is an entire line of comment, ignore the comment range and find the last node again
local first_node = get_first_node_at_line(root, prevlnum, indentcols) local first_node = get_first_node_at_line(root, prevlnum, indentcols)
local _, scol, _, _ = node:range() local _, scol, _, _ = node:range()
if first_node:id() ~= node:id() then if first_node and first_node:id() ~= node:id() then
-- In case the last captured node is a trailing comment node, re-trim the string -- In case the last captured node is a trailing comment node, re-trim the string
prevline = vim.trim(prevline:sub(1, scol - indentcols)) prevline = vim.trim(prevline:sub(1, scol - indentcols))
-- Add back indent as indent of prevline was trimmed away -- Add back indent as indent of prevline was trimmed away
@ -174,7 +175,7 @@ function M.get_indent(lnum)
node = get_last_node_at_line(root, prevlnum, col) node = get_last_node_at_line(root, prevlnum, col)
end end
end end
if q['indent.end'][node:id()] then if node and q['indent.end'][node:id()] then
node = get_first_node_at_line(root, lnum) node = get_first_node_at_line(root, lnum)
end end
else else
@ -192,7 +193,7 @@ function M.get_indent(lnum)
-- tracks to ensure multiple indent levels are not applied for same line -- tracks to ensure multiple indent levels are not applied for same line
local is_processed_by_row = {} --- @type table<integer,boolean> local is_processed_by_row = {} --- @type table<integer,boolean>
if q['indent.zero'][node:id()] then if node and q['indent.zero'][node:id()] then
return 0 return 0
end end
@ -240,7 +241,7 @@ function M.get_indent(lnum)
local is_in_err = false local is_in_err = false
if should_process then if should_process then
local parent = node:parent() local parent = node:parent()
is_in_err = parent and parent:has_error() is_in_err = parent and parent:has_error() or false
end end
if if
should_process should_process
@ -276,8 +277,8 @@ function M.get_indent(lnum)
and (srow ~= lnum - 1) and (srow ~= lnum - 1)
then then
local metadata = q['indent.align'][node:id()] local metadata = q['indent.align'][node:id()]
local o_delim_node, o_is_last_in_line ---@type TSNode|nil, boolean|nil local o_delim_node, o_is_last_in_line ---@type TSNode?, boolean?
local c_delim_node, c_is_last_in_line ---@type TSNode|nil, boolean|nil, boolean|nil local c_delim_node, c_is_last_in_line ---@type TSNode?, boolean?, boolean?
local indent_is_absolute = false local indent_is_absolute = false
if metadata['indent.open_delimiter'] then if metadata['indent.open_delimiter'] then
o_delim_node, o_is_last_in_line = o_delim_node, o_is_last_in_line =

View file

@ -434,7 +434,7 @@ local function install(languages, options, callback)
end end
end end
---@param languages string[] ---@param languages string[]|string
---@param options? InstallOptions ---@param options? InstallOptions
---@param callback? fun(boolean) ---@param callback? fun(boolean)
M.install = a.sync(function(languages, options, callback) M.install = a.sync(function(languages, options, callback)
@ -443,10 +443,8 @@ M.install = a.sync(function(languages, options, callback)
install(languages, options, callback) install(languages, options, callback)
end, 3) end, 3)
---@class UpdateOptions
---@param languages? string[]|string ---@param languages? string[]|string
---@param _options? UpdateOptions ---@param _options? table
---@param callback? function ---@param callback? function
M.update = a.sync(function(languages, _options, callback) M.update = a.sync(function(languages, _options, callback)
reload_parsers() reload_parsers()
@ -501,7 +499,7 @@ local function uninstall_lang(logger, lang, parser, queries)
end end
---@param languages string[]|string ---@param languages string[]|string
---@param _options? UpdateOptions ---@param _options? table
---@param _callback? fun() ---@param _callback? fun()
M.uninstall = a.sync(function(languages, _options, _callback) M.uninstall = a.sync(function(languages, _options, _callback)
languages = config.norm_languages(languages or 'all', { missing = true, dependencies = true }) languages = config.norm_languages(languages or 'all', { missing = true, dependencies = true })

View file

@ -18,7 +18,7 @@ end
---@param node TSNode ---@param node TSNode
---@return TSNode result ---@return TSNode result
local function get_root_for_node(node) local function get_root_for_node(node)
local parent = node local parent = node ---@type TSNode?
local result = node local result = node
while parent ~= nil do while parent ~= nil do
@ -56,9 +56,9 @@ end
-- Iterates over a nodes scopes moving from the bottom up -- Iterates over a nodes scopes moving from the bottom up
---@param node TSNode ---@param node TSNode
---@param bufnr integer ---@param bufnr integer
---@return fun(): TSNode|nil ---@return fun(): TSNode?
function M.iter_scope_tree(node, bufnr) function M.iter_scope_tree(node, bufnr)
local last_node = node local last_node = node ---@type TSNode?
return function() return function()
if not last_node then if not last_node then
return return
@ -247,7 +247,7 @@ M.get_definitions_lookup_table = memoize(function(bufnr)
return {} return {}
end end
local result = {} local result = {} ---@type TSLocal[]
for _, definition in ipairs(definitions) do for _, definition in ipairs(definitions) do
for _, node_entry in ipairs(M.get_local_nodes(definition)) do for _, node_entry in ipairs(M.get_local_nodes(definition)) do
local scopes = M.get_definition_scopes(node_entry.node, bufnr, node_entry.scope) local scopes = M.get_definition_scopes(node_entry.node, bufnr, node_entry.scope)
@ -279,9 +279,10 @@ end)
---@param node TSNode: the definition node ---@param node TSNode: the definition node
---@param bufnr integer: the buffer ---@param bufnr integer: the buffer
---@param scope_type TSScope: the scope type ---@param scope_type TSScope: the scope type
---@return TSNode[]
function M.get_definition_scopes(node, bufnr, scope_type) function M.get_definition_scopes(node, bufnr, scope_type)
local scopes = {} local scopes = {}
local scope_count = 1 ---@type integer|nil local scope_count = 1 ---@type integer?
-- Definition is valid for the containing scope -- Definition is valid for the containing scope
-- and the containing scope of that scope -- and the containing scope of that scope
@ -365,7 +366,7 @@ end
---@param node TSNode ---@param node TSNode
---@param bufnr? integer ---@param bufnr? integer
---@param allow_scope? boolean ---@param allow_scope? boolean
---@return TSNode|nil ---@return TSNode?
function M.containing_scope(node, bufnr, allow_scope) function M.containing_scope(node, bufnr, allow_scope)
bufnr = bufnr or api.nvim_get_current_buf() bufnr = bufnr or api.nvim_get_current_buf()
allow_scope = allow_scope == nil or allow_scope == true allow_scope = allow_scope == nil or allow_scope == true
@ -375,7 +376,7 @@ function M.containing_scope(node, bufnr, allow_scope)
return return
end end
local iter_node = node local iter_node = node ---@type TSNode?
while iter_node ~= nil and not vim.tbl_contains(scopes, iter_node) do while iter_node ~= nil and not vim.tbl_contains(scopes, iter_node) do
iter_node = iter_node:parent() iter_node = iter_node:parent()

View file

@ -1,8 +1,8 @@
local query = vim.treesitter.query local query = vim.treesitter.query
local predicates = { local predicates = {
---@param match TSQueryMatch ---@param match table<integer,TSNode[]>
---@param pred string[] ---@param pred any[]
---@param any boolean ---@param any boolean
---@return boolean ---@return boolean
['kind-eq'] = function(match, pred, any) ['kind-eq'] = function(match, pred, any)
@ -26,16 +26,16 @@ local predicates = {
-- register custom predicates (overwrite existing; needed for CI) -- register custom predicates (overwrite existing; needed for CI)
---@param match TSQueryMatch ---@param match table<integer,TSNode[]>
---@param pred string[] ---@param pred any[]
---@return boolean|nil ---@return boolean
query.add_predicate('kind-eq?', function(match, _, _, pred) query.add_predicate('kind-eq?', function(match, _, _, pred)
return predicates['kind-eq'](match, pred, false) return predicates['kind-eq'](match, pred, false)
end, { force = true }) end, { force = true })
---@param match TSQueryMatch ---@param match table<integer,TSNode[]>
---@param pred string[] ---@param pred any[]
---@return boolean|nil ---@return boolean
query.add_predicate('any-kind-eq?', function(match, _, _, pred) query.add_predicate('any-kind-eq?', function(match, _, _, pred)
return predicates['kind-eq'](match, pred, true) return predicates['kind-eq'](match, pred, true)
end, { force = true }) end, { force = true })

View file

@ -7,13 +7,13 @@ local parsers = #_G.arg > 0 and { unpack(_G.arg) }
or require('nvim-treesitter.config').installed_parsers() or require('nvim-treesitter.config').installed_parsers()
-- Extract captures from documentation for validation -- Extract captures from documentation for validation
local captures = {} local captures = {} ---@type table[]
do do
local current_query ---@type string local current_query ---@type string
for line in io.lines('CONTRIBUTING.md') do for line in io.lines('CONTRIBUTING.md') do
if vim.startswith(line, '### ') then if vim.startswith(line, '### ') then
current_query = line:sub(5):lower() current_query = line:sub(5):lower() ---@type string
elseif vim.startswith(line, '@') and current_query then elseif vim.startswith(line, '@') and current_query then
if not captures[current_query] then if not captures[current_query] then
captures[current_query] = {} captures[current_query] = {}
@ -24,14 +24,14 @@ do
end end
-- Complete captures for injections. -- Complete captures for injections.
for _, lang in pairs(vim.tbl_keys(configs)) do for lang, _ in pairs(configs) do
table.insert(captures['injections'], lang) table.insert(captures['injections'], lang)
end end
end end
-- Check queries for each installed parser in parsers -- Check queries for each installed parser in parsers
local errors = {} ---@type string[] local errors = {} ---@type string[]
local timings = {} ---@type number[][] local timings = {} ---@type { duration: number, lang: string, query_type: string }[]
do do
print('::group::Check parsers') print('::group::Check parsers')

View file

@ -351,7 +351,7 @@ end
---@param bufnr integer ---@param bufnr integer
---@param node TSNode ---@param node TSNode
---@param lines string[] ---@param lines string[]
---@param q table<string, vim.treesitter.query.TSMetadata> ---@param q table<string, table[]>
---@param level integer ---@param level integer
local function iter(bufnr, node, lines, q, level) local function iter(bufnr, node, lines, q, level)
--- Sometimes 2 queries apply append twice. This is to prevent the case from happening --- Sometimes 2 queries apply append twice. This is to prevent the case from happening
@ -430,19 +430,19 @@ end
---@param queries string ---@param queries string
local function format(bufnr, queries) local function format(bufnr, queries)
local lines = { '' } local lines = { '' }
-- stylua: ignore ---@type table<string,table<string,table>>
local map = { local map = {
['format.ignore'] = {}, -- Ignore the node and its children ['format.ignore'] = {}, -- Ignore the node and its children
['format.indent.begin'] = {}, -- +1 shiftwidth for all nodes after this ['format.indent.begin'] = {}, -- +1 shiftwidth for all nodes after this
['format.indent.dedent'] = {}, -- -1 shiftwidth for this line only ['format.indent.dedent'] = {}, -- -1 shiftwidth for this line only
['format.prepend-space'] = {}, -- Prepend a space before inserting the node ['format.prepend-space'] = {}, -- Prepend a space before inserting the node
['format.prepend-newline'] = {}, -- Prepend a \n before inserting the node ['format.prepend-newline'] = {}, -- Prepend a \n before inserting the node
['format.append-space'] = {}, -- Append a space after inserting the node ['format.append-space'] = {}, -- Append a space after inserting the node
['format.append-newline'] = {}, -- Append a newline after inserting the node ['format.append-newline'] = {}, -- Append a newline after inserting the node
['format.cancel-append'] = {}, -- Cancel any `@format.append-*` applied to the node ['format.cancel-append'] = {}, -- Cancel any `@format.append-*` applied to the node
['format.cancel-prepend'] = {}, -- Cancel any `@format.prepend-*` applied to the node ['format.cancel-prepend'] = {}, -- Cancel any `@format.prepend-*` applied to the node
['format.replace'] = {}, -- Dedicated capture used to store results of `(#gsub!)` ['format.replace'] = {}, -- Dedicated capture used to store results of `(#gsub!)`
['format.remove'] = {}, -- Do not add the syntax node to the result, i.e. brackets [], parens () ['format.remove'] = {}, -- Do not add the syntax node to the result, i.e. brackets [], parens ()
} }
local root = ts.get_parser(bufnr, 'query'):parse(true)[1]:root() local root = ts.get_parser(bufnr, 'query'):parse(true)[1]:root()
local query = ts.query.parse('query', queries) local query = ts.query.parse('query', queries)

View file

@ -12,7 +12,7 @@ for i = 1, #_G.arg do
elseif _G.arg[i]:find('^%-%-max%-jobs') then elseif _G.arg[i]:find('^%-%-max%-jobs') then
max_jobs = _G.arg[i]:match('=(%d+)') max_jobs = _G.arg[i]:match('=(%d+)')
else else
parsers[#parsers + 1] = _G.arg[i] parsers[#parsers + 1] = _G.arg[i] ---@type string
end end
end end

View file

@ -55,8 +55,9 @@ if #updates > 0 then
local update_list = table.concat(updates, ', ') local update_list = table.concat(updates, ', ')
print(string.format('\nUpdated parsers: %s', update_list)) print(string.format('\nUpdated parsers: %s', update_list))
-- pass list to workflow -- pass list to workflow
if os.getenv('GITHUB_ENV') then local gh_env = os.getenv('GITHUB_ENV')
local env = io.open(os.getenv('GITHUB_ENV'), 'a') if gh_env then
local env = assert(io.open(gh_env, 'a'))
env:write(string.format('UPDATED_PARSERS=%s\n', update_list)) env:write(string.format('UPDATED_PARSERS=%s\n', update_list))
env:close() env:close()
end end

View file

@ -3,11 +3,8 @@ vim.opt.runtimepath:append('.')
local util = require('nvim-treesitter.util') local util = require('nvim-treesitter.util')
local parsers = require('nvim-treesitter.parsers') local parsers = require('nvim-treesitter.parsers')
local tiers = require('nvim-treesitter.config').tiers local tiers = require('nvim-treesitter.config').tiers
---@class Parser
---@field name string
---@field parser ParserInfo
local sorted_parsers = {} local sorted_parsers = {} ---@type { name: string, parser: ParserInfo }[]
for k, v in pairs(parsers) do for k, v in pairs(parsers) do
table.insert(sorted_parsers, { name = k, parser = v }) table.insert(sorted_parsers, { name = k, parser = v })
end end