refactor: fix luals warnings

This commit is contained in:
dundargoc 2023-12-13 14:04:24 +01:00 committed by dundargoc
parent bf0be0f63e
commit d51b615747
17 changed files with 133 additions and 77 deletions

View File

@ -12,7 +12,7 @@
"ignoreDir": [
"test"
],
"checkThirdParty": false
"checkThirdParty": "Disable"
},
"diagnostics": {
"groupFileStatus": {

View File

@ -156,10 +156,10 @@ function vim._os_proc_info(pid)
elseif r.code ~= 0 then
error('command failed: ' .. vim.fn.string(cmd))
end
local ppid = assert(vim.system({ 'ps', '-p', pid, '-o', 'ppid=' }):wait().stdout)
local ppid_string = assert(vim.system({ 'ps', '-p', pid, '-o', 'ppid=' }):wait().stdout)
-- Remove trailing whitespace.
name = vim.trim(name):gsub('^.*/', '')
ppid = tonumber(ppid) or -1
local ppid = tonumber(ppid_string) or -1
return {
name = name,
pid = pid,
@ -533,20 +533,21 @@ function vim.region(bufnr, pos1, pos2, regtype, inclusive)
local region = {}
for l = pos1[1], pos2[1] do
local c1, c2
local c1 --- @type number
local c2 --- @type number
if regtype:byte() == 22 then -- block selection: take width from regtype
c1 = pos1[2]
c2 = c1 + regtype:sub(2)
c2 = c1 + tonumber(regtype:sub(2))
-- and adjust for non-ASCII characters
local bufline = vim.api.nvim_buf_get_lines(bufnr, l, l + 1, true)[1]
local utflen = vim.str_utfindex(bufline, #bufline)
if c1 <= utflen then
c1 = vim.str_byteindex(bufline, c1)
c1 = assert(tonumber(vim.str_byteindex(bufline, c1)))
else
c1 = #bufline + 1
end
if c2 <= utflen then
c2 = vim.str_byteindex(bufline, c2)
c2 = assert(tonumber(vim.str_byteindex(bufline, c2)))
else
c2 = #bufline + 1
end
@ -576,7 +577,7 @@ end
---@return table timer luv timer object
function vim.defer_fn(fn, timeout)
vim.validate({ fn = { fn, 'c', true } })
local timer = vim.uv.new_timer()
local timer = assert(vim.uv.new_timer())
timer:start(
timeout,
0,
@ -601,6 +602,7 @@ end
---@param msg string Content of the notification to show to the user.
---@param level integer|nil One of the values from |vim.log.levels|.
---@param opts table|nil Optional parameters. Unused by default.
---@diagnostic disable-next-line: unused-local
function vim.notify(msg, level, opts) -- luacheck: no unused args
if level == vim.log.levels.ERROR then
vim.api.nvim_err_writeln(msg)
@ -700,6 +702,8 @@ end
---
--- 1. Can we get it to just return things in the global namespace with that name prefix
--- 2. Can we get it to return things from global namespace even with `print(` in front.
---
--- @param pat string
function vim._expand_pat(pat, env)
env = env or _G
@ -801,11 +805,13 @@ function vim._expand_pat(pat, env)
return keys, #prefix_match_pat
end
--- @param lua_string string
vim._expand_pat_get_parts = function(lua_string)
local parts = {}
local accumulator, search_index = '', 1
local in_brackets, bracket_end = false, -1
local in_brackets = false
local bracket_end = -1 --- @type integer?
local string_char = nil
for idx = 1, #lua_string do
local s = lua_string:sub(idx, idx)
@ -938,9 +944,12 @@ function vim.keycode(str)
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
--- @param server_addr string
--- @param connect_error string
function vim._cs_remote(rcid, server_addr, connect_error, args)
--- @return string
local function connection_failure_errmsg(consequence)
local explanation
local explanation --- @type string
if server_addr == '' then
explanation = 'No server specified with --server'
else
@ -983,7 +992,7 @@ function vim._cs_remote(rcid, server_addr, connect_error, args)
local res = tostring(vim.rpcrequest(rcid, 'nvim_eval', args[2]))
return { result = res, should_exit = true, tabbed = false }
elseif subcmd ~= '' then
return { errmsg = 'Unknown option argument: ' .. args[1] }
return { errmsg = 'Unknown option argument: ' .. tostring(args[1]) }
end
if rcid == 0 then

View File

@ -12,6 +12,7 @@ for s in (package.cpath .. ';'):gmatch('[^;]*;') do
end
end
--- @param name string
function vim._load_package(name)
local basename = name:gsub('%.', '/')
local paths = { 'lua/' .. basename .. '.lua', 'lua/' .. basename .. '/init.lua' }

View File

@ -51,6 +51,7 @@ function M.watch(path, opts, callback)
local uvflags = opts and opts.uvflags or {}
local handle, new_err = vim.uv.new_fs_event()
assert(not new_err, new_err)
handle = assert(handle)
local _, start_err = handle:start(path, uvflags, function(err, filename, events)
assert(not err, err)
local fullpath = path

View File

@ -108,6 +108,7 @@ local function filter_by_severity(severity, diagnostics)
severities[to_severity(s)] = true
end
--- @param t table
return vim.tbl_filter(function(t)
return severities[t.severity]
end, diagnostics)

View File

@ -1,8 +1,8 @@
local M = {}
local s_output = {}
local s_output = {} ---@type string[]
-- Returns the fold text of the current healthcheck section
--- Returns the fold text of the current healthcheck section
function M.foldtext()
local foldtext = vim.fn.foldtext()
@ -36,12 +36,13 @@ function M.foldtext()
return vim.b.failedchecks[foldtext] and '+WE' .. foldtext:sub(4) or foldtext
end
-- From a path return a list [{name}, {func}, {type}] representing a healthcheck
--- @param path string path to search for the healthcheck
--- @return string[] { name, func, type } representing a healthcheck
local function filepath_to_healthcheck(path)
path = vim.fs.normalize(path)
local name
local func
local filetype
local name --- @type string
local func --- @type string
local filetype --- @type string
if path:find('vim$') then
name = vim.fs.basename(path):gsub('%.vim$', '')
func = 'health#' .. name .. '#check'
@ -50,10 +51,10 @@ local function filepath_to_healthcheck(path)
local subpath = path:gsub('.*lua/', '')
if vim.fs.basename(subpath) == 'health.lua' then
-- */health.lua
name = vim.fs.dirname(subpath)
name = assert(vim.fs.dirname(subpath))
else
-- */health/init.lua
name = vim.fs.dirname(vim.fs.dirname(subpath))
name = assert(vim.fs.dirname(assert(vim.fs.dirname(subpath))))
end
name = name:gsub('/', '.')
@ -63,11 +64,12 @@ local function filepath_to_healthcheck(path)
return { name, func, filetype }
end
-- Returns { {name, func, type}, ... } representing healthchecks
--- @param plugin_names string
--- @return table<any,string[]> { {name, func, type}, ... } representing healthchecks
local function get_healthcheck_list(plugin_names)
local healthchecks = {}
plugin_names = vim.split(plugin_names, ' ')
for _, p in pairs(plugin_names) do
local healthchecks = {} --- @type table<any,string[]>
local plugin_names_list = vim.split(plugin_names, ' ')
for _, p in pairs(plugin_names_list) do
-- support vim/lsp/health{/init/}.lua as :checkhealth vim.lsp
p = p:gsub('%.', '/')
@ -83,7 +85,7 @@ local function get_healthcheck_list(plugin_names)
if vim.tbl_count(paths) == 0 then
healthchecks[#healthchecks + 1] = { p, '', '' } -- healthcheck not found
else
local unique_paths = {}
local unique_paths = {} --- @type table<string, boolean>
for _, v in pairs(paths) do
unique_paths[v] = true
end
@ -100,10 +102,11 @@ local function get_healthcheck_list(plugin_names)
return healthchecks
end
-- Returns {name: [func, type], ..} representing healthchecks
--- @param plugin_names string
--- @return table<string, string[]> {name: [func, type], ..} representing healthchecks
local function get_healthcheck(plugin_names)
local health_list = get_healthcheck_list(plugin_names)
local healthchecks = {}
local healthchecks = {} --- @type table<string, string[]>
for _, c in pairs(health_list) do
if c[1] ~= 'vim' then
healthchecks[c[1]] = { c[2], c[3] }
@ -113,7 +116,11 @@ local function get_healthcheck(plugin_names)
return healthchecks
end
-- Indents lines *except* line 1 of a string if it contains newlines.
--- Indents lines *except* line 1 of a string if it contains newlines.
---
--- @param s string
--- @param columns integer
--- @return string
local function indent_after_line1(s, columns)
local lines = vim.split(s, '\n')
local indent = string.rep(' ', columns)
@ -123,13 +130,20 @@ local function indent_after_line1(s, columns)
return table.concat(lines, '\n')
end
-- Changes ':h clipboard' to ':help |clipboard|'.
--- Changes ':h clipboard' to ':help |clipboard|'.
---
--- @param s string
--- @return string
local function help_to_link(s)
return vim.fn.substitute(s, [[\v:h%[elp] ([^|][^"\r\n ]+)]], [[:help |\1|]], [[g]])
end
-- Format a message for a specific report item.
-- Variable args: Optional advice (string or list)
--- Format a message for a specific report item.
---
--- @param status string
--- @param msg string
--- @param ... string|string[] Optional advice
--- @return string
local function format_report_message(status, msg, ...)
local output = '- ' .. status
if status ~= '' then
@ -159,42 +173,54 @@ local function format_report_message(status, msg, ...)
return help_to_link(output)
end
--- @param output string
local function collect_output(output)
vim.list_extend(s_output, vim.split(output, '\n'))
end
-- Starts a new report.
--- Starts a new report.
---
--- @param name string
function M.start(name)
local input = string.format('\n%s ~', name)
collect_output(input)
end
-- Reports a message in the current section.
--- Reports a message in the current section.
---
--- @param msg string
function M.info(msg)
local input = format_report_message('', msg)
collect_output(input)
end
-- Reports a successful healthcheck.
--- Reports a successful healthcheck.
---
--- @param msg string
function M.ok(msg)
local input = format_report_message('OK', msg)
collect_output(input)
end
-- Reports a health warning.
-- ...: Optional advice (string or table)
--- Reports a health warning.
---
--- @param msg string
--- @param ... string|string[] Optional advice
function M.warn(msg, ...)
local input = format_report_message('WARNING', msg, ...)
collect_output(input)
end
-- Reports a failed healthcheck.
-- ...: Optional advice (string or table)
--- Reports a failed healthcheck.
---
--- @param msg string
--- @param ... string|string[] Optional advice
function M.error(msg, ...)
local input = format_report_message('ERROR', msg, ...)
collect_output(input)
end
--- @param type string
local function deprecate(type)
local before = string.format('vim.health.report_%s()', type)
local after = string.format('vim.health.%s()', type)
@ -206,22 +232,36 @@ local function deprecate(type)
vim.print('Running healthchecks...')
end
--- @deprecated
--- @param name string
function M.report_start(name)
deprecate('start')
M.start(name)
end
--- @deprecated
--- @param msg string
function M.report_info(msg)
deprecate('info')
M.info(msg)
end
--- @deprecated
--- @param msg string
function M.report_ok(msg)
deprecate('ok')
M.ok(msg)
end
--- @deprecated
--- @param msg string
function M.report_warn(msg, ...)
deprecate('warn')
M.warn(msg, ...)
end
--- @deprecated
--- @param msg string
function M.report_error(msg, ...)
deprecate('error')
M.error(msg, ...)
@ -251,7 +291,7 @@ local path2name = function(path)
end
local PATTERNS = { '/autoload/health/*.vim', '/lua/**/**/health.lua', '/lua/**/**/health/init.lua' }
-- :checkhealth completion function used by cmdexpand.c get_healthcheck_names()
--- :checkhealth completion function used by cmdexpand.c get_healthcheck_names()
M._complete = function()
local names = vim.tbl_flatten(vim.tbl_map(function(pattern)
return vim.tbl_map(path2name, vim.api.nvim_get_runtime_file(pattern, true))
@ -270,6 +310,9 @@ end
--- Runs all discovered healthchecks if plugin_names is empty.
---
--- @param mods string command modifiers that affect splitting a window.
--- @param plugin_names string glob of plugin names, split on whitespace. For example, using
--- `:checkhealth vim.* nvim` will healthcheck `vim.lsp`, `vim.treesitter`
--- and `nvim` modules.
function M._check(mods, plugin_names)
local healthchecks = plugin_names == '' and get_healthcheck('*') or get_healthcheck(plugin_names)
@ -289,7 +332,8 @@ function M._check(mods, plugin_names)
vim.cmd.file('health://')
vim.cmd.setfiletype('checkhealth')
if healthchecks == nil or next(healthchecks) == nil then
-- This should only happen when doing `:checkhealth vim`
if next(healthchecks) == nil then
vim.fn.setline(1, 'ERROR: No healthchecks found.')
return
end
@ -325,7 +369,7 @@ function M._check(mods, plugin_names)
local header = { string.rep('=', 78), name .. ': ' .. func, '' }
-- remove empty line after header from report_start
if s_output[1] == '' then
local tmp = {}
local tmp = {} ---@type string[]
for i = 2, #s_output do
tmp[#tmp + 1] = s_output[i]
end

View File

@ -432,6 +432,7 @@ end
--- ```
---
---@return any
---@diagnostic disable-next-line: unused-local
function Iter.next(self) -- luacheck: no unused args
-- This function is provided by the source iterator in Iter.new. This definition exists only for
-- the docstring
@ -489,6 +490,7 @@ end
--- ```
---
---@return any
---@diagnostic disable-next-line: unused-local
function Iter.peek(self) -- luacheck: no unused args
error('peek() requires a list-like table')
end
@ -568,12 +570,13 @@ end
---@see Iter.find
---
---@return any
---@diagnostic disable-next-line: unused-local
function Iter.rfind(self, f) -- luacheck: no unused args
error('rfind() requires a list-like table')
end
---@private
function ListIter.rfind(self, f) -- luacheck: no unused args
function ListIter.rfind(self, f)
if type(f) ~= 'function' then
local val = f
f = function(v)
@ -640,6 +643,7 @@ end
--- ```
---
---@return any
---@diagnostic disable-next-line: unused-local
function Iter.nextback(self) -- luacheck: no unused args
error('nextback() requires a list-like table')
end
@ -669,6 +673,7 @@ end
--- ```
---
---@return any
---@diagnostic disable-next-line: unused-local
function Iter.peekback(self) -- luacheck: no unused args
error('peekback() requires a list-like table')
end
@ -725,6 +730,7 @@ end
---
---@param n number Number of values to skip.
---@return Iter
---@diagnostic disable-next-line: unused-local
function Iter.skipback(self, n) -- luacheck: no unused args
error('skipback() requires a list-like table')
return self
@ -791,6 +797,7 @@ end
---@param first number
---@param last number
---@return Iter
---@diagnostic disable-next-line: unused-local
function Iter.slice(self, first, last) -- luacheck: no unused args
error('slice() requires a list-like table')
return self

View File

@ -1,5 +1,5 @@
local uv = vim.uv
local uri_encode = vim.uri_encode
local uri_encode = vim.uri_encode --- @type function
--- @type (fun(modename: string): fun()|string)[]
local loaders = package.loaders

View File

@ -329,11 +329,11 @@ end
---@param fn (T) Function to run
---@return T
local function once(fn)
local value --- @type any
local value --- @type function
local ran = false
return function(...)
if not ran then
value = fn(...)
value = fn(...) --- @type function
ran = true
end
return value

View File

@ -46,7 +46,7 @@ function M.hover()
end
local function request_with_options(name, params, options)
local req_handler
local req_handler --- @type function?
if options then
req_handler = function(err, result, ctx, config)
local client = assert(vim.lsp.get_client_by_id(ctx.client_id))

View File

@ -617,11 +617,6 @@ function vim.tbl_islist(t)
local num_elem = vim.tbl_count(t)
if num_elem == 0 then
-- TODO(bfredl): in the future, we will always be inside nvim
-- then this check can be deleted.
if vim._empty_dict_mt == nil then
return nil
end
return getmetatable(t) ~= vim._empty_dict_mt
else
for i = 1, num_elem do

View File

@ -133,7 +133,7 @@ function M.open(path)
path = vim.fn.expand(path)
end
local cmd
local cmd --- @type string[]
if vim.fn.has('mac') == 1 then
cmd = { 'open', path }

View File

@ -12,7 +12,7 @@
"${3rd}/luassert/library",
"${3rd}/luv/library"
],
"checkThirdParty": false
"checkThirdParty": "Disable"
},
"diagnostics": {
"groupFileStatus": {

View File

@ -65,10 +65,7 @@ if os.getenv('VALGRIND') then
table.insert(prepend_argv, '--vgdb-error=0')
end
elseif os.getenv('GDB') then
local gdbserver_port = '7777'
if os.getenv('GDBSERVER_PORT') then
gdbserver_port = os.getenv('GDBSERVER_PORT')
end
local gdbserver_port = os.getenv('GDBSERVER_PORT') or '7777'
prepend_argv = {'gdbserver', 'localhost:'..gdbserver_port}
end

View File

@ -1593,6 +1593,7 @@ function Screen:_pprint_attrs(attrs, cterm)
return table.concat(items, ", ")
end
---@diagnostic disable-next-line: unused-local, unused-function
local function backward_find_meaningful(tbl, from) -- luacheck: no unused
for i = from or #tbl, 1, -1 do
if tbl[i] ~= ' ' then

View File

@ -1,10 +1,10 @@
local shared = vim
local assert = require('luassert')
local luaassert = require('luassert')
local busted = require('busted')
local luv = require('luv')
local Paths = require('test.cmakeconfig.paths')
assert:set_parameter('TableFormatLevel', 100)
luaassert:set_parameter('TableFormatLevel', 100)
local quote_me = '[^.%w%+%-%@%_%/]' -- complement (needn't quote)
local function shell_quote(str)
@ -82,8 +82,8 @@ end
-- Calls fn() until it succeeds, up to `max` times or until `max_ms`
-- milliseconds have passed.
function module.retry(max, max_ms, fn)
assert(max == nil or max > 0)
assert(max_ms == nil or max_ms > 0)
luaassert(max == nil or max > 0)
luaassert(max_ms == nil or max_ms > 0)
local tries = 1
local timeout = (max_ms and max_ms or 10000)
local start_time = luv.now()
@ -108,10 +108,10 @@ local check_logs_useless_lines = {
}
function module.eq(expected, actual, context)
return assert.are.same(expected, actual, context)
return luaassert.are.same(expected, actual, context)
end
function module.neq(expected, actual, context)
return assert.are_not.same(expected, actual, context)
return luaassert.are_not.same(expected, actual, context)
end
--- Asserts that `cond` is true, or prints a message.
@ -120,21 +120,21 @@ end
--- @param expected (any) description of expected result
--- @param actual (any) description of actual result
function module.ok(cond, expected, actual)
assert(
luaassert(
(not expected and not actual) or (expected and actual),
'if "expected" is given, "actual" is also required'
)
local msg = expected and ('expected %s, got: %s'):format(expected, tostring(actual)) or nil
return assert(cond, msg)
return luaassert(cond, msg)
end
local function epicfail(state, arguments, _)
state.failure_message = arguments[1]
return false
end
assert:register('assertion', 'epicfail', epicfail)
luaassert:register('assertion', 'epicfail', epicfail)
function module.fail(msg)
return assert.epicfail(msg)
return luaassert.epicfail(msg)
end
function module.matches(pat, actual)
@ -154,7 +154,7 @@ end
---@param inverse? (boolean) Assert that the pattern does NOT match.
function module.assert_log(pat, logfile, nrlines, inverse)
logfile = logfile or os.getenv('NVIM_LOG_FILE') or '.nvimlog'
assert(logfile ~= nil, 'no logfile')
luaassert(logfile ~= nil, 'no logfile')
nrlines = nrlines or 10
inverse = inverse or false
@ -191,7 +191,7 @@ function module.assert_nolog(pat, logfile, nrlines)
end
function module.pcall(fn, ...)
assert(type(fn) == 'function')
luaassert(type(fn) == 'function')
local status, rv = pcall(fn, ...)
if status then
return status, rv
@ -238,7 +238,7 @@ end
-- matches('e[or]+$', pcall_err(function(a, b) error('some error') end, 'arg1', 'arg2'))
--
function module.pcall_err_withfile(fn, ...)
assert(type(fn) == 'function')
luaassert(type(fn) == 'function')
local status, rv = module.pcall(fn, ...)
if status == true then
error('expected failure, but got success')
@ -315,7 +315,7 @@ function module.check_logs()
for tail in vim.fs.dir(log_dir) do
if tail:sub(1, 30) == 'valgrind-' or tail:find('san%.') then
local file = log_dir .. '/' .. tail
local fd = io.open(file)
local fd = assert(io.open(file))
local start_msg = ('='):rep(20) .. ' File ' .. file .. ' ' .. ('='):rep(20)
local lines = {}
local warning_line = 0
@ -350,7 +350,7 @@ function module.check_logs()
end
end
end
assert(
luaassert(
0 == #runtime_errors,
string.format('Found runtime errors in logfile(s): %s', table.concat(runtime_errors, ', '))
)
@ -757,7 +757,7 @@ function module.format_luav(v, indent, opts)
else
print(type(v))
-- Not implemented yet
assert(false)
luaassert(false)
end
return ret
end
@ -805,7 +805,7 @@ end
local fixtbl_metatable = {
__newindex = function()
assert(false)
luaassert(false)
end,
}
@ -902,7 +902,7 @@ end
-- Dedent the given text and write it to the file name.
function module.write_file(name, text, no_dedent, append)
local file = io.open(name, (append and 'a' or 'w'))
local file = assert(io.open(name, (append and 'a' or 'w')))
if type(text) == 'table' then
-- Byte blob
local bytes = text
@ -920,7 +920,7 @@ end
function module.is_ci(name)
local any = (name == nil)
assert(any or name == 'github' or name == 'cirrus')
luaassert(any or name == 'github' or name == 'cirrus')
local gh = ((any or name == 'github') and nil ~= os.getenv('GITHUB_ACTIONS'))
local cirrus = ((any or name == 'cirrus') and nil ~= os.getenv('CIRRUS_CI'))
return gh or cirrus

View File

@ -19,7 +19,7 @@ for _, p in ipairs(Paths.include_paths) do
Preprocess.add_to_include_path(p)
end
local child_pid = nil --- @type integer
local child_pid = nil --- @type integer?
--- @generic F: function
--- @param func F
--- @return F