build: enable lintlua for src/ dir #26395

Problem:
Not all Lua code is checked by stylua. Automating code-style is an
important mechanism for reducing time spent on accidental
(non-essential) complexity.

Solution:
- Enable lintlua for `src/` directory.

followup to 517f0cc634
This commit is contained in:
Justin M. Keyes 2023-12-04 13:31:57 -08:00 committed by GitHub
parent 517f0cc634
commit 45fe4d11ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 3224 additions and 2978 deletions

View File

@ -2,5 +2,4 @@
/runtime/lua/coxpcall.lua
/runtime/lua/vim/_meta
/runtime/lua/vim/re.lua
/src
/test

View File

@ -233,7 +233,7 @@ add_glob_target(
TARGET lintlua-stylua
COMMAND ${STYLUA_PRG}
FLAGS --color=always --check --respect-ignores
GLOB_DIRS runtime/ scripts/
GLOB_DIRS runtime/ scripts/ src/
GLOB_PAT *.lua
TOUCH_STRATEGY SINGLE)
@ -260,7 +260,7 @@ add_glob_target(
TARGET formatlua
COMMAND ${STYLUA_PRG}
FLAGS --respect-ignores
GLOB_DIRS runtime/ scripts/
GLOB_DIRS runtime/ scripts/ src/
GLOB_PAT *.lua)
add_custom_target(format)

View File

@ -1,69 +1,69 @@
local deprecated_aliases = {
nvim_buf_add_highlight="buffer_add_highlight",
nvim_buf_clear_highlight="buffer_clear_highlight",
nvim_buf_get_lines="buffer_get_lines",
nvim_buf_get_mark="buffer_get_mark",
nvim_buf_get_name="buffer_get_name",
nvim_buf_get_number="buffer_get_number",
nvim_buf_get_option="buffer_get_option",
nvim_buf_get_var="buffer_get_var",
nvim_buf_is_valid="buffer_is_valid",
nvim_buf_line_count="buffer_line_count",
nvim_buf_set_lines="buffer_set_lines",
nvim_buf_set_name="buffer_set_name",
nvim_buf_set_option="buffer_set_option",
nvim_call_function="vim_call_function",
nvim_command="vim_command",
nvim_command_output="vim_command_output",
nvim_del_current_line="vim_del_current_line",
nvim_err_write="vim_err_write",
nvim_err_writeln="vim_report_error",
nvim_eval="vim_eval",
nvim_feedkeys="vim_feedkeys",
nvim_get_api_info="vim_get_api_info",
nvim_get_color_by_name="vim_name_to_color",
nvim_get_color_map="vim_get_color_map",
nvim_get_current_buf="vim_get_current_buffer",
nvim_get_current_line="vim_get_current_line",
nvim_get_current_tabpage="vim_get_current_tabpage",
nvim_get_current_win="vim_get_current_window",
nvim_get_option="vim_get_option",
nvim_get_var="vim_get_var",
nvim_get_vvar="vim_get_vvar",
nvim_input="vim_input",
nvim_list_bufs="vim_get_buffers",
nvim_list_runtime_paths="vim_list_runtime_paths",
nvim_list_tabpages="vim_get_tabpages",
nvim_list_wins="vim_get_windows",
nvim_out_write="vim_out_write",
nvim_replace_termcodes="vim_replace_termcodes",
nvim_set_current_buf="vim_set_current_buffer",
nvim_set_current_dir="vim_change_directory",
nvim_set_current_line="vim_set_current_line",
nvim_set_current_tabpage="vim_set_current_tabpage",
nvim_set_current_win="vim_set_current_window",
nvim_set_option="vim_set_option",
nvim_strwidth="vim_strwidth",
nvim_subscribe="vim_subscribe",
nvim_tabpage_get_var="tabpage_get_var",
nvim_tabpage_get_win="tabpage_get_window",
nvim_tabpage_is_valid="tabpage_is_valid",
nvim_tabpage_list_wins="tabpage_get_windows",
nvim_ui_detach="ui_detach",
nvim_ui_try_resize="ui_try_resize",
nvim_unsubscribe="vim_unsubscribe",
nvim_win_get_buf="window_get_buffer",
nvim_win_get_cursor="window_get_cursor",
nvim_win_get_height="window_get_height",
nvim_win_get_option="window_get_option",
nvim_win_get_position="window_get_position",
nvim_win_get_tabpage="window_get_tabpage",
nvim_win_get_var="window_get_var",
nvim_win_get_width="window_get_width",
nvim_win_is_valid="window_is_valid",
nvim_win_set_cursor="window_set_cursor",
nvim_win_set_height="window_set_height",
nvim_win_set_option="window_set_option",
nvim_win_set_width="window_set_width",
nvim_buf_add_highlight = 'buffer_add_highlight',
nvim_buf_clear_highlight = 'buffer_clear_highlight',
nvim_buf_get_lines = 'buffer_get_lines',
nvim_buf_get_mark = 'buffer_get_mark',
nvim_buf_get_name = 'buffer_get_name',
nvim_buf_get_number = 'buffer_get_number',
nvim_buf_get_option = 'buffer_get_option',
nvim_buf_get_var = 'buffer_get_var',
nvim_buf_is_valid = 'buffer_is_valid',
nvim_buf_line_count = 'buffer_line_count',
nvim_buf_set_lines = 'buffer_set_lines',
nvim_buf_set_name = 'buffer_set_name',
nvim_buf_set_option = 'buffer_set_option',
nvim_call_function = 'vim_call_function',
nvim_command = 'vim_command',
nvim_command_output = 'vim_command_output',
nvim_del_current_line = 'vim_del_current_line',
nvim_err_write = 'vim_err_write',
nvim_err_writeln = 'vim_report_error',
nvim_eval = 'vim_eval',
nvim_feedkeys = 'vim_feedkeys',
nvim_get_api_info = 'vim_get_api_info',
nvim_get_color_by_name = 'vim_name_to_color',
nvim_get_color_map = 'vim_get_color_map',
nvim_get_current_buf = 'vim_get_current_buffer',
nvim_get_current_line = 'vim_get_current_line',
nvim_get_current_tabpage = 'vim_get_current_tabpage',
nvim_get_current_win = 'vim_get_current_window',
nvim_get_option = 'vim_get_option',
nvim_get_var = 'vim_get_var',
nvim_get_vvar = 'vim_get_vvar',
nvim_input = 'vim_input',
nvim_list_bufs = 'vim_get_buffers',
nvim_list_runtime_paths = 'vim_list_runtime_paths',
nvim_list_tabpages = 'vim_get_tabpages',
nvim_list_wins = 'vim_get_windows',
nvim_out_write = 'vim_out_write',
nvim_replace_termcodes = 'vim_replace_termcodes',
nvim_set_current_buf = 'vim_set_current_buffer',
nvim_set_current_dir = 'vim_change_directory',
nvim_set_current_line = 'vim_set_current_line',
nvim_set_current_tabpage = 'vim_set_current_tabpage',
nvim_set_current_win = 'vim_set_current_window',
nvim_set_option = 'vim_set_option',
nvim_strwidth = 'vim_strwidth',
nvim_subscribe = 'vim_subscribe',
nvim_tabpage_get_var = 'tabpage_get_var',
nvim_tabpage_get_win = 'tabpage_get_window',
nvim_tabpage_is_valid = 'tabpage_is_valid',
nvim_tabpage_list_wins = 'tabpage_get_windows',
nvim_ui_detach = 'ui_detach',
nvim_ui_try_resize = 'ui_try_resize',
nvim_unsubscribe = 'vim_unsubscribe',
nvim_win_get_buf = 'window_get_buffer',
nvim_win_get_cursor = 'window_get_cursor',
nvim_win_get_height = 'window_get_height',
nvim_win_get_option = 'window_get_option',
nvim_win_get_position = 'window_get_position',
nvim_win_get_tabpage = 'window_get_tabpage',
nvim_win_get_var = 'window_get_var',
nvim_win_get_width = 'window_get_width',
nvim_win_is_valid = 'window_is_valid',
nvim_win_set_cursor = 'window_set_cursor',
nvim_win_set_height = 'window_set_height',
nvim_win_set_option = 'window_set_option',
nvim_win_set_width = 'window_set_width',
}
return deprecated_aliases

View File

