Packages

An embedded lisp interpreter based on the gleam implementation of MAL lisp.

Current section

Files

Jump to
kirala_l4u src l4u@bif_template.erl
Raw

src/l4u@bif_template.erl

-module(l4u@bif_template).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([bif_template_def/0]).
-spec bif_template_compile(list(l4u@l4u_type:expr()), l4u@l4u_type:env()) -> l4u@l4u_type:expr().
bif_template_compile(Exprs, Env) ->
[{string, Template}] = case Exprs of
[{string, _}] -> Exprs;
_assert_fail ->
erlang:error(#{gleam_error => let_assert,
message => <<"Assertion pattern match failed"/utf8>>,
value => _assert_fail,
module => <<"l4u/bif_template"/utf8>>,
function => <<"bif_template_compile"/utf8>>,
line => 36})
end,
Compiled = l4u@bbmustache_js:compile(Template),
{with_env,
{native_value, <<"bbmustache"/utf8>>, gleam@dynamic:from(Compiled)},
Env}.
-spec assoc_list_to_plist(
list(l4u@l4u_type:expr()),
list({l4u@l4u_type:expr(), l4u@l4u_type:expr()})
) -> list({l4u@l4u_type:expr(), l4u@l4u_type:expr()}).
assoc_list_to_plist(Assoc_list, Acc) ->
case Assoc_list of
[] ->
Acc;
[Key, Value | Rest] ->
assoc_list_to_plist(Rest, [{Key, Value} | Acc]);
Unhandable ->
l4u@sys_bridge_ffi:throw_err(
<<"assoc_list_to_plist: unhandable pattern"/utf8>>
),
[]
end.
-spec to_mustache_param(list(l4u@l4u_type:expr())) -> list({binary(),
gleam@bbmustache:argument()}).
to_mustache_param(Assoc_list) ->
Plist = assoc_list_to_plist(Assoc_list, []),
gleam@list:map(
Plist,
fun(Item) ->
{Key, Value} = case Item of
{_, _} -> Item;
_assert_fail ->
erlang:error(#{gleam_error => let_assert,
message => <<"Assertion pattern match failed"/utf8>>,
value => _assert_fail,
module => <<"l4u/bif_template"/utf8>>,
function => <<"to_mustache_param"/utf8>>,
line => 61})
end,
{l4u@l4u_core:pstr(Key),
l4u@bbmustache_js:string(l4u@l4u_core:pstr(Value))}
end
).
-spec bif_template_render(list(l4u@l4u_type:expr()), l4u@l4u_type:env()) -> l4u@l4u_type:expr().
bif_template_render(Exprs, Env) ->
[{native_value, <<"bbmustache"/utf8>>, Compiled}, {dict, Assoc_list}] = case Exprs of
[{native_value, <<"bbmustache"/utf8>>, _}, {dict, _}] -> Exprs;
_assert_fail ->
erlang:error(#{gleam_error => let_assert,
message => <<"Assertion pattern match failed"/utf8>>,
value => _assert_fail,
module => <<"l4u/bif_template"/utf8>>,
function => <<"bif_template_render"/utf8>>,
line => 68})
end,
Rendered = l4u@bbmustache_js:render(
l4u_ffi:unsafe_corece(Compiled),
to_mustache_param(Assoc_list)
),
{with_env, {string, Rendered}, Env}.
-spec bif_template_def() -> list({binary(), l4u@l4u_type:expr()}).
bif_template_def() ->
Bif = fun(Name, F) -> {Name, {bif, l4u@l4u_core:description(Name), F}} end,
Bsf = fun(Name@1, F@1) ->
{Name@1, {bispform, l4u@l4u_core:description(Name@1), F@1}}
end,
[Bif(<<"template-compile"/utf8>>, fun bif_template_compile/2),
Bif(<<"template-render"/utf8>>, fun bif_template_render/2)].