From 996a057fb9b4b7d791adad19f07b2f9c53a88ab5 Mon Sep 17 00:00:00 2001 From: Hirokazu Hata Date: Mon, 21 Oct 2019 23:46:28 +0900 Subject: lua/stdlib: adjust some validation messages #11271 close #11271 --- runtime/lua/vim/shared.lua | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) (limited to 'runtime/lua/vim/shared.lua') diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index cd6f8a04d8..220b6c6c7c 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -44,9 +44,9 @@ end --@param plain If `true` use `sep` literally (passed to String.find) --@returns Iterator over the split components local function gsplit(s, sep, plain) - assert(type(s) == "string") - assert(type(sep) == "string") - assert(type(plain) == "boolean" or type(plain) == "nil") + assert(type(s) == "string", string.format("Expected string, got %s", type(s))) + assert(type(sep) == "string", string.format("Expected string, got %s", type(sep))) + assert(type(plain) == "boolean" or type(plain) == "nil", string.format("Expected boolean or nil, got %s", type(plain))) local start = 1 local done = false @@ -103,9 +103,8 @@ end --@param value Value to compare --@returns true if `t` contains `value` local function tbl_contains(t, value) - if type(t) ~= 'table' then - error('t must be a table') - end + assert(type(t) == 'table', string.format("Expected table, got %s", type(t))) + for _,v in ipairs(t) do if v == value then return true @@ -174,7 +173,7 @@ end --@param s String to trim --@returns String with whitespace removed from its beginning and end local function trim(s) - assert(type(s) == 'string', 'Only strings can be trimmed') + assert(type(s) == 'string', string.format("Expected string, got %s", type(s))) return s:match('^%s*(.*%S)') or '' end @@ -184,7 +183,7 @@ end --@param s String to escape --@returns %-escaped pattern string local function pesc(s) - assert(type(s) == 'string') + assert(type(s) == 'string', string.format("Expected string, got %s", type(s))) return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1') end -- cgit From c2fc4255f92157b65a2f0d5b299027195541d6b8 Mon Sep 17 00:00:00 2001 From: Hirokazu Hata Date: Wed, 23 Oct 2019 10:50:42 +0900 Subject: runtime: Use module pattern with vim/shared.lua It's a bit cumbersome for us to add an export target every time we define a new function. It's also cumbersome to care about the order of definition when creating a new function by referring to other functions in the module. --- runtime/lua/vim/shared.lua | 75 +++++++++++++++++++++------------------------- 1 file changed, 34 insertions(+), 41 deletions(-) (limited to 'runtime/lua/vim/shared.lua') diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index 220b6c6c7c..7727fdbab0 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -4,34 +4,37 @@ -- test-suite. If, in the future, Nvim itself is used to run the test-suite -- instead of "vanilla Lua", these functions could move to src/nvim/lua/vim.lua +local vim = {} --- Returns a deep copy of the given object. Non-table objects are copied as --- in a typical Lua assignment, whereas table objects are copied recursively. --- --@param orig Table to copy --@returns New table of copied keys and (nested) values. -local function deepcopy(orig) - error(orig) -end -local function _id(v) - return v -end -local deepcopy_funcs = { - table = function(orig) - local copy = {} - for k, v in pairs(orig) do - copy[deepcopy(k)] = deepcopy(v) - end - return copy - end, - number = _id, - string = _id, - ['nil'] = _id, - boolean = _id, -} -deepcopy = function(orig) - return deepcopy_funcs[type(orig)](orig) -end +function vim.deepcopy(orig) end -- luacheck: no unused +vim.deepcopy = (function() + local function _id(v) + return v + end + + local deepcopy_funcs = { + table = function(orig) + local copy = {} + for k, v in pairs(orig) do + copy[vim.deepcopy(k)] = vim.deepcopy(v) + end + return copy + end, + number = _id, + string = _id, + ['nil'] = _id, + boolean = _id, + } + + return function(orig) + return deepcopy_funcs[type(orig)](orig) + end +end)() --- Splits a string at each instance of a separator. --- @@ -43,7 +46,7 @@ end --@param sep Separator string or pattern --@param plain If `true` use `sep` literally (passed to String.find) --@returns Iterator over the split components -local function gsplit(s, sep, plain) +function vim.gsplit(s, sep, plain) assert(type(s) == "string", string.format("Expected string, got %s", type(s))) assert(type(sep) == "string", string.format("Expected string, got %s", type(sep))) assert(type(plain) == "boolean" or type(plain) == "nil", string.format("Expected boolean or nil, got %s", type(plain))) @@ -92,8 +95,8 @@ end --@param sep Separator string or pattern --@param plain If `true` use `sep` literally (passed to String.find) --@returns List-like table of the split components. -local function split(s,sep,plain) - local t={} for c in gsplit(s, sep, plain) do table.insert(t,c) end +function vim.split(s,sep,plain) + local t={} for c in vim.gsplit(s, sep, plain) do table.insert(t,c) end return t end @@ -102,7 +105,7 @@ end --@param t Table to check --@param value Value to compare --@returns true if `t` contains `value` -local function tbl_contains(t, value) +function vim.tbl_contains(t, value) assert(type(t) == 'table', string.format("Expected table, got %s", type(t))) for _,v in ipairs(t) do @@ -122,7 +125,7 @@ end --- - "keep": use value from the leftmost map --- - "force": use value from the rightmost map --@param ... Two or more map-like tables. -local function tbl_extend(behavior, ...) +function vim.tbl_extend(behavior, ...) if (behavior ~= 'error' and behavior ~= 'keep' and behavior ~= 'force') then error('invalid "behavior": '..tostring(behavior)) end @@ -149,7 +152,7 @@ end --- --@param t List-like table --@returns Flattened copy of the given list-like table. -local function tbl_flatten(t) +function vim.tbl_flatten(t) -- From https://github.com/premake/premake-core/blob/master/src/base/table.lua local result = {} local function _tbl_flatten(_t) @@ -172,7 +175,7 @@ end --@see https://www.lua.org/pil/20.2.html --@param s String to trim --@returns String with whitespace removed from its beginning and end -local function trim(s) +function vim.trim(s) assert(type(s) == 'string', string.format("Expected string, got %s", type(s))) return s:match('^%s*(.*%S)') or '' end @@ -182,19 +185,9 @@ end --@see https://github.com/rxi/lume --@param s String to escape --@returns %-escaped pattern string -local function pesc(s) +function vim.pesc(s) assert(type(s) == 'string', string.format("Expected string, got %s", type(s))) return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1') end -local module = { - deepcopy = deepcopy, - gsplit = gsplit, - pesc = pesc, - split = split, - tbl_contains = tbl_contains, - tbl_extend = tbl_extend, - tbl_flatten = tbl_flatten, - trim = trim, -} -return module +return vim -- cgit From 678a51b1da0c0535299341e7a598c080adcf8553 Mon Sep 17 00:00:00 2001 From: Hirokazu Hata Date: Mon, 28 Oct 2019 20:52:18 +0900 Subject: Lua: vim.validate() We often want to do type checking of public function arguments. - test: Rename utility_function_spec.lua to vim_spec.lua - .luacov: Map lua module names --- runtime/lua/vim/shared.lua | 74 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) (limited to 'runtime/lua/vim/shared.lua') diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index 7727fdbab0..9f656774a1 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -190,4 +190,78 @@ function vim.pesc(s) return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1') end +--- Type checking validation function +--- +--- Examples: +---
+---  validate({ arg={ { 'foo' }, 'table' }})                                     --> Nop
+---  validate({ arg={ 1, 'table' } })                                            --> error("arg: expected table, got number")
+---  validate({ arg1={ { 'foo' }, 'table' }, arg2={ 1, 'string' } })             --> error("arg2: expected string, got number")
+---  validate({ arg={ 3, function(a) return (a % 2) == 0  end, 'even number' }}) --> error("arg: expected even number, got 3")
+--- 
+--- +---@param ... Table or list of table. That table is "argument_name = { validation_target, type_name (, whether nil is allowed) }" +--- or "argument_name = { validation_target, validation function, expected_description }". +--- The following can be used as type_names: +--- - table or t +--- - string or s +--- - number or n +--- - boolean or b +--- - function or f +--- - nil +--- - thread +--- - userdata +function vim.validate(opt) + local function _type_name(t) + if t == 't' or t == 'table' then return 'table' end + if t == 's' or t == 'string' then return 'string' end + if t == 'n' or t == 'number' then return 'number' end + if t == 'b' or t == 'boolean' then return 'boolean' end + if t == 'f' or t == 'function' then return 'function' end + if t == 'c' then return 'callable' end + if t == 'nil' then return 'nil' end + if t == 'thread' or t == 'thread' then return 'thread' end + if t == 'userdata' then return 'userdata' end + if vim.is_callable(t) then return end + + error(string.format("Invalid type name '%s'. See \":help validate\" for more info.", t)) + end + local function _check_type(target, expected_type) + if expected_type == 'callable' then + return vim.is_callable(target) + else + return type(target) == expected_type + end + end + + for arg, v in pairs(opt) do + assert(type(arg) == 'string',string.format('Expected string, got %s', type(arg))) + assert(type(v) == 'table', string.format('Expected table, got %s', type(v))) + + local actual_arg_type = type(v[1]) + local expected_type = _type_name(v[2]) + + if expected_type then + if v[3] == true then + assert(_check_type(v[1], expected_type) or actual_arg_type == 'nil', string.format("%s: expected %s, got %s", arg, expected_type, actual_arg_type)) + else + assert(_check_type(v[1], expected_type), string.format("%s: expected %s, got %s", arg, expected_type, actual_arg_type)) + end + else + assert(v[2](v[1]), string.format("%s: expected %s, got %s", arg, v[3], v[1])) + end + end +end + +--- Return whether an object can call be used as a function. +--- +--@param f Any type of variable +--@return Boolean +function vim.is_callable(f) + if type(f) == 'function' then return true end + local m = getmetatable(f) + if m == nil then return false end + return type(m.__call) == 'function' +end + return vim -- cgit From 7aa4042d3bddf2f39d048b9ba1dd7adf2193d4eb Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Sun, 10 Nov 2019 19:58:14 -0800 Subject: Lua: vim.validate() --- runtime/lua/vim/shared.lua | 111 +++++++++++++++++++++++++-------------------- 1 file changed, 62 insertions(+), 49 deletions(-) (limited to 'runtime/lua/vim/shared.lua') diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index 9f656774a1..7d2523403a 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -190,68 +190,81 @@ function vim.pesc(s) return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1') end ---- Type checking validation function +--- Validates a parameter specification (types and values). --- --- Examples: ---
----  validate({ arg={ { 'foo' }, 'table' }})                                     --> Nop
----  validate({ arg={ 1, 'table' } })                                            --> error("arg: expected table, got number")
----  validate({ arg1={ { 'foo' }, 'table' }, arg2={ 1, 'string' } })             --> error("arg2: expected string, got number")
----  validate({ arg={ 3, function(a) return (a % 2) == 0  end, 'even number' }}) --> error("arg: expected even number, got 3")
+---  function user.new(name, age, hobbies)
+---    vim.validate{
+---      name={name, 'string'},
+---      age={age, 'number'},
+---      hobbies={hobbies, 'table'},
+---    }
+---    ...
+---  end
+--
+---  vim.validate{ arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
+---     => NOP (success)
+---  vim.validate{arg1={1, 'table'}}
+---     => error("arg1: expected table, got number")
+---  vim.validate{arg1={{'foo'}, 'table'}, arg2={1, 'string'}}
+---     => error("arg2: expected string, got number")
+---  vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}}
+---     => error("arg1: expected even number, got 3")
 --- 
