Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add types to argparse and alt_getopt #4497

Merged
merged 6 commits into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 26 additions & 0 deletions library/lua/3rdparty/alt_getopt.lua
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@

local _ENV = mkmodule('3rdparty.alt_getopt')

---@nodiscard
---@param opts string
---@return table<string, string|integer>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

table value is always an integer (but I see that the more permissive type might be needed because it can be string|integer in other contexts)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah this is one of a few "just has to be truthy" fields.

local function get_opt_map(opts)
local i = 1
local len = #opts
Expand All @@ -57,11 +60,16 @@ local function get_opt_map(opts)
return options
end

---@param opt string|integer
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

opt can only be a string at this point (but I see that the more permissive type might be needed because it can be string|integer in other contexts)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As above, I believe.

local function err_unknown_opt(opt)
qerror(string.format('Unknown option "-%s%s"', #opt > 1 and '-' or '', opt))
end

-- resolve aliases into their canonical forms
---@nodiscard
---@param options table<string, string|integer>
---@param opt string|integer
---@return integer
local function canonicalize(options, opt)
if not options[opt] then
err_unknown_opt(opt)
Expand All @@ -80,14 +88,26 @@ local function canonicalize(options, opt)
'Option "%s" resolves to non-number for has_arg flag', opt))
end

---@type integer
return opt
end

---@nodiscard
---@param options table<string, string|integer>
---@param opt string|integer
---@return boolean
local function has_arg(options, opt)
return options[canonicalize(options, opt)] == 1
end

-- returns vectors for opts, optargs, and nonoptions
---@nodiscard
---@param args string[] e.g, { ... }
---@param sh_opts string e.g., 'ak:hv'
---@param long_opts table<string, string|integer>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isn't this a table<string, string>?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

processArgsGetopt assigns a truthy 1 or 0 to it. So I guess it kind of like the other "just has to be a truthy" fields.

---@return string[] opts
---@return string[] optargs
---@return string[] nonoptions
function get_ordered_opts(args, sh_opts, long_opts)
local optind, count, opts, optargs, nonoptions = 1, 1, {}, {}, {}

Expand Down Expand Up @@ -159,6 +179,12 @@ end

-- returns a map of options to their optargs (or 1 if the option doesn't take an
-- argument), and a vector for nonoptions
---@nodiscard
---@param args string[]
---@param sh_opts string
---@param long_opts string[]
---@return table
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

specifically, table<string, string|integer>, right?

---@return string[]
function get_opts(args, sh_opts, long_opts)
local ret = {}

Expand Down
58 changes: 51 additions & 7 deletions library/lua/argparse.lua
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ local _ENV = mkmodule('argparse')

local getopt = require('3rdparty.alt_getopt')

---@nodiscard
---@param args string[] Most commonly `{ ... }`
---@param validArgs table<string, integer> Use `utils.invert`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the value of this table just has to be truthy. maybe use boolean instead of integer

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we do that the return value of utils.invert will be incompatible in LuaLS's eyes. We could do "any" and mention in the comment it has to be truthy?

Just to be clear:

---@param truthy boolean
function foo(truthy) end

local bar = foo("") -- Shows a warning
local caz = foo(1) -- Shows a warning

---@return table<string, string[]|nil>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a table<string, string|string[]>

function processArgs(args, validArgs)
local result = {}
local argName
Expand Down Expand Up @@ -58,25 +62,34 @@ function processArgs(args, validArgs)
return result
end

---@class argparse.OptionAction
---@field [1] string|nil Short option (eg. "q")
---@field [2] string|nil Long option (eg. "quiet")
---@field handler fun(optarg?: string)
---@field hasArg boolean|nil
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we have to specify |nil here? nil is just a falsey boolean

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

|nil here specifies that the field is not required.


-- See online docs for full usage info.
--
-- Quick example:
--
-- local args = {...}
-- local open_readonly, filename = false, nil -- set defaults
-- local args = {...}
-- local open_readonly, filename = false, nil -- set defaults
--
-- local positionals = argparse.processArgsGetopt(args, {
-- {'r', handler=function() open_readonly = true end},
-- {'f', 'filename', hasArg=true,
-- handler=function(optarg) filename = optarg end}
-- })
-- local positionals = argparse.processArgsGetopt(args, {
-- {'r', handler=function() open_readonly = true end},
-- {'f', 'filename', hasArg=true,
-- handler=function(optarg) filename = optarg end}
-- })
--
-- In this example, if args is {'first', '-rf', 'fname', 'second'} or,
-- equivalently, {'first', '-r', '--filename', 'myfile.txt', 'second'} (note the
-- double dash in front of the long option alias), then:
-- open_readonly == true
-- filename == 'myfile.txt'
-- positionals == {'first', 'second'}.
---@param args string[] Most commonly `{ ... }`
---@param optionActions argparse.OptionAction[]
---@return string[] positionals # Positional arguments
function processArgsGetopt(args, optionActions)
local sh_opts, long_opts = '', {}
local handlers = {}
Expand Down Expand Up @@ -120,6 +133,9 @@ function processArgsGetopt(args, optionActions)
return nonoptions
end