@ -134,19 +134,19 @@ return {
aliases = {
{
'BufCreate',
'BufAdd'
'BufAdd',
},
{
'BufRead',
'BufReadPost'
'BufReadPost',
},
{
'BufWrite',
'BufWritePre'
'BufWritePre',
},
{
'FileEncoding',
'EncodingChanged'
'EncodingChanged',
},
},
-- List of nvim-specific events or aliases for the purpose of generating

View File

@ -2114,7 +2114,7 @@ M.funcs = {
name = 'execute',
params = {
{ 'command', 'string|string[]' },
{ 'silent', "''|'silent'|'silent!'" }
{ 'silent', "''|'silent'|'silent!'" },
},
returns = 'string',
signature = 'execute({command} [, {silent}])',
@ -4519,7 +4519,7 @@ M.funcs = {
name = 'getwininfo',
params = { { 'winid', 'integer' } },
signature = 'getwininfo([{winid}])',
returns = 'vim.fn.getwininfo.ret.item[]'
returns = 'vim.fn.getwininfo.ret.item[]',
},
getwinpos = {
args = { 0, 1 },
@ -6297,7 +6297,7 @@ M.funcs = {
]],
name = 'maplist',
params = {},
signature = 'maplist([{abbr}])'
signature = 'maplist([{abbr}])',
},
mapnew = {
args = 2,
@ -9905,7 +9905,7 @@ M.funcs = {
name = 'sign_jump',
params = { { 'id', 'integer' }, { 'group', 'string' }, { 'buf', 'integer|string' } },
signature = 'sign_jump({id}, {group}, {buf})',
returns = 'integer'
returns = 'integer',
},
sign_place = {
args = { 4, 5 },
@ -9968,7 +9968,7 @@ M.funcs = {
{ 'dict', 'vim.fn.sign_place.dict' },
},
signature = 'sign_place({id}, {group}, {name}, {buf} [, {dict}])',
returns = 'integer'
returns = 'integer',
},
sign_placelist = {
args = 1,
@ -10035,7 +10035,7 @@ M.funcs = {
name = 'sign_placelist',
params = { { 'list', 'vim.fn.sign_placelist.list.item[]' } },
signature = 'sign_placelist({list})',
returns = 'integer[]'
returns = 'integer[]',
},
sign_undefine = {
args = { 0, 1 },
@ -12698,7 +12698,7 @@ M.funcs = {
name = 'winsaveview',
params = {},
signature = 'winsaveview()',
returns = 'vim.fn.winsaveview.ret'
returns = 'vim.fn.winsaveview.ret',
},
winwidth = {
args = 1,

View File

@ -35,7 +35,7 @@ local FILE1 = bit.bor(FILES, NOSPC)
module.flags = {
RANGE = RANGE,
DFLALL = DFLALL,
PREVIEW = PREVIEW
PREVIEW = PREVIEW,
}
-- The following table is described in ex_cmds_defs.h file.

View File

@ -17,50 +17,70 @@ local fill = ws ^ 0
local c_comment = P('//') * (not_nl ^ 0)
local c_preproc = P('#') * (not_nl ^ 0)
local dllexport = P('DLLEXPORT') * (ws ^ 1)
local typed_container =
(P('ArrayOf(') + P('DictionaryOf(') + P('Dict(')) * ((any - P(')')) ^ 1) * P(')')
local c_id = (
typed_container +
(letter * (alpha ^ 0))
)
local typed_container = (P('ArrayOf(') + P('DictionaryOf(') + P('Dict('))
* ((any - P(')')) ^ 1)
* P(')')
local c_id = (typed_container + (letter * (alpha ^ 0)))
local c_void = P('void')
local c_param_type = (
((P('Error') * fill * P('*') * fill) * Cc('error')) +
((P('Arena') * fill * P('*') * fill) * Cc('arena')) +
((P('lua_State') * fill * P('*') * fill) * Cc('lstate')) +
C((P('const ') ^ -1) * (c_id) * (ws ^ 1) * P('*')) +
(C(c_id) * (ws ^ 1))
((P('Error') * fill * P('*') * fill) * Cc('error'))
+ ((P('Arena') * fill * P('*') * fill) * Cc('arena'))
+ ((P('lua_State') * fill * P('*') * fill) * Cc('lstate'))
+ C((P('const ') ^ -1) * c_id * (ws ^ 1) * P('*'))
+ (C(c_id) * (ws ^ 1))
)
local c_type = (C(c_void) * (ws ^ 1)) + c_param_type
local c_param = Ct(c_param_type * C(c_id))
local c_param_list = c_param * (fill * (P(',') * fill * c_param) ^ 0)
local c_params = Ct(c_void + c_param_list)
local c_proto = Ct(
(dllexport ^ -1) *
Cg(c_type, 'return_type') * Cg(c_id, 'name') *
fill * P('(') * fill * Cg(c_params, 'parameters') * fill * P(')') *
Cg(Cc(false), 'fast') *
(fill * Cg((P('FUNC_API_SINCE(') * C(num ^ 1)) * P(')'), 'since') ^ -1) *
(fill * Cg((P('FUNC_API_DEPRECATED_SINCE(') * C(num ^ 1)) * P(')'),
'deprecated_since') ^ -1) *
(fill * Cg((P('FUNC_API_FAST') * Cc(true)), 'fast') ^ -1) *
(fill * Cg((P('FUNC_API_NOEXPORT') * Cc(true)), 'noexport') ^ -1) *
(fill * Cg((P('FUNC_API_REMOTE_ONLY') * Cc(true)), 'remote_only') ^ -1) *
(fill * Cg((P('FUNC_API_LUA_ONLY') * Cc(true)), 'lua_only') ^ -1) *
(fill * (Cg(P('FUNC_API_TEXTLOCK_ALLOW_CMDWIN') * Cc(true), 'textlock_allow_cmdwin') +
Cg(P('FUNC_API_TEXTLOCK') * Cc(true), 'textlock')) ^ -1) *
(fill * Cg((P('FUNC_API_REMOTE_IMPL') * Cc(true)), 'remote_impl') ^ -1) *
(fill * Cg((P('FUNC_API_COMPOSITOR_IMPL') * Cc(true)), 'compositor_impl') ^ -1) *
(fill * Cg((P('FUNC_API_CLIENT_IMPL') * Cc(true)), 'client_impl') ^ -1) *
(fill * Cg((P('FUNC_API_CLIENT_IGNORE') * Cc(true)), 'client_ignore') ^ -1) *
fill * P(';')
(dllexport ^ -1)
* Cg(c_type, 'return_type')
* Cg(c_id, 'name')
* fill
* P('(')
* fill
* Cg(c_params, 'parameters')
* fill
* P(')')
* Cg(Cc(false), 'fast')
* (fill * Cg((P('FUNC_API_SINCE(') * C(num ^ 1)) * P(')'), 'since') ^ -1)
* (fill * Cg((P('FUNC_API_DEPRECATED_SINCE(') * C(num ^ 1)) * P(')'), 'deprecated_since') ^ -1)
* (fill * Cg((P('FUNC_API_FAST') * Cc(true)), 'fast') ^ -1)
* (fill * Cg((P('FUNC_API_NOEXPORT') * Cc(true)), 'noexport') ^ -1)
* (fill * Cg((P('FUNC_API_REMOTE_ONLY') * Cc(true)), 'remote_only') ^ -1)
* (fill * Cg((P('FUNC_API_LUA_ONLY') * Cc(true)), 'lua_only') ^ -1)
* (fill * (Cg(P('FUNC_API_TEXTLOCK_ALLOW_CMDWIN') * Cc(true), 'textlock_allow_cmdwin') + Cg(
P('FUNC_API_TEXTLOCK') * Cc(true),
'textlock'
)) ^ -1)
* (fill * Cg((P('FUNC_API_REMOTE_IMPL') * Cc(true)), 'remote_impl') ^ -1)
* (fill * Cg((P('FUNC_API_COMPOSITOR_IMPL') * Cc(true)), 'compositor_impl') ^ -1)
* (fill * Cg((P('FUNC_API_CLIENT_IMPL') * Cc(true)), 'client_impl') ^ -1)
* (fill * Cg((P('FUNC_API_CLIENT_IGNORE') * Cc(true)), 'client_ignore') ^ -1)
* fill
* P(';')
)
local c_field = Ct(Cg(c_id, 'type') * ws * Cg(c_id, 'name') * fill * P(';') * fill)
local c_keyset = Ct(
P('typedef') * ws * P('struct') * fill * P('{') * fill *
Cg(Ct(c_field ^ 1), 'fields') *
P('}') * fill * P('Dict') * fill * P('(') * Cg(c_id, 'keyset_name') * fill * P(')') * P(';'))
P('typedef')
* ws
* P('struct')
* fill
* P('{')
* fill
* Cg(Ct(c_field ^ 1), 'fields')
* P('}')
* fill
* P('Dict')
* fill
* P('(')
* Cg(c_id, 'keyset_name')
* fill
* P(')')
* P(';')
)
local grammar = Ct((c_proto + c_comment + c_preproc + ws + c_keyset) ^ 1)
return { grammar = grammar, typed_container = typed_container }

View File

@ -28,11 +28,15 @@ local function startswith(String,Start)
end
local function add_function(fn)
local public = startswith(fn.name, "nvim_") or fn.deprecated_since
local public = startswith(fn.name, 'nvim_') or fn.deprecated_since
if public and not fn.noexport then
functions[#functions + 1] = fn
function_names[fn.name] = true
if #fn.parameters >= 2 and fn.parameters[2][1] == 'Array' and fn.parameters[2][2] == 'uidata' then
if
#fn.parameters >= 2
and fn.parameters[2][1] == 'Array'
and fn.parameters[2][2] == 'uidata'
then
-- function receives the "args" as a parameter
fn.receives_array_args = true
-- remove the args parameter
@ -80,14 +84,17 @@ local function add_keyset(val)
if i > 1 then
error("'is_set__{type}_' must be first if present")
elseif field.name ~= is_set_name then
error(val.keyset_name..": name of first key should be "..is_set_name)
error(val.keyset_name .. ': name of first key should be ' .. is_set_name)
elseif field.type ~= 'OptionalKeys' then
error("'" .. is_set_name .. "' must have type 'OptionalKeys'")
end
has_optional = true
end
end
table.insert(keysets, {name=val.keyset_name, keys=keys, types=types, has_optional=has_optional})
table.insert(
keysets,
{ name = val.keyset_name, keys = keys, types = types, has_optional = has_optional }
)
end
-- read each input file, parse and append to the api metadata
@ -123,14 +130,14 @@ end
-- Export functions under older deprecated names.
-- These will be removed eventually.
local deprecated_aliases = require("api.dispatch_deprecated")
local deprecated_aliases = require('api.dispatch_deprecated')
for _, f in ipairs(shallowcopy(functions)) do
local ismethod = false
if startswith(f.name, "nvim_") then
if startswith(f.name, "nvim__") or f.name == "nvim_error_event" then
if startswith(f.name, 'nvim_') then
if startswith(f.name, 'nvim__') or f.name == 'nvim_error_event' then
f.since = -1
elseif f.since == nil then
print("Function "..f.name.." lacks since field.\n")
print('Function ' .. f.name .. ' lacks since field.\n')
os.exit(1)
end
f.since = tonumber(f.since)
@ -138,16 +145,16 @@ for _,f in ipairs(shallowcopy(functions)) do
f.deprecated_since = tonumber(f.deprecated_since)
end
if startswith(f.name, "nvim_buf_") then
if startswith(f.name, 'nvim_buf_') then
ismethod = true
elseif startswith(f.name, "nvim_win_") then
elseif startswith(f.name, 'nvim_win_') then
ismethod = true
elseif startswith(f.name, "nvim_tabpage_") then
elseif startswith(f.name, 'nvim_tabpage_') then
ismethod = true
end
f.remote = f.remote_only or not f.lua_only
f.lua = f.lua_only or not f.remote_only
f.eval = (not f.lua_only) and (not f.remote_only)
f.eval = (not f.lua_only) and not f.remote_only
else
f.deprecated_since = tonumber(f.deprecated_since)
assert(f.deprecated_since == 1)
@ -159,17 +166,22 @@ for _,f in ipairs(shallowcopy(functions)) do
if newname ~= nil then
if function_names[newname] then
-- duplicate
print("Function "..f.name.." has deprecated alias\n"
..newname.." which has a separate implementation.\n"..
"Please remove it from src/nvim/api/dispatch_deprecated.lua")
print(
'Function '
.. f.name
.. ' has deprecated alias\n'
.. newname
.. ' which has a separate implementation.\n'
.. 'Please remove it from src/nvim/api/dispatch_deprecated.lua'
)
os.exit(1)
end
local newf = shallowcopy(f)
newf.name = newname
if newname == "ui_try_resize" then
if newname == 'ui_try_resize' then
-- The return type was incorrectly set to Object in 0.1.5.
-- Keep it that way for clients that rely on this.
newf.return_type = "Object"
newf.return_type = 'Object'
end
newf.impl_name = f.name
newf.lua = false
@ -181,21 +193,20 @@ for _,f in ipairs(shallowcopy(functions)) do
end
-- don't expose internal attributes like "impl_name" in public metadata
local exported_attributes = {'name', 'return_type', 'method',
'since', 'deprecated_since'}
local exported_attributes = { 'name', 'return_type', 'method', 'since', 'deprecated_since' }
local exported_functions = {}
for _, f in ipairs(functions) do
if not (startswith(f.name, "nvim__") or f.name == "nvim_error_event" or f.name == "redraw") then
if not (startswith(f.name, 'nvim__') or f.name == 'nvim_error_event' or f.name == 'redraw') then
local f_exported = {}
for _, attr in ipairs(exported_attributes) do
f_exported[attr] = f[attr]
end
f_exported.parameters = {}
for i, param in ipairs(f.parameters) do
if param[1] == "DictionaryOf(LuaRef)" then
param = {"Dictionary", param[2]}
elseif startswith(param[1], "Dict(") then
param = {"Dictionary", param[2]}
if param[1] == 'DictionaryOf(LuaRef)' then
param = { 'Dictionary', param[2] }
elseif startswith(param[1], 'Dict(') then
param = { 'Dictionary', param[2] }
end
f_exported.parameters[i] = param
end
@ -203,12 +214,11 @@ for _,f in ipairs(functions) do
end
end
-- serialize the API metadata using msgpack and embed into the resulting
-- binary for easy querying by clients
local funcs_metadata_output = io.open(funcs_metadata_outputf, 'wb')
local packed = mpack.encode(exported_functions)
local dump_bin_array = require("generators.dump_bin_array")
local dump_bin_array = require('generators.dump_bin_array')
dump_bin_array(funcs_metadata_output, 'funcs_metadata', packed)
funcs_metadata_output:close()
@ -252,39 +262,51 @@ for _,k in ipairs(keysets) do
for i = 1, #k.keys do
-- some keys, like "register" are c keywords and get
-- escaped with a trailing _ in the struct.
if vim.endswith(k.keys[i], "_") then
if vim.endswith(k.keys[i], '_') then
local orig = k.keys[i]
k.keys[i] = string.sub(k.keys[i],1, #(k.keys[i]) - 1)
k.keys[i] = string.sub(k.keys[i], 1, #k.keys[i] - 1)
c_name[k.keys[i]] = orig
k.types[k.keys[i]] = k.types[orig]
end
end
local neworder, hashfun = hashy.hashy_hash(k.name, k.keys, function(idx)
return k.name.."_table["..idx.."].str"
return k.name .. '_table[' .. idx .. '].str'
end)
keysets_defs:write("extern KeySetLink "..k.name.."_table[];\n")
keysets_defs:write('extern KeySetLink ' .. k.name .. '_table[];\n')
local function typename(type)
if type ~= nil then
return "kObjectType"..type
return 'kObjectType' .. type
else
return "kObjectTypeNil"
return 'kObjectTypeNil'
end
end
output:write("KeySetLink "..k.name.."_table[] = {\n")
output:write('KeySetLink ' .. k.name .. '_table[] = {\n')
for i, key in ipairs(neworder) do
local ind = -1
if k.has_optional then
ind = i
keysets_defs:write("#define KEYSET_OPTIDX_"..k.name.."__"..key.." "..ind.."\n")
keysets_defs:write('#define KEYSET_OPTIDX_' .. k.name .. '__' .. key .. ' ' .. ind .. '\n')
end
output:write(' {"'..key..'", offsetof(KeyDict_'..k.name..", "..(c_name[key] or key).."), "..typename(k.types[key])..", "..ind.."},\n")
output:write(
' {"'
.. key
.. '", offsetof(KeyDict_'
.. k.name
.. ', '
.. (c_name[key] or key)
.. '), '
.. typename(k.types[key])
.. ', '
.. ind
.. '},\n'
)
end
output:write(' {NULL, 0, kObjectTypeNil, -1},\n')
output:write("};\n\n")
output:write('};\n\n')
output:write(hashfun)
@ -299,14 +321,16 @@ KeySetLink *KeyDict_]]..k.name..[[_get_field(const char *str, size_t len)
}
]])
keysets_defs:write("#define api_free_keydict_"..k.name.."(x) api_free_keydict(x, "..k.name.."_table)\n")
keysets_defs:write(
'#define api_free_keydict_' .. k.name .. '(x) api_free_keydict(x, ' .. k.name .. '_table)\n'
)
end
local function real_type(type)
local rv = type
local rmatch = string.match(type, "Dict%(([_%w]+)%)")
local rmatch = string.match(type, 'Dict%(([_%w]+)%)')
if rmatch then
return "KeyDict_"..rmatch
return 'KeyDict_' .. rmatch
elseif c_grammar.typed_container:match(rv) then
if rv:match('Array') then
rv = 'Array'
@ -333,7 +357,9 @@ for i = 1, #functions do
if fn.impl_name == nil and fn.remote then
local args = {}
output:write('Object handle_'..fn.name..'(uint64_t channel_id, Array args, Arena* arena, Error *error)')
output:write(
'Object handle_' .. fn.name .. '(uint64_t channel_id, Array args, Arena* arena, Error *error)'
)
output:write('\n{')
output:write('\n#ifdef NVIM_LOG_DEBUG')
output:write('\n DLOG("RPC: ch %" PRIu64 ": invoke ' .. fn.name .. '", channel_id);')
@ -349,8 +375,12 @@ for i = 1, #functions do
output:write('\n')
if not fn.receives_array_args then
output:write('\n if (args.size != ' .. #fn.parameters .. ') {')
output:write('\n api_set_error(error, kErrorTypeException, \
"Wrong number of arguments: expecting '..#fn.parameters..' but got %zu", args.size);')
output:write(
'\n api_set_error(error, kErrorTypeException, \
"Wrong number of arguments: expecting '
.. #fn.parameters
.. ' but got %zu", args.size);'
)
output:write('\n goto cleanup;')
output:write('\n }\n')
end
@ -367,47 +397,113 @@ for i = 1, #functions do
converted = '&' .. converted
output:write('\n if (args.items[' .. (j - 1) .. '].type == kObjectTypeDictionary) {') --luacheck: ignore 631
output:write('\n memset(' .. converted .. ', 0, sizeof(*' .. converted .. '));') -- TODO: neeeee
output:write('\n if (!api_dict_to_keydict('..converted..', '..rt..'_get_field, args.items['..(j - 1)..'].data.dictionary, error)) {')
output:write(
'\n if (!api_dict_to_keydict('
.. converted
.. ', '
.. rt
.. '_get_field, args.items['
.. (j - 1)
.. '].data.dictionary, error)) {'
)
output:write('\n goto cleanup;')
output:write('\n }')
output:write('\n } else if (args.items['..(j - 1)..'].type == kObjectTypeArray && args.items['..(j - 1)..'].data.array.size == 0) {') --luacheck: ignore 631
output:write(
'\n } else if (args.items['
.. (j - 1)
.. '].type == kObjectTypeArray && args.items['
.. (j - 1)
.. '].data.array.size == 0) {'
) --luacheck: ignore 631
output:write('\n memset(' .. converted .. ', 0, sizeof(*' .. converted .. '));')
output:write('\n } else {')
output:write('\n api_set_error(error, kErrorTypeException, \
"Wrong type for argument '..j..' when calling '..fn.name..', expecting '..param[1]..'");')
output:write(
'\n api_set_error(error, kErrorTypeException, \
"Wrong type for argument '
.. j
.. ' when calling '
.. fn.name
.. ', expecting '
.. param[1]
.. '");'
)
output:write('\n goto cleanup;')
output:write('\n }\n')
else
if rt:match('^Buffer$') or rt:match('^Window$') or rt:match('^Tabpage$') then
-- Buffer, Window, and Tabpage have a specific type, but are stored in integer
output:write('\n if (args.items['..
(j - 1)..'].type == kObjectType'..rt..' && args.items['..(j - 1)..'].data.integer >= 0) {')
output:write('\n '..converted..' = (handle_T)args.items['..(j - 1)..'].data.integer;')
output:write(
'\n if (args.items['
.. (j - 1)
.. '].type == kObjectType'
.. rt
.. ' && args.items['
.. (j - 1)
.. '].data.integer >= 0) {'
)
output:write(
'\n ' .. converted .. ' = (handle_T)args.items[' .. (j - 1) .. '].data.integer;'
)
else
output:write('\n if (args.items[' .. (j - 1) .. '].type == kObjectType' .. rt .. ') {')
output:write('\n '..converted..' = args.items['..(j - 1)..'].data.'..attr_name(rt)..';')
output:write(
'\n '
.. converted
.. ' = args.items['
.. (j - 1)
.. '].data.'
.. attr_name(rt)
.. ';'
)
end
if rt:match('^Buffer$') or rt:match('^Window$') or rt:match('^Tabpage$') or rt:match('^Boolean$') then
if
rt:match('^Buffer$')
or rt:match('^Window$')
or rt:match('^Tabpage$')
or rt:match('^Boolean$')
then
-- accept nonnegative integers for Booleans, Buffers, Windows and Tabpages
output:write('\n } else if (args.items['..
(j - 1)..'].type == kObjectTypeInteger && args.items['..(j - 1)..'].data.integer >= 0) {')
output:write('\n '..converted..' = (handle_T)args.items['..(j - 1)..'].data.integer;')
output:write(
'\n } else if (args.items['
.. (j - 1)
.. '].type == kObjectTypeInteger && args.items['
.. (j - 1)
.. '].data.integer >= 0) {'
)
output:write(
'\n ' .. converted .. ' = (handle_T)args.items[' .. (j - 1) .. '].data.integer;'
)
end
if rt:match('^Float$') then
-- accept integers for Floats
output:write('\n } else if (args.items['..
(j - 1)..'].type == kObjectTypeInteger) {')
output:write('\n '..converted..' = (Float)args.items['..(j - 1)..'].data.integer;')
output:write('\n } else if (args.items[' .. (j - 1) .. '].type == kObjectTypeInteger) {')
output:write(
'\n ' .. converted .. ' = (Float)args.items[' .. (j - 1) .. '].data.integer;'
)
end
-- accept empty lua tables as empty dictionaries
if rt:match('^Dictionary') then
output:write('\n } else if (args.items['..(j - 1)..'].type == kObjectTypeArray && args.items['..(j - 1)..'].data.array.size == 0) {') --luacheck: ignore 631
output:write(
'\n } else if (args.items['
.. (j - 1)
.. '].type == kObjectTypeArray && args.items['
.. (j - 1)
.. '].data.array.size == 0) {'
) --luacheck: ignore 631
output:write('\n ' .. converted .. ' = (Dictionary)ARRAY_DICT_INIT;')
end
output:write('\n } else {')
output:write('\n api_set_error(error, kErrorTypeException, \
"Wrong type for argument '..j..' when calling '..fn.name..', expecting '..param[1]..'");')
output:write(
'\n api_set_error(error, kErrorTypeException, \
"Wrong type for argument '
.. j
.. ' when calling '
.. fn.name
.. ', expecting '
.. param[1]
.. '");'
)
output:write('\n goto cleanup;')
output:write('\n }\n')
end
@ -494,9 +590,9 @@ for i = 1, #functions do
if fn.return_type ~= 'void' then
output:write('\n ret = ' .. string.upper(real_type(fn.return_type)) .. '_OBJ(rv);')
end
output:write('\n\ncleanup:');
output:write('\n\ncleanup:')
output:write('\n return ret;\n}\n\n');
output:write('\n return ret;\n}\n\n')
end
end
@ -506,22 +602,31 @@ for _,fn in ipairs(functions) do
remote_fns[fn.name] = fn
end
end
remote_fns.redraw = {impl_name="ui_client_redraw", fast=true}
remote_fns.redraw = { impl_name = 'ui_client_redraw', fast = true }
local names = vim.tbl_keys(remote_fns)
table.sort(names)
local hashorder, hashfun = hashy.hashy_hash("msgpack_rpc_get_handler_for", names, function (idx)
return "method_handlers["..idx.."].name"
local hashorder, hashfun = hashy.hashy_hash('msgpack_rpc_get_handler_for', names, function(idx)
return 'method_handlers[' .. idx .. '].name'
end)
output:write("const MsgpackRpcRequestHandler method_handlers[] = {\n")
output:write('const MsgpackRpcRequestHandler method_handlers[] = {\n')
for n, name in ipairs(hashorder) do
local fn = remote_fns[name]
fn.handler_id = n - 1
output:write(' { .name = "'..name..'", .fn = handle_'.. (fn.impl_name or fn.name)..
', .fast = '..tostring(fn.fast)..', .arena_return = '..tostring(not not fn.arena_return)..'},\n')
output:write(
' { .name = "'
.. name
.. '", .fn = handle_'
.. (fn.impl_name or fn.name)
.. ', .fast = '
.. tostring(fn.fast)
.. ', .arena_return = '
.. tostring(not not fn.arena_return)
.. '},\n'
)
end
output:write("};\n\n")
output:write('};\n\n')
output:write(hashfun)
output:close()
@ -572,7 +677,10 @@ local lua_c_functions = {}
local function process_function(fn)
local lua_c_function_name = ('nlua_api_%s'):format(fn.name)
write_shifted_output(output, string.format([[
write_shifted_output(
output,
string.format(
[[
static int %s(lua_State *lstate)
{
@ -582,35 +690,52 @@ local function process_function(fn)
api_set_error(&err, kErrorTypeValidation, "Expected %i argument%s");
goto exit_0;
}
]], lua_c_function_name, #fn.parameters, #fn.parameters,
(#fn.parameters == 1) and '' or 's'))
]],
lua_c_function_name,
#fn.parameters,
#fn.parameters,
(#fn.parameters == 1) and '' or 's'
)
)
lua_c_functions[#lua_c_functions + 1] = {
binding = lua_c_function_name,
api=fn.name
api = fn.name,
}
if not fn.fast then
write_shifted_output(output, string.format([[
write_shifted_output(
output,
string.format(
[[
if (!nlua_is_deferred_safe()) {
return luaL_error(lstate, e_luv_api_disabled, "%s");
}
]], fn.name))
]],
fn.name
)
)
end
if fn.textlock then
write_shifted_output(output, [[
write_shifted_output(
output,
[[
if (text_locked()) {
api_set_error(&err, kErrorTypeException, "%s", get_text_locked_msg());
goto exit_0;
}
]])
]]
)
elseif fn.textlock_allow_cmdwin then
write_shifted_output(output, [[
write_shifted_output(
output,
[[
if (textlock != 0 || expr_map_locked()) {
api_set_error(&err, kErrorTypeException, "%s", e_textlock);
goto exit_0;
}
]])
]]
)
end
local cparams = ''
@ -620,33 +745,53 @@ local function process_function(fn)
local cparam = string.format('arg%u', j)
local param_type = real_type(param[1])
local lc_param_type = real_type(param[1]):lower()
local extra = param_type == "Dictionary" and "false, " or ""
if param[1] == "Object" or param[1] == "DictionaryOf(LuaRef)" then
extra = "true, "
local extra = param_type == 'Dictionary' and 'false, ' or ''
if param[1] == 'Object' or param[1] == 'DictionaryOf(LuaRef)' then
extra = 'true, '
end
local errshift = 0
local seterr = ''
if string.match(param_type, '^KeyDict_') then
write_shifted_output(output, string.format([[
%s %s = { 0 }; nlua_pop_keydict(lstate, &%s, %s_get_field, &err_param, &err);]], param_type, cparam, cparam, param_type))
write_shifted_output(
output,
string.format(
[[
%s %s = { 0 }; nlua_pop_keydict(lstate, &%s, %s_get_field, &err_param, &err);]],
param_type,
cparam,
cparam,
param_type
)
)
cparam = '&' .. cparam
errshift = 1 -- free incomplete dict on error
else
write_shifted_output(output, string.format([[
const %s %s = nlua_pop_%s(lstate, %s&err);]], param[1], cparam, param_type, extra))
write_shifted_output(
output,
string.format(
[[
const %s %s = nlua_pop_%s(lstate, %s&err);]],
param[1],
cparam,
param_type,
extra
)
)
seterr = [[
err_param = "]] .. param[2] .. [[";]]
end
write_shifted_output(output, string.format([[
write_shifted_output(
output,
string.format([[
if (ERROR_SET(&err)) {]] .. seterr .. [[
goto exit_%u;
}
]], #fn.parameters - j + errshift))
free_code[#free_code + 1] = ('api_free_%s(%s);'):format(
lc_param_type, cparam)
]], #fn.parameters - j + errshift)
)
free_code[#free_code + 1] = ('api_free_%s(%s);'):format(lc_param_type, cparam)
cparams = cparam .. ', ' .. cparams
end
if fn.receives_channel_id then
@ -654,9 +799,12 @@ local function process_function(fn)
end
if fn.arena_return then
cparams = cparams .. '&arena, '
write_shifted_output(output, [[
write_shifted_output(
output,
[[
Arena arena = ARENA_EMPTY;
]])
]]
)
end
if fn.has_lua_imp then
@ -675,8 +823,7 @@ local function process_function(fn)
if i == 1 and not string.match(real_type(fn.parameters[1][1]), '^KeyDict_') then
free_at_exit_code = free_at_exit_code .. ('\n %s'):format(code)
else
free_at_exit_code = free_at_exit_code .. ('\n exit_%u:\n %s'):format(
rev_i, code)
free_at_exit_code = free_at_exit_code .. ('\n exit_%u:\n %s'):format(rev_i, code)
end
end
local err_throw_code = [[
@ -704,45 +851,86 @@ local function process_function(fn)
end
local free_retval
if fn.arena_return then
free_retval = "arena_mem_free(arena_finish(&arena));"
free_retval = 'arena_mem_free(arena_finish(&arena));'
else
free_retval = "api_free_"..return_type:lower().."(ret);"
free_retval = 'api_free_' .. return_type:lower() .. '(ret);'
end
write_shifted_output(output, string.format([[
write_shifted_output(
output,
string.format(
[[
const %s ret = %s(%s);
]], fn.return_type, fn.name, cparams))
]],
fn.return_type,
fn.name,
cparams
)
)
if fn.has_lua_imp then
-- only push onto the Lua stack if we haven't already
write_shifted_output(output, string.format([[
write_shifted_output(
output,
string.format(
[[
if (lua_gettop(lstate) == 0) {
nlua_push_%s(lstate, ret, true);
}
]], return_type))
]],
return_type
)
)
else
local special = (fn.since ~= nil and fn.since < 11)
write_shifted_output(output, string.format([[
write_shifted_output(
output,
string.format(
[[
nlua_push_%s(lstate, ret, %s);
]], return_type, tostring(special)))
]],
return_type,
tostring(special)
)
)
end
write_shifted_output(output, string.format([[
write_shifted_output(
output,
string.format(
[[
%s
%s
%s
return 1;
]], free_retval, free_at_exit_code, err_throw_code))
]],
free_retval,
free_at_exit_code,
err_throw_code
)
)
else
write_shifted_output(output, string.format([[
write_shifted_output(
output,
string.format(
[[
%s(%s);
%s
%s
return 0;
]], fn.name, cparams, free_at_exit_code, err_throw_code))
]],
fn.name,
cparams,
free_at_exit_code,
err_throw_code
)
)
end
write_shifted_output(output, [[
write_shifted_output(
output,
[[
}
]])
]]
)
end
for _, fn in ipairs(functions) do
@ -751,18 +939,25 @@ for _, fn in ipairs(functions) do
end
end
output:write(string.format([[
output:write(string.format(
[[
void nlua_add_api_functions(lua_State *lstate)
REAL_FATTR_NONNULL_ALL;
void nlua_add_api_functions(lua_State *lstate)
{
lua_createtable(lstate, 0, %u);
]], #lua_c_functions))
]],
#lua_c_functions
))
for _, func in ipairs(lua_c_functions) do
output:write(string.format([[
output:write(string.format(
[[
lua_pushcfunction(lstate, &%s);
lua_setfield(lstate, -2, "%s");]], func.binding, func.api))
lua_setfield(lstate, -2, "%s");]],
func.binding,
func.api
))
end
output:write([[

View File

@ -14,7 +14,7 @@ local hashy = require'generators.hashy'
local function write_signature(output, ev, prefix, notype)
output:write('(' .. prefix)
if prefix == "" and #ev.parameters == 0 then
if prefix == '' and #ev.parameters == 0 then
output:write('void')
end
for j = 1, #ev.parameters do
@ -45,11 +45,13 @@ local function call_ui_event_method(output, ev)
local hlattrs_args_count = 0
if #ev.parameters > 0 then
output:write(' if (args.size < '..(#ev.parameters))
output:write(' if (args.size < ' .. #ev.parameters)
for j = 1, #ev.parameters do
local kind = ev.parameters[j][1]
if kind ~= "Object" then
if kind == 'HlAttrs' then kind = 'Dictionary' end
if kind ~= 'Object' then
if kind == 'HlAttrs' then
kind = 'Dictionary'
end
output:write('\n || args.items[' .. (j - 1) .. '].type != kObjectType' .. kind .. '')
end
end
@ -65,7 +67,13 @@ local function call_ui_event_method(output, ev)
output:write(' ' .. kind .. ' arg_' .. j .. ' = ')
if kind == 'HlAttrs' then
-- The first HlAttrs argument is rgb_attrs and second is cterm_attrs
output:write('ui_client_dict2hlattrs(args.items['..(j-1)..'].data.dictionary, '..(hlattrs_args_count == 0 and 'true' or 'false')..');\n')
output:write(
'ui_client_dict2hlattrs(args.items['
.. (j - 1)
.. '].data.dictionary, '
.. (hlattrs_args_count == 0 and 'true' or 'false')
.. ');\n'
)
hlattrs_args_count = hlattrs_args_count + 1
elseif kind == 'Object' then
output:write('args.items[' .. (j - 1) .. '];\n')
@ -90,13 +98,12 @@ for i = 1, #events do
assert(ev.return_type == 'void')
if ev.since == nil and not ev.noexport then
print("Ui event "..ev.name.." lacks since field.\n")
print('Ui event ' .. ev.name .. ' lacks since field.\n')
os.exit(1)
end
ev.since = tonumber(ev.since)
if not ev.remote_only then
if not ev.remote_impl and not ev.noexport then
remote_output:write('void remote_ui_' .. ev.name)
write_signature(remote_output, ev, 'UI *ui')
@ -120,16 +127,16 @@ for i = 1, #events do
elseif ev.compositor_impl then
call_output:write(' ui_comp_' .. ev.name)
write_signature(call_output, ev, '', true)
call_output:write(";\n")
call_output:write(';\n')
call_output:write(' UI_CALL')
write_signature(call_output, ev, '!ui->composed, ' .. ev.name .. ', ui', true)
call_output:write(";\n")
call_output:write(';\n')
else
call_output:write(' UI_CALL')
write_signature(call_output, ev, 'true, ' .. ev.name .. ', ui', true)
call_output:write(";\n")
call_output:write(';\n')
end
call_output:write("}\n\n")
call_output:write('}\n\n')
end
if ev.compositor_impl then
@ -138,27 +145,31 @@ for i = 1, #events do
call_output:write('\n{\n')
call_output:write(' UI_CALL')
write_signature(call_output, ev, 'ui->composed, ' .. ev.name .. ', ui', true)
call_output:write(";\n")
call_output:write("}\n\n")
call_output:write(';\n')
call_output:write('}\n\n')
end
if (not ev.remote_only) and (not ev.noexport) and (not ev.client_impl) and (not ev.client_ignore) then
if (not ev.remote_only) and not ev.noexport and not ev.client_impl and not ev.client_ignore then
call_ui_event_method(client_output, ev)
end
end
local client_events = {}
for _, ev in ipairs(events) do
if (not ev.noexport) and ((not ev.remote_only) or ev.client_impl) and (not ev.client_ignore) then
if (not ev.noexport) and ((not ev.remote_only) or ev.client_impl) and not ev.client_ignore then
client_events[ev.name] = ev
end
end
local hashorder, hashfun = hashy.hashy_hash("ui_client_handler", vim.tbl_keys(client_events), function (idx)
return "event_handlers["..idx.."].name"
end)
local hashorder, hashfun = hashy.hashy_hash(
'ui_client_handler',
vim.tbl_keys(client_events),
function(idx)
return 'event_handlers[' .. idx .. '].name'
end
)
client_output:write("static const UIClientHandler event_handlers[] = {\n")
client_output:write('static const UIClientHandler event_handlers[] = {\n')
for _, name in ipairs(hashorder) do
client_output:write(' { .name = "' .. name .. '", .fn = ui_client_event_' .. name .. '},\n')
@ -172,8 +183,7 @@ remote_output:close()
client_output:close()
-- don't expose internal attributes like "impl_name" in public metadata
local exported_attributes = {'name', 'parameters',
'since', 'deprecated_since'}
local exported_attributes = { 'name', 'parameters', 'since', 'deprecated_since' }
local exported_events = {}
for _, ev in ipairs(events) do
local ev_exported = {}
@ -191,6 +201,6 @@ for _,ev in ipairs(events) do
end
local packed = mpack.encode(exported_events)
local dump_bin_array = require("generators.dump_bin_array")
local dump_bin_array = require('generators.dump_bin_array')
dump_bin_array(metadata_output, 'ui_events_metadata', packed)
metadata_output:close()

View File

@ -12,7 +12,7 @@ end
local options = {}
while true do
local opt = string.match(arg[1], "^-(%w)")
local opt = string.match(arg[1], '^-(%w)')
if not opt then
break
end
@ -36,28 +36,28 @@ for argi = 2, #arg, 2 do
local source_file = arg[argi]
local modname = arg[argi + 1]
if modnames[modname] then
error(string.format("modname %q is already specified for file %q", modname, modnames[modname]))
error(string.format('modname %q is already specified for file %q', modname, modnames[modname]))
end
modnames[modname] = source_file
local varname = string.gsub(modname,'%.','_dot_').."_module"
local varname = string.gsub(modname, '%.', '_dot_') .. '_module'
target:write(('static const uint8_t %s[] = {\n'):format(varname))
local output
if options.c then
local luac = os.getenv("LUAC_PRG")
if luac and luac ~= "" then
output = io.popen(luac:format(source_file), "r"):read("*a")
local luac = os.getenv('LUAC_PRG')
if luac and luac ~= '' then
output = io.popen(luac:format(source_file), 'r'):read('*a')
elseif warn_on_missing_compiler then
print("LUAC_PRG is missing, embedding raw source")
print('LUAC_PRG is missing, embedding raw source')
warn_on_missing_compiler = false
end
end
if not output then
local source = io.open(source_file, "r")
local source = io.open(source_file, 'r')
or error(string.format("source_file %q doesn't exist", source_file))
output = source:read("*a")
output = source:read('*a')
source:close()
end
@ -81,8 +81,11 @@ for argi = 2, #arg, 2 do
end
target:write(' 0};\n')
if modname ~= "_" then
table.insert(index_items, ' { "'..modname..'", '..varname..', sizeof '..varname..' },\n\n')
if modname ~= '_' then
table.insert(
index_items,
' { "' .. modname .. '", ' .. varname .. ', sizeof ' .. varname .. ' },\n\n'
)
end
end

View File

@ -25,85 +25,67 @@ end
local lit = lpeg.P
local set = function(...)
return lpeg.S(fold(function (a, b) return a .. b end, ...))
return lpeg.S(fold(function(a, b)
return a .. b
end, ...))
end
local any_character = lpeg.P(1)
local rng = function(s, e) return lpeg.R(s .. e) end
local concat = folder(function (a, b) return a * b end)
local branch = folder(function (a, b) return a + b end)
local one_or_more = function(v) return v ^ 1 end
local two_or_more = function(v) return v ^ 2 end
local any_amount = function(v) return v ^ 0 end
local one_or_no = function(v) return v ^ -1 end
local rng = function(s, e)
return lpeg.R(s .. e)
end
local concat = folder(function(a, b)
return a * b
end)
local branch = folder(function(a, b)
return a + b
end)
local one_or_more = function(v)
return v ^ 1
end
local two_or_more = function(v)
return v ^ 2
end
local any_amount = function(v)
return v ^ 0
end
local one_or_no = function(v)
return v ^ -1
end
local look_behind = lpeg.B
local look_ahead = function(v) return #v end
local neg_look_ahead = function(v) return -v end
local neg_look_behind = function(v) return -look_behind(v) end
local look_ahead = function(v)
return #v
end
local neg_look_ahead = function(v)
return -v
end
local neg_look_behind = function(v)
return -look_behind(v)
end
local w = branch(
rng('a', 'z'),
rng('A', 'Z'),
lit('_')
)
local aw = branch(
w,
rng('0', '9')
)
local w = branch(rng('a', 'z'), rng('A', 'Z'), lit('_'))
local aw = branch(w, rng('0', '9'))
local s = set(' ', '\n', '\t')
local raw_word = concat(w, any_amount(aw))
local right_word = concat(
raw_word,
neg_look_ahead(aw)
)
local right_word = concat(raw_word, neg_look_ahead(aw))
local word = branch(
concat(
branch(lit('ArrayOf('), lit('DictionaryOf('), lit('Dict(')), -- typed container macro
one_or_more(any_character - lit(')')),
lit(')')
),
concat(
neg_look_behind(aw),
right_word
)
)
local inline_comment = concat(
lit('/*'),
any_amount(concat(
neg_look_ahead(lit('*/')),
any_character
)),
lit('*/')
concat(neg_look_behind(aw), right_word)
)
local inline_comment =
concat(lit('/*'), any_amount(concat(neg_look_ahead(lit('*/')), any_character)), lit('*/'))
local spaces = any_amount(branch(
s,
-- Comments are really handled by preprocessor, so the following is not needed
inline_comment,
concat(
lit('//'),
any_amount(concat(
neg_look_ahead(lit('\n')),
any_character
)),
lit('\n')
),
concat(lit('//'), any_amount(concat(neg_look_ahead(lit('\n')), any_character)), lit('\n')),
-- Linemarker inserted by preprocessor
concat(
lit('# '),
any_amount(concat(
neg_look_ahead(lit('\n')),
any_character
)),
lit('\n')
)
concat(lit('# '), any_amount(concat(neg_look_ahead(lit('\n')), any_character)), lit('\n'))
))
local typ_part = concat(
word,
any_amount(concat(
spaces,
lit('*')
)),
spaces
)
local typ_part = concat(word, any_amount(concat(spaces, lit('*'))), spaces)
local typ_id = two_or_more(typ_part)
local arg = typ_id -- argument name is swallowed by typ
@ -121,20 +103,9 @@ local pattern = concat(
lit(','),
spaces,
arg,
any_amount(concat(
lit('['),
spaces,
any_amount(aw),
spaces,
lit(']')
))
any_amount(concat(lit('['), spaces, any_amount(aw), spaces, lit(']')))
)),
one_or_no(concat(
spaces,
lit(','),
spaces,
lit('...')
))
one_or_no(concat(spaces, lit(','), spaces, lit('...')))
),
lit('void') -- also accepts just void
)),
@ -147,10 +118,7 @@ local pattern = concat(
one_or_no(concat( -- attribute argument
spaces,
lit('('),
any_amount(concat(
neg_look_ahead(lit(')')),
any_character
)),
any_amount(concat(neg_look_ahead(lit(')')), any_character)),
lit(')')
))
)),
@ -198,10 +166,9 @@ Additionally uses the following environment variables:
end
local preproc_f = io.open(preproc_fname)
local text = preproc_f:read("*all")
local text = preproc_f:read('*all')
preproc_f:close()
local non_static = [[
#define DEFINE_FUNC_ATTRIBUTES
#include "nvim/func_attr.h"
@ -289,8 +256,7 @@ while init ~= nil do
declaration = declaration .. ';'
if os.getenv('NVIM_GEN_DECLARATIONS_LINE_NUMBERS') == '1' then
declaration = declaration .. (' // %s/%s:%u'):format(
curdir, curfile, declline)
declaration = declaration .. (' // %s/%s:%u'):format(curdir, curfile, declline)
end
declaration = declaration .. '\n'
if declaration:sub(1, 6) == 'static' then

View File

@ -48,18 +48,18 @@ hashpipe:write([[
local funcs = require('eval').funcs
for _, func in pairs(funcs) do
if func.float_func then
func.func = "float_op_wrapper"
func.data = "{ .float_func = &"..func.float_func.." }"
func.func = 'float_op_wrapper'
func.data = '{ .float_func = &' .. func.float_func .. ' }'
end
end
local metadata = mpack.decode(io.open(metadata_file, 'rb'):read("*all"))
local metadata = mpack.decode(io.open(metadata_file, 'rb'):read('*all'))
for _, fun in ipairs(metadata) do
if fun.eval then
funcs[fun.name] = {
args = #fun.parameters,
func = 'api_wrapper',
data='{ .api_handler = &method_handlers['..fun.handler_id..'] }'
data = '{ .api_handler = &method_handlers[' .. fun.handler_id .. '] }',
}
end
end
@ -74,11 +74,11 @@ local funcsdata = assert(io.open(funcs_file, 'w'))
funcsdata:write(mpack.encode(func_names))
funcsdata:close()
local neworder, hashfun = hashy.hashy_hash("find_internal_func", func_names, function (idx)
return "functions["..idx.."].name"
local neworder, hashfun = hashy.hashy_hash('find_internal_func', func_names, function(idx)
return 'functions[' .. idx .. '].name'
end)
hashpipe:write("static const EvalFuncDef functions[] = {\n")
hashpipe:write('static const EvalFuncDef functions[] = {\n')
for _, name in ipairs(neworder) do
local def = funcs[name]
@ -88,14 +88,23 @@ for _, name in ipairs(neworder) do
elseif #args == 1 then
args[2] = 'MAX_FUNC_ARGS'
end
local base = def.base or "BASE_NONE"
local base = def.base or 'BASE_NONE'
local func = def.func or ('f_' .. name)
local data = def.data or "{ .null = NULL }"
local data = def.data or '{ .null = NULL }'
local fast = def.fast and 'true' or 'false'
hashpipe:write((' { "%s", %s, %s, %s, %s, &%s, %s },\n')
:format(name, args[1], args[2], base, fast, func, data))
hashpipe:write(
(' { "%s", %s, %s, %s, %s, &%s, %s },\n'):format(
name,
args[1],
args[2],
base,
fast,
func,
data
)
)
end
hashpipe:write(' { NULL, 0, 0, BASE_NONE, false, NULL, { .null = NULL } },\n')
hashpipe:write("};\n\n")
hashpipe:write('};\n\n')
hashpipe:write(hashfun)
hashpipe:close()

View File

@ -41,15 +41,15 @@ names_tgt:write('\n};\n')
do
names_tgt:write('\nstatic AutoCmdVec autocmds[NUM_EVENTS] = {\n ')
local line_len = 1
for _ = 1,((#events) - 1) do
line_len = line_len + #(' KV_INITIAL_VALUE,')
for _ = 1, (#events - 1) do
line_len = line_len + #' KV_INITIAL_VALUE,'
if line_len > 80 then
names_tgt:write('\n ')
line_len = 1 + #(' KV_INITIAL_VALUE,')
line_len = 1 + #' KV_INITIAL_VALUE,'
end
names_tgt:write(' KV_INITIAL_VALUE,')
end
if line_len + #(' KV_INITIAL_VALUE') > 80 then
if line_len + #' KV_INITIAL_VALUE' > 80 then
names_tgt:write('\n KV_INITIAL_VALUE')
else
names_tgt:write(' KV_INITIAL_VALUE')

View File

@ -21,24 +21,32 @@ local a_to_z = byte_z - byte_a + 1
-- Table giving the index of the first command in cmdnames[] to lookup
-- based on the first letter of a command.
local cmdidxs1_out = string.format([[
local cmdidxs1_out = string.format(
[[
static const uint16_t cmdidxs1[%u] = {
]], a_to_z)
]],
a_to_z
)
-- Table giving the index of the first command in cmdnames[] to lookup
-- based on the first 2 letters of a command.
-- Values in cmdidxs2[c1][c2] are relative to cmdidxs1[c1] so that they
-- fit in a byte.
local cmdidxs2_out = string.format([[
local cmdidxs2_out = string.format(
[[
static const uint8_t cmdidxs2[%u][%u] = {
/* a b c d e f g h i j k l m n o p q r s t u v w x y z */
]], a_to_z, a_to_z)
]],
a_to_z,
a_to_z
)
enumfile:write([[
// IWYU pragma: private, include "nvim/ex_cmds_defs.h"
typedef enum CMD_index {
]])
defsfile:write(string.format([[
defsfile:write(string.format(
[[
#include "nvim/arglist.h"
#include "nvim/autocmd.h"
#include "nvim/buffer.h"
@ -79,23 +87,34 @@ defsfile:write(string.format([[
static const int command_count = %u;
static CommandDefinition cmdnames[%u] = {
]], #defs, #defs))
]],
#defs,
#defs
))
local cmds, cmdidxs1, cmdidxs2 = {}, {}, {}
for _, cmd in ipairs(defs) do
if bit.band(cmd.flags, flags.RANGE) == flags.RANGE then
assert(cmd.addr_type ~= 'ADDR_NONE',
string.format('ex_cmds.lua:%s: Using RANGE with ADDR_NONE\n', cmd.command))
assert(
cmd.addr_type ~= 'ADDR_NONE',
string.format('ex_cmds.lua:%s: Using RANGE with ADDR_NONE\n', cmd.command)
)
else
assert(cmd.addr_type == 'ADDR_NONE',
string.format('ex_cmds.lua:%s: Missing ADDR_NONE\n', cmd.command))
assert(
cmd.addr_type == 'ADDR_NONE',
string.format('ex_cmds.lua:%s: Missing ADDR_NONE\n', cmd.command)
)
end
if bit.band(cmd.flags, flags.DFLALL) == flags.DFLALL then
assert(cmd.addr_type ~= 'ADDR_OTHER' and cmd.addr_type ~= 'ADDR_NONE',
string.format('ex_cmds.lua:%s: Missing misplaced DFLALL\n', cmd.command))
assert(
cmd.addr_type ~= 'ADDR_OTHER' and cmd.addr_type ~= 'ADDR_NONE',
string.format('ex_cmds.lua:%s: Missing misplaced DFLALL\n', cmd.command)
)
end
if bit.band(cmd.flags, flags.PREVIEW) == flags.PREVIEW then
assert(cmd.preview_func ~= nil,
string.format('ex_cmds.lua:%s: Missing preview_func\n', cmd.command))
assert(
cmd.preview_func ~= nil,
string.format('ex_cmds.lua:%s: Missing preview_func\n', cmd.command)
)
end
local enumname = cmd.enum or ('CMD_' .. cmd.command)
local byte_cmd = cmd.command:sub(1, 1):byte()
@ -104,12 +123,13 @@ for _, cmd in ipairs(defs) do
end
local preview_func
if cmd.preview_func then
preview_func = string.format("&%s", cmd.preview_func)
preview_func = string.format('&%s', cmd.preview_func)
else
preview_func = "NULL"
preview_func = 'NULL'
end
enumfile:write(' ' .. enumname .. ',\n')
defsfile:write(string.format([[
defsfile:write(string.format(
[[
[%s] = {
.cmd_name = "%s",
.cmd_func = (ex_func_T)&%s,
@ -117,7 +137,14 @@ for _, cmd in ipairs(defs) do
.cmd_argt = %uL,
.cmd_addr_type = %s
},
]], enumname, cmd.command, cmd.func, preview_func, cmd.flags, cmd.addr_type))
]],
enumname,
cmd.command,
cmd.func,
preview_func,
cmd.flags,
cmd.addr_type
))
end
for i = #cmds, 1, -1 do
local cmd = cmds[i]
@ -141,10 +168,12 @@ for i = byte_a, byte_z do
cmdidxs2_out = cmdidxs2_out .. ' /* ' .. c1 .. ' */ {'
for j = byte_a, byte_z do
local c2 = string.char(j)
cmdidxs2_out = cmdidxs2_out ..
((cmdidxs2[c1] and cmdidxs2[c1][c2])
and string.format('%3d', cmdidxs2[c1][c2] - cmdidxs1[c1])
or ' 0') .. ','
cmdidxs2_out = cmdidxs2_out
.. ((cmdidxs2[c1] and cmdidxs2[c1][c2]) and string.format(
'%3d',
cmdidxs2[c1][c2] - cmdidxs1[c1]
) or ' 0')
.. ','
end
cmdidxs2_out = cmdidxs2_out .. ' },\n'
end
@ -154,8 +183,12 @@ enumfile:write([[
CMD_USER_BUF = -2
} cmdidx_T;
]])
defsfile:write(string.format([[
defsfile:write(string.format(
[[
};
%s};
%s};
]], cmdidxs1_out, cmdidxs2_out))
]],
cmdidxs1_out,
cmdidxs2_out
))

View File

@ -76,7 +76,7 @@ local function get_flags(o)
{ 'deny_in_modelines', 'P_NO_ML' },
{ 'deny_duplicates', 'P_NODUP' },
{ 'modelineexpr', 'P_MLE' },
{'func'}
{ 'func' },
}) do
local key_name = flag_desc[1]
local def_name = flag_desc[2] or ('P_' .. key_name:upper())
@ -108,11 +108,19 @@ local function get_cond(c, base_string)
end
local value_dumpers = {
['function']=function(v) return v() end,
['function'] = function(v)
return v()
end,
string = cstr,
boolean=function(v) return v and 'true' or 'false' end,
number=function(v) return ('%iL'):format(v) end,
['nil']=function(_) return '0' end,
boolean = function(v)
return v and 'true' or 'false'
end,
number = function(v)
return ('%iL'):format(v)
end,
['nil'] = function(_)
return '0'
end,
}
local get_value = function(v)
@ -156,12 +164,13 @@ local function dump_option(i, o)
assert(#o.scope == 1 or #o.scope == 2)
assert(#o.scope == 1 or o.scope[1] == 'global')
local min_scope = o.scope[#o.scope]
local varname = o.pv_name or o.varname or (
'p_' .. (o.abbreviation or o.full_name))
local varname = o.pv_name or o.varname or ('p_' .. (o.abbreviation or o.full_name))
local pv_name = (
'OPT_' .. min_scope:sub(1, 3):upper() .. '(' .. (
min_scope:sub(1, 1):upper() .. 'V_' .. varname:sub(3):upper()
) .. ')'
'OPT_'
.. min_scope:sub(1, 3):upper()
.. '('
.. (min_scope:sub(1, 1):upper() .. 'V_' .. varname:sub(3):upper())
.. ')'
)
if #o.scope == 2 then
pv_name = 'OPT_BOTH(' .. pv_name .. ')'

View File

@ -60,12 +60,10 @@ local fp_lines_to_lists = function(fp, n, has_comments)
if not line then
break
end
if (not has_comments
or (line:sub(1, 1) ~= '#' and not line:match('^%s*$'))) then
if not has_comments or (line:sub(1, 1) ~= '#' and not line:match('^%s*$')) then
local l = split_on_semicolons(line)
if #l ~= n then
io.stderr:write(('Found %s items in line %u, expected %u\n'):format(
#l, i, n))
io.stderr:write(('Found %s items in line %u, expected %u\n'):format(#l, i, n))
io.stderr:write('Line: ' .. line .. '\n')
return nil
end
@ -93,15 +91,13 @@ end
local make_range = function(start, end_, step, add)
if step and add then
return (' {0x%x, 0x%x, %d, %d},\n'):format(
start, end_, step == 0 and -1 or step, add)
return (' {0x%x, 0x%x, %d, %d},\n'):format(start, end_, step == 0 and -1 or step, add)
else
return (' {0x%04x, 0x%04x},\n'):format(start, end_)
end
end
local build_convert_table = function(ut_fp, props, cond_func, nl_index,
table_name)
local build_convert_table = function(ut_fp, props, cond_func, nl_index, table_name)
ut_fp:write('static const convertStruct ' .. table_name .. '[] = {\n')
local start = -1
local end_ = -1
@ -137,8 +133,7 @@ local build_case_table = function(ut_fp, dataprops, table_name, index)
local cond_func = function(p)
return p[index] ~= ''
end
return build_convert_table(ut_fp, dataprops, cond_func, index,
'to' .. table_name)
return build_convert_table(ut_fp, dataprops, cond_func, index, 'to' .. table_name)
end
local build_fold_table = function(ut_fp, foldprops)
@ -154,7 +149,7 @@ local build_combining_table = function(ut_fp, dataprops)
local end_ = -1
for _, p in ipairs(dataprops) do
-- The 'Mc' property was removed, it does take up space.
if (({Mn=true, Me=true})[p[3]]) then
if ({ Mn = true, Me = true })[p[3]] then
local n = tonumber(p[1], 16)
if start >= 0 and end_ + 1 == n then
-- Continue with the same range.
@ -175,8 +170,7 @@ local build_combining_table = function(ut_fp, dataprops)
ut_fp:write('};\n')
end
local build_width_table = function(ut_fp, dataprops, widthprops, widths,
table_name)
local build_width_table = function(ut_fp, dataprops, widthprops, widths, table_name)
ut_fp:write('static const struct interval ' .. table_name .. '[] = {\n')
local start = -1
local end_ = -1
@ -208,7 +202,7 @@ local build_width_table = function(ut_fp, dataprops, widthprops, widths,
-- Only use the char when its not a composing char.
-- But use all chars from a range.
local dp = dataprops[dataidx]
if (n_last > n) or (not (({Mn=true, Mc=true, Me=true})[dp[3]])) then
if (n_last > n) or not ({ Mn = true, Mc = true, Me = true })[dp[3]] then
if start >= 0 and end_ + 1 == n then -- luacheck: ignore 542
-- Continue with the same range.
else
@ -316,10 +310,9 @@ local eaw_fp = io.open(eastasianwidth_fname, 'r')
local widthprops = parse_width_props(eaw_fp)
eaw_fp:close()
local doublewidth = build_width_table(ut_fp, dataprops, widthprops,
{W=true, F=true}, 'doublewidth')
local ambiwidth = build_width_table(ut_fp, dataprops, widthprops,
{A=true}, 'ambiguous')
local doublewidth =
build_width_table(ut_fp, dataprops, widthprops, { W = true, F = true }, 'doublewidth')
local ambiwidth = build_width_table(ut_fp, dataprops, widthprops, { A = true }, 'ambiguous')
local emoji_fp = io.open(emoji_fname, 'r')
local emojiprops = parse_emoji_props(emoji_fp)

View File

@ -41,12 +41,14 @@ end
-- Exclude these from the vimCommand keyword list, they are handled specially
-- in syntax/vim.vim (vimAugroupKey, vimAutoCmd, vimGlobal, vimSubst). #9327
local function is_special_cased_cmd(cmd)
return (cmd == 'augroup'
return (
cmd == 'augroup'
or cmd == 'autocmd'
or cmd == 'doautocmd'
or cmd == 'doautoall'
or cmd == 'global'
or cmd == 'substitute')
or cmd == 'substitute'
)
end
local vimcmd_start = 'syn keyword vimCommand contained '
@ -133,7 +135,7 @@ end
w('\n\nsyn case match')
local vimfun_start = 'syn keyword vimFuncName contained '
w('\n\n' .. vimfun_start)
local funcs = mpack.decode(io.open(funcs_file, 'rb'):read("*all"))
local funcs = mpack.decode(io.open(funcs_file, 'rb'):read('*all'))
for _, name in ipairs(funcs) do
if name then
if lld.line_length > 850 then

View File

@ -3,7 +3,6 @@
local M = {}
_G.d = M
local function setdefault(table, key)
local val = table[key]
if val == nil then
@ -18,7 +17,9 @@ function M.build_pos_hash(strings)
local maxlen = 0
for _, s in ipairs(strings) do
table.insert(setdefault(len_buckets, #s), s)
if #s > maxlen then maxlen = #s end
if #s > maxlen then
maxlen = #s
end
end
local len_pos_buckets = {}
@ -55,59 +56,65 @@ end
function M.switcher(put, tab, maxlen, worst_buck_size)
local neworder = {}
put " switch (len) {\n"
put ' switch (len) {\n'
local bucky = worst_buck_size > 1
for len = 1, maxlen do
local vals = tab[len]
if vals then
put(" case "..len..": ")
put(' case ' .. len .. ': ')
local pos, posbuck = unpack(vals)
local keys = vim.tbl_keys(posbuck)
if #keys > 1 then
table.sort(keys)
put("switch (str["..(pos-1).."]) {\n")
put('switch (str[' .. (pos - 1) .. ']) {\n')
for _, c in ipairs(keys) do
local buck = posbuck[c]
local startidx = #neworder
vim.list_extend(neworder, buck)
local endidx = #neworder
put(" case '" .. c .. "': ")
put("low = "..startidx.."; ")
if bucky then put("high = "..endidx.."; ") end
put "break;\n"
put('low = ' .. startidx .. '; ')
if bucky then
put('high = ' .. endidx .. '; ')
end
put " default: break;\n"
put " }\n "
put 'break;\n'
end
put ' default: break;\n'
put ' }\n '
else
local startidx = #neworder
table.insert(neworder, posbuck[keys[1]][1])
local endidx = #neworder
put("low = "..startidx.."; ")
if bucky then put("high = "..endidx.."; ") end
end
put "break;\n"
put('low = ' .. startidx .. '; ')
if bucky then
put('high = ' .. endidx .. '; ')
end
end
put " default: break;\n"
put " }\n"
put 'break;\n'
end
end
put ' default: break;\n'
put ' }\n'
return neworder
end
function M.hashy_hash(name, strings, access)
local stats = {}
local put = function(str) table.insert(stats, str) end
local put = function(str)
table.insert(stats, str)
end
local len_pos_buckets, maxlen, worst_buck_size = M.build_pos_hash(strings)
put("int "..name.."_hash(const char *str, size_t len)\n{\n")
put('int ' .. name .. '_hash(const char *str, size_t len)\n{\n')
if worst_buck_size > 1 then
put(" int low = 0, high = 0;\n")
put(' int low = 0, high = 0;\n')
else
put(" int low = -1;\n")
put(' int low = -1;\n')
end
local neworder = M.switcher(put, len_pos_buckets, maxlen, worst_buck_size)
if worst_buck_size > 1 then
put([[
for (int i = low; i < high; i++) {
if (!memcmp(str, ]]..access("i")..[[, len)) {
if (!memcmp(str, ]] .. access('i') .. [[, len)) {
return i;
}
}
@ -115,13 +122,13 @@ function M.hashy_hash(name, strings, access)
]])
else
put([[
if (low < 0 || memcmp(str, ]]..access("low")..[[, len)) {
if (low < 0 || memcmp(str, ]] .. access('low') .. [[, len)) {
return -1;
}
return low;
]])
end
put "}\n\n"
put '}\n\n'
return neworder, table.concat(stats)
end