--- ----@param ... Table or list of table. That table is "argument_name = { validation_target, type_name (, whether nil is allowed) }" ---- or "argument_name = { validation_target, validation function, expected_description }". ---- The following can be used as type_names: ---- - table or t ---- - string or s ---- - number or n ---- - boolean or b ---- - function or f ---- - nil ---- - thread ---- - userdata -function vim.validate(opt) - local function _type_name(t) - if t == 't' or t == 'table' then return 'table' end - if t == 's' or t == 'string' then return 'string' end - if t == 'n' or t == 'number' then return 'number' end - if t == 'b' or t == 'boolean' then return 'boolean' end - if t == 'f' or t == 'function' then return 'function' end - if t == 'c' then return 'callable' end - if t == 'nil' then return 'nil' end - if t == 'thread' or t == 'thread' then return 'thread' end - if t == 'userdata' then return 'userdata' end - if vim.is_callable(t) then return end - - error(string.format("Invalid type name '%s'. See \":help validate\" for more info.", t)) - end - local function _check_type(target, expected_type) - if expected_type == 'callable' then - return vim.is_callable(target) - else - return type(target) == expected_type +--@param opt Map of parameter names to validations. Each key is a parameter +--- name; each value is a tuple in one of these forms: +--- 1. {arg_value, type_name, optional} +--- - arg_value: argument value +--- - type_name: string type name, one of: ("table", "t", "string", +--- "s", "number", "n", "boolean", "b", "function", "f", "nil", +--- "thread", "userdata") +--- - optional: (optional) boolean, if true, `nil` is valid +--- 2. {arg_value, fn, msg} +--- - arg_value: argument value +--- - fn: any function accepting one argument, returns true if and +--- only if the argument is valid +--- - msg: (optional) error string if validation fails +function vim.validate(opt) end -- luacheck: no unused +vim.validate = (function() + local type_names = { + t='table', s='string', n='number', b='boolean', f='function', c='callable', + ['table']='table', ['string']='string', ['number']='number', + ['boolean']='boolean', ['function']='function', ['callable']='callable', + ['nil']='nil', ['thread']='thread', ['userdata']='userdata', + } + local function type_name(t) + local tname = type_names[t] + if tname == nil then + error(string.format('invalid type name: %s', tostring(t))) end + return tname + end + local function is_type(val, t) + return t == 'callable' and vim.is_callable(val) or type(val) == t end - for arg, v in pairs(opt) do - assert(type(arg) == 'string',string.format('Expected string, got %s', type(arg))) - assert(type(v) == 'table', string.format('Expected table, got %s', type(v))) + return function(opt) + assert(type(opt) == 'table', string.format('opt: expected table, got %s', type(opt))) + for param_name, spec in pairs(opt) do + assert(type(spec) == 'table', string.format('%s: expected table, got %s', param_name, type(spec))) - local actual_arg_type = type(v[1]) - local expected_type = _type_name(v[2]) + local val = spec[1] -- Argument value. + local t = spec[2] -- Type name, or callable. + local optional = (true == spec[3]) - if expected_type then - if v[3] == true then - assert(_check_type(v[1], expected_type) or actual_arg_type == 'nil', string.format("%s: expected %s, got %s", arg, expected_type, actual_arg_type)) - else - assert(_check_type(v[1], expected_type), string.format("%s: expected %s, got %s", arg, expected_type, actual_arg_type)) + if not vim.is_callable(t) then -- Check type name. + if not (optional or type(val) == 'nil') and not is_type(val, type_name(t)) then + error(string.format("%s: expected %s, got %s", param_name, type_name(t), type(val))) + end + elseif not t(val) then -- Check user-provided validation function. + error(string.format("%s: expected %s, got %s", param_name, spec[3], val)) end - else - assert(v[2](v[1]), string.format("%s: expected %s, got %s", arg, v[3], v[1])) end + return true end -end +end)() --- Return whether an object can call be used as a function. --- -- cgit From a0d992785feeefaea2810dcf08564fd8bea8cab9 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Sun, 10 Nov 2019 22:18:59 -0800 Subject: Lua: Use vim.validate() instead of assert() --- runtime/lua/vim/shared.lua | 47 +++++++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 23 deletions(-) (limited to 'runtime/lua/vim/shared.lua') diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index 7d2523403a..e987e07a2a 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -47,9 +47,7 @@ end)() --@param plain If `true` use `sep` literally (passed to String.find) --@returns Iterator over the split components function vim.gsplit(s, sep, plain) - assert(type(s) == "string", string.format("Expected string, got %s", type(s))) - assert(type(sep) == "string", string.format("Expected string, got %s", type(sep))) - assert(type(plain) == "boolean" or type(plain) == "nil", string.format("Expected boolean or nil, got %s", type(plain))) + vim.validate{s={s,'s'},sep={sep,'s'},plain={plain,'b',true}} local start = 1 local done = false @@ -106,7 +104,7 @@ end --@param value Value to compare --@returns true if `t` contains `value` function vim.tbl_contains(t, value) - assert(type(t) == 'table', string.format("Expected table, got %s", type(t))) + vim.validate{t={t,'t'}} for _,v in ipairs(t) do if v == value then @@ -176,7 +174,7 @@ end --@param s String to trim --@returns String with whitespace removed from its beginning and end function vim.trim(s) - assert(type(s) == 'string', string.format("Expected string, got %s", type(s))) + vim.validate{s={s,'s'}} return s:match('^%s*(.*%S)') or '' end @@ -186,13 +184,13 @@ end --@param s String to escape --@returns %-escaped pattern string function vim.pesc(s) - assert(type(s) == 'string', string.format("Expected string, got %s", type(s))) + vim.validate{s={s,'s'}} return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1') end --- Validates a parameter specification (types and values). --- ---- Examples: +--- Usage example: ---
 ---  function user.new(name, age, hobbies)
 ---    vim.validate{
@@ -202,26 +200,29 @@ end
 ---    }
 ---    ...
 ---  end