---@param arg_name? string
---@param fmt string
---@param ... any
local function arg_error(arg_name, fmt, ...)
local prefix = ''
if arg_name and #arg_name > 0 then
Expand All @@ -128,6 +144,11 @@ local function arg_error(arg_name, fmt, ...)
qerror(('%s'..fmt):format(prefix, ...))
end

---@nodiscard
---@param arg string
---@param arg_name? string
---@param list_length? integer
---@return string[]
function stringList(arg, arg_name, list_length)
if not list_length then list_length = 0 end
local list = arg and (arg):split(',') or {}
Expand All @@ -141,7 +162,13 @@ function stringList(arg, arg_name, list_length)
return list
end

---@nodiscard
---@param arg string
---@param arg_name? string
---@param list_length? integer
---@return integer[]
function numberList(arg, arg_name, list_length)
---@type integer[]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ugh, should we just declare a new output table so we don't have to live this lie?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure can do!

local strings = stringList(arg, arg_name, list_length)
for i,str in ipairs(strings) do
local num = tonumber(str)
Expand All @@ -153,6 +180,10 @@ function numberList(arg, arg_name, list_length)
return strings
end

---@nodiscard
---@param arg integer
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

arg is string|integer (but is likely to be a string)

---@param arg_name? string
---@return number
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

specifically an integer, if that matters

function positiveInt(arg, arg_name)
local val = tonumber(arg)
if not val or val <= 0 or val ~= math.floor(val) then
Expand All @@ -162,6 +193,10 @@ function positiveInt(arg, arg_name)
return val
end

---@nodiscard
---@param arg integer
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

string|integer

---@param arg_name? string
---@return number
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

integer

function nonnegativeInt(arg, arg_name)
local val = tonumber(arg)
if not val or val < 0 or val ~= math.floor(val) then
Expand All @@ -171,6 +206,11 @@ function nonnegativeInt(arg, arg_name)
return val
end

---@nodiscard
---@param arg string|'here'
---@param arg_name? string
---@param skip_validation? boolean
---@return global.T_cursor|coord
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

always a coord, never a T_cursor

function coords(arg, arg_name, skip_validation)
if arg == 'here' then
local guidm = require('gui.dwarfmode') -- globals may not be available yet
Expand Down Expand Up @@ -198,6 +238,10 @@ end

local toBool={["true"]=true,["yes"]=true,["y"]=true,["on"]=true,["1"]=true,
["false"]=false,["no"]=false,["n"]=false,["off"]=false,["0"]=false}
---@nodiscard
---@param arg string
---@param arg_name? string
---@return boolean
function boolean(arg, arg_name)
local arg_lower = string.lower(arg)
if toBool[arg_lower] == nil then
Expand Down
2 changes: 1 addition & 1 deletion library/lua/dfhack.lua
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ function printall_recurse(value, seen)
end

---@generic T
---@param table `T`
---@param table T
---@return T
function copyall(table)
local rv = {}
Expand Down
1 change: 1 addition & 0 deletions library/lua/gui/dwarfmode.lua
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ function getPanelLayout()
}
end

---@return global.T_cursor|nil
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it doesn't actually return a T_cursor, it returns a standard Lua table with the same fields as T_cursor.

function getCursorPos()
if g_cursor.x >= 0 then
return copyall(g_cursor)
Expand Down
10 changes: 10 additions & 0 deletions library/lua/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,9 @@ function normalizePath(path)
return path:gsub(PLATFORM_SLASH, '/'):gsub('/+', '/')
end

---@nodiscard
---@param tab table
---@return table<string, integer>
function invert(tab)
local result = {}
for k,v in pairs(tab) do
Expand All @@ -586,9 +589,16 @@ end
-- processArgs() and processArgsGetopt() have been moved to argparse.lua.
-- The 'require' statements are within the functions to avoid adding hard
-- dependencies to utils.lua (which could lead to circular dependency issues).
---@nodiscard
---@param args string[] Most commonly `{ ... }`
---@param validArgs table<string, integer> Use `utils.invert`
---@return table<string, string|string[]|nil>
function processArgs(args, validArgs)
return require('argparse').processArgs(args, validArgs)
end
---@param args string[] Most commonly `{ ... }`
---@param optionActions argparse.OptionAction[]
---@return nil
function processArgsGetopt(args, optionActions)
return require('argparse').processArgsGetopt(args, optionActions)
end
Expand Down