aboutsummaryrefslogtreecommitdiffstats
path: root/lua
diff options
context:
space:
mode:
authorWilliam Boman <william@redwill.se>2022-12-26 16:59:31 +0100
committerGitHub <noreply@github.com>2022-12-26 16:59:31 +0100
commit6f3d6e08e143f6f843410391991a2fc1db113ef2 (patch)
tree21d96848b602024833922b959cec46a82a25e5d1 /lua
parentfeat(functional): add strip_{prefix,suffix} (#803) (diff)
downloadmason-6f3d6e08e143f6f843410391991a2fc1db113ef2.tar
mason-6f3d6e08e143f6f843410391991a2fc1db113ef2.tar.gz
mason-6f3d6e08e143f6f843410391991a2fc1db113ef2.tar.bz2
mason-6f3d6e08e143f6f843410391991a2fc1db113ef2.tar.lz
mason-6f3d6e08e143f6f843410391991a2fc1db113ef2.tar.xz
mason-6f3d6e08e143f6f843410391991a2fc1db113ef2.tar.zst
mason-6f3d6e08e143f6f843410391991a2fc1db113ef2.zip
feat(result): add .try() interface (#804)
Diffstat (limited to 'lua')
-rw-r--r--lua/mason-core/result.lua32
1 files changed, 32 insertions, 0 deletions
diff --git a/lua/mason-core/result.lua b/lua/mason-core/result.lua
index 2521fff1..6e7f942c 100644
--- a/lua/mason-core/result.lua
+++ b/lua/mason-core/result.lua
@@ -176,6 +176,38 @@ function Result.run_catching(fn)
end
end
+---@generic V
+---@param fn fun(try: fun(result: Result): any): V
+---@return Result # Result<V>
+function Result.try(fn)
+ local thread = coroutine.create(fn)
+ local step
+ step = function(...)
+ local ok, result = coroutine.resume(thread, ...)
+ if not ok then
+ -- l'exception! panique!!!
+ error(result, 0)
+ end
+ if coroutine.status(thread) == "dead" then
+ if getmetatable(result) == Result then
+ return result
+ else
+ return Result.success(result)
+ end
+ elseif getmetatable(result) == Result then
+ if result:is_failure() then
+ return result
+ else
+ return step(result:get_or_nil())
+ end
+ else
+ -- yield to parent coroutine
+ return step(coroutine.yield(result))
+ end
+ end
+ return step(coroutine.yield)
+end
+
function Result.pcall(fn, ...)
local ok, res = pcall(fn, ...)
if ok then