---
----  vim.validate{ arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
+--- 
+--- +--- Examples with explicit argument values (can be run directly): +---
+---  vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
 ---     => NOP (success)
+---
 ---  vim.validate{arg1={1, 'table'}}
----     => error("arg1: expected table, got number")
----  vim.validate{arg1={{'foo'}, 'table'}, arg2={1, 'string'}}
----     => error("arg2: expected string, got number")
+---     => error('arg1: expected table, got number')
+---
 ---  vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}}
----     => error("arg1: expected even number, got 3")
+---     => error('arg1: expected even number, got 3')
 --- 
--- --@param opt Map of parameter names to validations. Each key is a parameter --- name; each value is a tuple in one of these forms: ---- 1. {arg_value, type_name, optional} +--- 1. (arg_value, type_name, optional) --- - arg_value: argument value --- - type_name: string type name, one of: ("table", "t", "string", --- "s", "number", "n", "boolean", "b", "function", "f", "nil", --- "thread", "userdata") --- - optional: (optional) boolean, if true, `nil` is valid ---- 2. {arg_value, fn, msg} +--- 2. (arg_value, fn, msg) --- - arg_value: argument value --- - fn: any function accepting one argument, returns true if and --- only if the argument is valid @@ -234,14 +235,14 @@ vim.validate = (function() ['boolean']='boolean', ['function']='function', ['callable']='callable', ['nil']='nil', ['thread']='thread', ['userdata']='userdata', } - local function type_name(t) + local function _type_name(t) local tname = type_names[t] if tname == nil then error(string.format('invalid type name: %s', tostring(t))) end return tname end - local function is_type(val, t) + local function _is_type(val, t) return t == 'callable' and vim.is_callable(val) or type(val) == t end @@ -255,21 +256,21 @@ vim.validate = (function() local optional = (true == spec[3]) if not vim.is_callable(t) then -- Check type name. - if not (optional or type(val) == 'nil') and not is_type(val, type_name(t)) then - error(string.format("%s: expected %s, got %s", param_name, type_name(t), type(val))) + if (not optional or val ~= nil) and not _is_type(val, _type_name(t)) then + error(string.format("%s: expected %s, got %s", param_name, _type_name(t), type(val))) end elseif not t(val) then -- Check user-provided validation function. - error(string.format("%s: expected %s, got %s", param_name, spec[3], val)) + error(string.format("%s: expected %s, got %s", param_name, (spec[3] or '?'), val)) end end return true end end)() ---- Return whether an object can call be used as a function. +--- Returns true if object `f` can be called as a function. --- ---@param f Any type of variable ---@return Boolean +--@param f Any object +--@return true if `f` is callable, else false function vim.is_callable(f) if type(f) == 'function' then return true end local m = getmetatable(f) -- cgit From 00dc12c5d8454a2d3c6806710f63bbb446076e96 Mon Sep 17 00:00:00 2001 From: Ashkan Kiani Date: Wed, 13 Nov 2019 12:55:26 -0800 Subject: lua LSP client: initial implementation (#11336) Mainly configuration and RPC infrastructure can be considered "done". Specific requests and their callbacks will be improved later (and also served by plugins). There are also some TODO:s for the client itself, like incremental updates. Co-authored by at-tjdevries and at-h-michael, with many review/suggestion contributions. --- runtime/lua/vim/shared.lua | 127 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 126 insertions(+), 1 deletion(-) (limited to 'runtime/lua/vim/shared.lua') diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index e987e07a2a..ff89acc524 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -98,6 +98,38 @@ function vim.split(s,sep,plain) return t end +--- Return a list of all keys used in a table. +--- However, the order of the return table of keys is not guaranteed. +--- +--@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua +--- +--@param t Table +--@returns list of keys +function vim.tbl_keys(t) + assert(type(t) == 'table', string.format("Expected table, got %s", type(t))) + + local keys = {} + for k, _ in pairs(t) do + table.insert(keys, k) + end + return keys +end + +--- Return a list of all values used in a table. +--- However, the order of the return table of values is not guaranteed. +--- +--@param t Table +--@returns list of values +function vim.tbl_values(t) + assert(type(t) == 'table', string.format("Expected table, got %s", type(t))) + + local values = {} + for _, v in pairs(t) do + table.insert(values, v) + end + return values +end + --- Checks if a list-like (vector) table contains `value`. --- --@param t Table to check @@ -114,6 +146,16 @@ function vim.tbl_contains(t, value) return false end +-- Returns true if the table is empty, and contains no indexed or keyed values. +-- +--@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua +-- +--@param t Table to check +function vim.tbl_isempty(t) + assert(type(t) == 'table', string.format("Expected table, got %s", type(t))) + return next(t) == nil +end + --- Merges two or more map-like tables. --- --@see |extend()| @@ -145,13 +187,69 @@ function vim.tbl_extend(behavior, ...) return ret end +--- Deep compare values for equality +function vim.deep_equal(a, b) + if a == b then return true end + if type(a) ~= type(b) then return false end + if type(a) == 'table' then + -- TODO improve this algorithm's performance. + for k, v in pairs(a) do + if not vim.deep_equal(v, b[k]) then + return false + end + end + for k, v in pairs(b) do + if not vim.deep_equal(v, a[k]) then + return false + end + end + return true + end + return false +end + +--- Add the reverse lookup values to an existing table. +--- For example: +--- `tbl_add_reverse_lookup { A = 1 } == { [1] = 'A', A = 1 }` +-- +--Do note that it *modifies* the input. +--@param o table The table to add the reverse to. +function vim.tbl_add_reverse_lookup(o) + local keys = vim.tbl_keys(o) + for _, k in ipairs(keys) do + local v = o[k] + if o[v] then + error(string.format("The reverse lookup found an existing value for %q while processing key %q", tostring(v), tostring(k))) + end + o[v] = k + end + return o +end + +--- Extends a list-like table with the values of another list-like table. +--- +--NOTE: This *mutates* dst! +--@see |extend()| +--- +--@param dst The list which will be modified and appended to. +--@param src The list from which values will be inserted. +function vim.list_extend(dst, src) + assert(type(dst) == 'table', "dst must be a table") + assert(type(src) == 'table', "src must be a table") + for _, v in ipairs(src) do + table.insert(dst, v) + end + return dst +end + --- Creates a copy of a list-like table such that any nested tables are --- "unrolled" and appended to the result. --- +--@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua +--- --@param t List-like table --@returns Flattened copy of the given list-like table. function vim.tbl_flatten(t) - -- From https://github.com/premake/premake-core/blob/master/src/base/table.lua local result = {} local function _tbl_flatten(_t) local n = #_t @@ -168,6 +266,32 @@ function vim.tbl_flatten(t) return result end +-- Determine whether a Lua table can be treated as an array. +--- +--@params Table +--@returns true: A non-empty array, false: A non-empty table, nil: An empty table +function vim.tbl_islist(t) + if type(t) ~= 'table' then + return false + end + + local count = 0 + + for k, _ in pairs(t) do + if type(k) == "number" then + count = count + 1 + else + return false + end + end + + if count > 0 then + return true + else + return nil + end +end + --- Trim whitespace (Lua pattern "%s") from both sides of a string. --- --@see https://www.lua.org/pil/20.2.html @@ -279,3 +403,4 @@ function vim.is_callable(f) end return vim +-- vim:sw=2 ts=2 et -- cgit From b984f613c1e8dadbe59bf0d7093a6ed12af61b37 Mon Sep 17 00:00:00 2001 From: Ashkan Kiani Date: Wed, 20 Nov 2019 17:09:21 -0800 Subject: Extend list_extend to take start/finish. --- runtime/lua/vim/shared.lua | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) (limited to 'runtime/lua/vim/shared.lua') diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index ff89acc524..25287ed1aa 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -226,18 +226,25 @@ function vim.tbl_add_reverse_lookup(o) return o end ---- Extends a list-like table with the values of another list-like table. ---- ---NOTE: This *mutates* dst! ---@see |extend()| ---- ---@param dst The list which will be modified and appended to. ---@param src The list from which values will be inserted. -function vim.list_extend(dst, src) - assert(type(dst) == 'table', "dst must be a table") - assert(type(src) == 'table', "src must be a table") - for _, v in ipairs(src) do - table.insert(dst, v) +-- Extends a list-like table with the values of another list-like table. +-- +-- NOTE: This *mutates* dst! +-- @see |extend()| +-- +-- @param dst list which will be modified and appended to. +-- @param src list from which values will be inserted. +-- @param start Start index on src. defaults to 1 +-- @param finish Final index on src. defaults to #src +-- @returns dst +function vim.list_extend(dst, src, start, finish) + vim.validate { + dst = {dst, 't'}; + src = {src, 't'}; + start = {start, 'n', true}; + finish = {finish, 'n', true}; + } + for i = start or 1, finish or #src do + table.insert(dst, src[i]) end return dst end -- cgit From d0d38fc36e0c1602186aa540417070fa6c1e2746 Mon Sep 17 00:00:00 2001 From: Ashkan Kiani Date: Sun, 24 Nov 2019 02:28:48 -0800 Subject: Lua: vim.env, vim.{g,v,w,bo,wo} #11442 - Add vim variable meta accessors: vim.env, vim.{g,v,w,bo,wo} - Redo gen_char_blob to generate multiple blobs instead of just one so that multiple Lua modules can be inlined. - Reorder vim.lua inclusion so that it can use previously defined C functions and utility functions like vim.shared and vim.inspect things. - Inline shared.lua into nvim, but also keep it available in runtime. --- runtime/lua/vim/shared.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runtime/lua/vim/shared.lua') diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index ff89acc524..6aa5f3bd9b 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -4,7 +4,7 @@ -- test-suite. If, in the future, Nvim itself is used to run the test-suite -- instead of "vanilla Lua", these functions could move to src/nvim/lua/vim.lua -local vim = {} +local vim = vim or {} --- Returns a deep copy of the given object. Non-table objects are copied as --- in a typical Lua assignment, whereas table objects are copied recursively. -- cgit From fd5710ae9a3bcbc0f9cbb71de9e39253350ff09c Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Mon, 25 Nov 2019 01:08:02 -0800 Subject: doc + extmarks tweaks #11421 - nvim_buf_get_extmarks: rename "amount" => "limit" - rename `set_extmark_index_from_obj` --- runtime/lua/vim/shared.lua | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) (limited to 'runtime/lua/vim/shared.lua') diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index 1912d3708d..631dd04c35 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -226,16 +226,17 @@ function vim.tbl_add_reverse_lookup(o) return o end --- Extends a list-like table with the values of another list-like table. --- --- NOTE: This *mutates* dst! --- @see |extend()| --- --- @param dst list which will be modified and appended to. --- @param src list from which values will be inserted. --- @param start Start index on src. defaults to 1 --- @param finish Final index on src. defaults to #src --- @returns dst +--- Extends a list-like table with the values of another list-like table. +--- +--- NOTE: This mutates dst! +--- +--@see |vim.tbl_extend()| +--- +--@param dst list which will be modified and appended to. +--@param src list from which values will be inserted. +--@param start Start index on src. defaults to 1 +--@param finish Final index on src. defaults to #src +--@returns dst function vim.list_extend(dst, src, start, finish) vim.validate { dst = {dst, 't'}; -- cgit From 70b606166640d043fc7b78a52b89ff1bba798b6a Mon Sep 17 00:00:00 2001 From: Ashkan Kiani Date: Sun, 1 Dec 2019 05:32:55 -0800 Subject: Add vim.startswith and vim.endswith (#11248) --- runtime/lua/vim/shared.lua | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'runtime/lua/vim/shared.lua') diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index 631dd04c35..b5b04d7757 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -320,6 +320,26 @@ function vim.pesc(s) return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1') end +--- Test if `prefix` is a prefix of `s` for strings. +-- +-- @param s String to check +-- @param prefix Potential prefix +-- @return boolean True if prefix is a prefix of s +function vim.startswith(s, prefix) + vim.validate { s = {s, 's'}; prefix = {prefix, 's'}; } + return s:sub(1, #prefix) == prefix +end + +--- Test if `suffix` is a suffix of `s` for strings. +-- +-- @param s String to check +-- @param suffix Potential suffix +-- @return boolean True if suffix is a suffix of s +function vim.endswith(s, suffix) + vim.validate { s = {s, 's'}; suffix = {suffix, 's'}; } + return #suffix == 0 or s:sub(-#suffix) == suffix +end + --- Validates a parameter specification (types and values). --- --- Usage example: -- cgit