From f152767145e61fea96eddb1b550ab3f25701e0ad Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Wed, 28 Feb 2024 16:54:16 +0300 Subject: [PATCH] add join and mkCall --- lib.nix | 27 +++++++++++++++++++++++---- lib.test.nix | 6 +++++- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/lib.nix b/lib.nix index f2ae92e..f8bc905 100644 --- a/lib.nix +++ b/lib.nix @@ -22,6 +22,11 @@ let warn = msg: builtins.trace "[nix2lua] warning: ${msg}"; + isJoin = expr: getType expr == "_join"; + join = sep: expr: + if isList expr then { _type = "_join"; sep = validString sep; parts = expr; } + else error "Value '${toString expr}' is not supported for a join type"; + isLuaRaw = expr: getType expr == "raw"; mkLuaRaw = expr: if isLuaRaw expr then @@ -31,10 +36,20 @@ let else error "Value '${toString expr}' is not supported for a raw type"; - # mkCall = fnName: args: mkLuaRaw + mkCall = fnName: args: + let + luaFn = + if isString fnName && builtins.stringLength fnName > 0 then mkLuaRaw fnName + else error "Value '${toString fnName}' is not a valid function name"; + in + join "" ( + [ luaFn (mkLuaRaw "(") ] + ++ [ (join ", " args) ] + ++ [ (mkLuaRaw ")") ] + ); - LuaNil = { _type = "nil"; }; isLuaNil = expr: getType expr == "nil"; + LuaNil = { _type = "nil"; }; # DEPRECATED mkLuaNil = warn "`mkLuaNil` is deprecated. Use `LuaNil` instead" LuaNil; @@ -53,7 +68,8 @@ let toLuaInternal = depth: expr: let nextDepth = depth + 1; in - if isLuaNil expr then "nil" + if isJoin expr then concatStringsSep expr.sep (map (toLuaInternal depth) expr.parts) + else if isLuaNil expr then "nil" else if isLuaRaw expr then expr.raw else if isNamedField expr then if depth > 0 then toLuaNamedField expr.name expr.value @@ -86,8 +102,11 @@ let else error "Value '${toString expr}' is not a valid string"; in { + # low-level + inherit join; + inherit toLua; - inherit LuaNil mkLuaRaw mkNamedField; + inherit LuaNil mkLuaRaw mkNamedField mkCall; # DEPRECATED inherit mkLuaNil; } diff --git a/lib.test.nix b/lib.test.nix index a4ccf2b..db3e960 100644 --- a/lib.test.nix +++ b/lib.test.nix @@ -18,7 +18,7 @@ let nix2lua = import ./lib.nix; - inherit (nix2lua) toLua LuaNil mkLuaRaw mkNamedField; + inherit (nix2lua) toLua LuaNil mkLuaRaw mkNamedField mkCall; inherit (builtins) tryEval; failed = { success = false; value = false; }; @@ -120,4 +120,8 @@ pkgs.lib.runTests { expr = tryEval (toLua (mkNamedField "foo" "bar")); expected = failed; }; + "test returns call function with arguments" = { + expr = toLua (mkCall "root_pattern" [ "deno.json" "deno.jsonc" ]); + expected = "root_pattern(\"deno.json\", \"deno.jsonc\")"; + }; }