%% @copyright 2015 Hinagiku Soranoba All Rights Reserved.
%%
%% @doc Binary pattern match Based Mustach template engine for Erlang/OTP.
%%
%% Please refer to [the man page](http://mustache.github.io/mustache.5.html) and [the spec](https://github.com/mustache/spec) of mustache as the need arises.
%%
%% Please see [this](../benchmarks/README.md) for a list of features that bbmustache supports.
%%
-module(bbmustache).
%%----------------------------------------------------------------------------------------------------------------------
%% Exported API
%%----------------------------------------------------------------------------------------------------------------------
-export([
render/2,
render/3,
parse_binary/1,
parse_file/1,
compile/2,
compile/3
]).
-export_type([
template/0,
data/0,
option/0
]).
%%----------------------------------------------------------------------------------------------------------------------
%% Defines & Records & Types
%%----------------------------------------------------------------------------------------------------------------------
-define(PARSE_ERROR, incorrect_format).
-define(FILE_ERROR, file_not_found).
-define(IIF(Cond, TValue, FValue),
case Cond of true -> TValue; false -> FValue end).
-define(ADD(X, Y), ?IIF(X =:= <<>>, Y, [X | Y])).
-define(START_TAG, <<"{{">>).
-define(STOP_TAG, <<"}}">>).
-type key() :: binary().
%% Key MUST be a non-whitespace character sequence NOT containing the current closing delimiter.
%%
%% In addition, `.' have a special meaning.
%% (1) `parent.child' ... find the child in the parent.
%% (2) `.' ... It means this. However, the type of correspond is only `[integer() | float() | binary() | string() | atom()]'. Otherwise, the behavior is undefined.
%%
-type source() :: binary().
%% If you use lamda expressions, the original text is necessary.
%%
%% ```
%% e.g.
%% template:
%% {{#lamda}}a{{b}}c{{/lamda}}
%% parse result:
%% {'#', <<"lamda">>, [<<"a">>, {'n', <<"b">>}, <<"c">>], <<"a{{b}}c">>}
%% '''
%%
%% NOTE:
%% Since the binary reference is used internally, it is not a capacitively large waste.
%% However, the greater the number of tags used, it should use the wasted memory.
-type tag() :: {n, [key()]}
| {'&', [key()]}
| {'#', [key()], [tag()], source()}
| {'^', [key()], [tag()]}
| {'>', key(), Indent :: source()}
| binary(). % plain text
-record(?MODULE,
{
data :: [tag()],
partials = [] :: [{key(), [tag()]}],
options = [] :: [option()],
indents = [] :: [binary()],
context_stack = [] :: [data()]
}).
-opaque template() :: #?MODULE{}.
%% @see parse_binary/1
%% @see parse_file/1
-record(state,
{
dirname = <<>> :: file:filename_all(),
start = ?START_TAG :: binary(),
stop = ?STOP_TAG :: binary(),
partials = [] :: [key()],
standalone = true :: boolean()
}).
-type state() :: #state{}.
-type data_key() :: atom() | binary() | string().
%% You can choose one from these as the type of key in {@link data/0}.
-type data_value() :: data() | iodata() | number() | atom() | fun((data(), function()) -> iodata()).
%% Function is intended to support a lambda expression.
-type assoc_data() :: [{atom(), data_value()}] | [{binary(), data_value()}] | [{string(), data_value()}].
-type option() :: {key_type, atom | binary | string}.
%% - key_type: Specify the type of the key in {@link data/0}. Default value is `string'.
-ifdef(namespaced_types).
-type maps_data() :: #{atom() => data_value()} | #{binary() => data_value()} | #{string() => data_value()}.
-type data() :: maps_data() | assoc_data().
-else.
-type data() :: assoc_data().
-endif.
%% All key in assoc list or maps must be same type.
%% @see render/2
%% @see compile/2
-type endtag() :: {endtag, {state(), [key()], LastTagSize :: non_neg_integer(), Rest :: binary(), Result :: [tag()]}}.
%%----------------------------------------------------------------------------------------------------------------------
%% Exported Functions
%%----------------------------------------------------------------------------------------------------------------------
%% @equiv render(Bin, Data, [])
-spec render(binary(), data()) -> binary().
render(Bin, Data) ->
render(Bin, Data, []).
%% @equiv compile(parse_binary(Bin), Data, Options)
-spec render(binary(), data(), [option()]) -> binary().
render(Bin, Data, Options) ->
compile(parse_binary(Bin), Data, Options).
%% @doc Create a {@link template/0} from a binary.
-spec parse_binary(binary()) -> template().
parse_binary(Bin) when is_binary(Bin) ->
parse_binary_impl(#state{}, Bin).
%% @doc Create a {@link template/0} from a file.
-spec parse_file(file:filename_all()) -> template().
parse_file(Filename) ->
State = #state{dirname = filename:dirname(Filename)},
case to_binary(filename:extension(Filename)) of
<<".mustache">> = Ext ->
Partials = [Key = to_binary(filename:basename(Filename, Ext))],
parse_binary_impl(State#state{partials = Partials}, #?MODULE{data = [{'>', Key, <<>>}]});
_ ->
case file:read_file(Filename) of
{ok, Bin} -> parse_binary_impl(State, Bin);
_ -> error(?FILE_ERROR, [Filename])
end
end.
%% @equiv compile(Template, Data, [])
-spec compile(template(), data()) -> binary().
compile(Template, Data) ->
compile(Template, Data, []).
%% @doc Embed the data in the template.
%%
%% ```
%% 1> Template = bbmustache:parse_binary(<<"{{name}}">>).
%% 2> bbmustache:compile(Template, #{"name" => "Alice"}).
%% <<"Alice">>
%% '''
%% Data support assoc list or maps (OTP17 or later).
%% All key in assoc list or maps MUST be same type.
-spec compile(template(), data(), [option()]) -> binary().
compile(#?MODULE{data = Tags} = T, Data, Options) ->
case check_data_type(Data) of
false -> error(function_clause, [T, Data]);
_ ->
Ret = compile_impl(Tags, Data, [], T#?MODULE{options = Options, data = []}),
iolist_to_binary(lists:reverse(Ret))
end.
%%----------------------------------------------------------------------------------------------------------------------
%% Internal Function
%%----------------------------------------------------------------------------------------------------------------------
%% @doc {@link compile/2}
%%
%% ATTENTION: The result is a list that is inverted.
-spec compile_impl(Template :: [tag()], data(), Result :: iodata(), template()) -> iodata().
compile_impl([], _, Result, _) ->
Result;
compile_impl([{n, Keys} | T], Map, Result, State) ->
compile_impl(T, Map, ?ADD(escape(to_iodata(get_data_recursive(Keys, Map, <<>>, State))), Result), State);
compile_impl([{'&', Keys} | T], Map, Result, State) ->
compile_impl(T, Map, ?ADD(to_iodata(get_data_recursive(Keys, Map, <<>>, State)), Result), State);
compile_impl([{'#', Keys, Tags, Source} | T], Map, Result, State) ->
Value = get_data_recursive(Keys, Map, false, State),
NestedState = State#?MODULE{context_stack = [Map | State#?MODULE.context_stack]},
case check_data_type(Value) of
true ->
compile_impl(T, Map, compile_impl(Tags, Value, Result, NestedState), State);
_ when is_list(Value) ->
compile_impl(T, Map, lists:foldl(fun(X, Acc) -> compile_impl(Tags, X, Acc, NestedState) end,
Result, Value), State);
_ when Value =:= false ->
compile_impl(T, Map, Result, State);
_ when is_function(Value, 2) ->
Ret = Value(Source, fun(Text) -> render(Text, Map, State#?MODULE.options) end),
compile_impl(T, Map, ?ADD(Ret, Result), State);
_ ->
compile_impl(T, Map, compile_impl(Tags, Map, Result, State), State)
end;
compile_impl([{'^', Keys, Tags} | T], Map, Result, State) ->
Value = get_data_recursive(Keys, Map, false, State),
case Value =:= [] orelse Value =:= false of
true -> compile_impl(T, Map, compile_impl(Tags, Map, Result, State), State);
false -> compile_impl(T, Map, Result, State)
end;
compile_impl([{'>', Key, Indent} | T], Map, Result0, #?MODULE{partials = Partials} = State) ->
case proplists:get_value(Key, Partials) of
undefined -> compile_impl(T, Map, Result0, State);
PartialT ->
Indents = State#?MODULE.indents ++ [Indent],
Result1 = compile_impl(PartialT, Map, [Indent | Result0], State#?MODULE{indents = Indents}),
compile_impl(T, Map, Result1, State)
end;
compile_impl([B1 | [_|_] = T], Map, Result, #?MODULE{indents = Indents} = State) when Indents =/= [] ->
%% NOTE: indent of partials
case byte_size(B1) > 0 andalso binary:last(B1) of
$\n -> compile_impl(T, Map, [Indents, B1 | Result], State);
_ -> compile_impl(T, Map, [B1 | Result], State)
end;
compile_impl([Bin | T], Map, Result, State) ->
compile_impl(T, Map, [Bin | Result], State).
%% @see parse_binary/1
-spec parse_binary_impl(state(), Input | template()) -> template() when
Input :: binary().
parse_binary_impl(#state{partials = []}, Template = #?MODULE{}) ->
Template;
parse_binary_impl(State = #state{partials = [P | PartialKeys]}, Template = #?MODULE{partials = Partials}) ->
case proplists:is_defined(P, Partials) of
true -> parse_binary_impl(State#state{partials = PartialKeys}, Template);
false ->
Filename0 = <
>,
Dirname = State#state.dirname,
Filename = ?IIF(Dirname =:= <<>>, Filename0, filename:join([Dirname, Filename0])),
case file:read_file(Filename) of
{ok, Input} ->
{State1, Data} = parse(State, Input),
parse_binary_impl(State1, Template#?MODULE{partials = [{P, Data} | Partials]});
_ ->
parse_binary_impl(State, Template#?MODULE{partials = [{P, []}]})
end
end;
parse_binary_impl(State, Input) ->
{State1, Data} = parse(State, Input),
parse_binary_impl(State1, #?MODULE{data = Data}).
%% @doc Analyze the syntax of the mustache.
-spec parse(state(), binary()) -> {#state{}, [tag()]}.
parse(State0, Bin) ->
case parse1(State0, Bin, []) of
{endtag, {_, Keys, _, _, _}} ->
error({?PARSE_ERROR, {section_is_incorrect, binary_join(Keys, <<".">>)}});
{#state{partials = Partials} = State, Tags} ->
{State#state{partials = lists:usort(Partials), start = ?START_TAG, stop = ?STOP_TAG},
lists:reverse(Tags)}
end.
%% @doc Part of the `parse/1'
%%
%% ATTENTION: The result is a list that is inverted.
-spec parse1(state(), Input :: binary(), Result :: [tag()]) -> {state(), [tag()]} | endtag().
parse1(#state{start = Start} = State, Bin, Result) ->
case binary:match(Bin, [Start, <<"\n">>]) of
nomatch -> {State, ?ADD(Bin, Result)};
{S, L} ->
Pos = S + L,
B2 = binary:part(Bin, Pos, byte_size(Bin) - Pos),
case binary:at(Bin, S) of
$\n -> parse1(State#state{standalone = true}, B2, ?ADD(binary:part(Bin, 0, Pos), Result)); % \n
_ -> parse2(State, split_tag(State, Bin), Result)
end
end.
%% @doc Part of the `parse/1'
%%
%% ATTENTION: The result is a list that is inverted.
-spec parse2(state(), iolist(), Result :: [tag()]) -> {state(), [tag()]} | endtag().
parse2(State, [B1, B2, B3], Result) ->
case remove_space_from_head(B2) of
<