add join and mkCall

This commit is contained in:
Dmitriy Pleshevskiy 2024-02-28 16:54:16 +03:00
parent 828f2a3b8b
commit f152767145
Signed by: pleshevskiy
GPG key ID: 17041163DA10A9A2
2 changed files with 28 additions and 5 deletions

27
lib.nix
View file

@ -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;
}

View file

@ -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\")";
};
}