summaryrefslogtreecommitdiff
path: root/src/rebar_mustache.erl
blob: af8a3424722f3d5ccbf045e085bf0e7073daab60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
%% The MIT License (MIT)
%%
%% Copyright (c) 2015 Hinagiku Soranoba
%%
%% Permission is hereby granted, free of charge, to any person obtaining a copy
%% of this software and associated documentation files (the "Software"), to deal
%% in the Software without restriction, including without limitation the rights
%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
%% copies of the Software, and to permit persons to whom the Software is
%% furnished to do so, subject to the following conditions:
%%
%% The above copyright notice and this permission notice shall be included in all
%% copies or substantial portions of the Software.
%%
%% @doc Mustache template engine for Erlang/OTP.
-module(rebar_mustache).

%%----------------------------------------------------------------------------------------------------------------------
%% Exported API
%%----------------------------------------------------------------------------------------------------------------------
-export([
         render/2,
         parse_binary/1,
         parse_file/1,
         compile/2
        ]).

-export_type([
              template/0,
              data/0
             ]).

%%----------------------------------------------------------------------------------------------------------------------
%% Defines & Records & Types
%%----------------------------------------------------------------------------------------------------------------------

-define(PARSE_ERROR,        incorrect_format).
-define(FILE_ERROR,         file_not_found).
-define(COND(Cond, TValue, FValue),
        case Cond of true -> TValue; false -> FValue end).

-type key()  :: binary().
-type tag()  :: {n,   key()}                              |
                {'&', key()}                              |
                {'#', key(), [tag()], Source :: binary()} |
                {'^', key(), [tag()]}                     |
                binary().

-record(state,
        {
          dirname = <<>>     :: file:filename_all(),
          start   = <<"{{">> :: binary(),
          stop    = <<"}}">> :: binary()
        }).
-type state() :: #state{}.

-record(?MODULE,
        {
          data :: [tag()]
        }).

-opaque template() :: #?MODULE{}.
%% @see parse_binary/1
%% @see parse_file/1
-ifdef(namespaced_types).
-type data()       :: #{string() => data() | iodata() | fun((data(), function()) -> iodata())}.
-else.
-type data()       :: dict().
-endif.
%% @see render/2
%% @see compile/2
-type partial()    :: {partial, {state(), EndTag :: binary(), LastTagSize :: non_neg_integer(), Rest :: binary(), [tag()]}}.

%%----------------------------------------------------------------------------------------------------------------------
%% Exported Functions
%%----------------------------------------------------------------------------------------------------------------------

%% @equiv compile(parse_binary(Bin), Map)
-spec render(binary(), data()) -> binary().
render(Bin, Map) ->
    compile(parse_binary(Bin), Map).

%% @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()) -> template().
parse_file(Filename) ->
    case file:read_file(Filename) of
        {ok, Bin} -> parse_binary_impl(#state{dirname = filename:dirname(Filename)}, Bin);
        _         -> error(?FILE_ERROR, [Filename])
    end.

%% @doc Embed the data in the template.
-spec compile(template(), data()) -> binary().
compile(#?MODULE{data = Tags}, Map) ->
    ec_cnv:to_binary(lists:reverse(compile_impl(Tags, Map, []))).

%%----------------------------------------------------------------------------------------------------------------------
%% Internal Function
%%----------------------------------------------------------------------------------------------------------------------

%% @doc {@link compile/2}
%%
%% ATTENTION: The result is a list that is inverted.
-spec compile_impl(Template :: [tag()], data(), Result :: iodata()) -> iodata().
compile_impl([], _, Result) ->
    Result;
compile_impl([{n, Key} | T], Map, Result) ->
    compile_impl(T, Map, [escape(to_binary(dict_get(binary_to_list(Key), Map, <<>>))) | Result]);
compile_impl([{'&', Key} | T], Map, Result) ->
    compile_impl(T, Map, [to_binary(dict_get(binary_to_list(Key), Map, <<>>)) | Result]);
compile_impl([{'#', Key, Tags, Source} | T], Map, Result) ->
    Value = dict_get(binary_to_list(Key), Map, undefined),
    if
        is_list(Value)                       -> compile_impl(T, Map, lists:foldl(fun(X, Acc) -> compile_impl(Tags, X, Acc) end,
                                                                                 Result, Value));
        Value =:= false; Value =:= undefined -> compile_impl(T, Map, Result);
        is_function(Value, 2)                -> compile_impl(T, Map, [Value(Source, fun(Text) -> render(Text, Map) end) | Result]);
        %is_dict(Value)                        -> compile_impl(T, Map, compile_impl(Tags, Value, Result));
        true                                 -> compile_impl(T, Map, compile_impl(Tags, Map, Result))
    end;
compile_impl([{'^', Key, Tags} | T], Map, Result) ->
    Value = dict_get(binary_to_list(Key), Map, undefined),
    case Value =:= undefined orelse Value =:= [] orelse Value =:= false of
        true  -> compile_impl(T, Map, compile_impl(Tags, Map, Result));
        false -> compile_impl(T, Map, Result)
    end;
compile_impl([Bin | T], Map, Result) ->
    compile_impl(T, Map, [Bin | Result]).

%% @see parse_binary/1
-spec parse_binary_impl(state(), Input :: binary()) -> template().
parse_binary_impl(State, Input) ->
    #?MODULE{data = parse(State, Input)}.

%% @doc Analyze the syntax of the mustache.
-spec parse(state(), binary()) -> [tag()].
parse(State, Bin) ->
    case parse1(State, Bin, []) of
        {partial, _} -> error(?PARSE_ERROR);
        {_, Tags}    -> 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()]} | partial().
parse1(#state{start = Start, stop = Stop} = State, Bin, Result) ->
    case binary:split(Bin, Start) of
        []                       -> {State, Result};
        [B1]                     -> {State, [B1 | Result]};
        [B1, <<"{", B2/binary>>] -> parse2(State, binary:split(B2, <<"}", Stop/binary>>), [B1 | Result]);
        [B1, B2]                 -> parse3(State, binary:split(B2, Stop),                 [B1 | Result])
    end.

%% @doc Part of the `parse/1'
%%
%% ATTENTION: The result is a list that is inverted.
parse2(State, [B1, B2], Result) ->
    parse1(State, B2, [{'&', remove_space_from_edge(B1)} | Result]);
parse2(_, _, _) ->
    error(?PARSE_ERROR).

%% @doc Part of the `parse/1'
%%
%% ATTENTION: The result is a list that is inverted.
parse3(State, [B1, B2], Result) ->
    case remove_space_from_head(B1) of
        <<"&", Tag/binary>> ->
            parse1(State, B2, [{'&', remove_space_from_edge(Tag)} | Result]);
        <<T, Tag/binary>> when T =:= $#; T =:= $^ ->
            parse_loop(State, ?COND(T =:= $#, '#', '^'), remove_space_from_edge(Tag), B2, Result);
        <<"=", Tag0/binary>> ->
            Tag1 = remove_space_from_tail(Tag0),
            Size = byte_size(Tag1) - 1,
            case Size >= 0 andalso Tag1 of
                <<Tag2:Size/binary, "=">> -> parse_delimiter(State, Tag2, B2, Result);
                _                         -> error(?PARSE_ERROR)
            end;
        <<"!", _/binary>> ->
            parse1(State, B2, Result);
        <<"/", Tag/binary>> ->
            {partial, {State, remove_space_from_edge(Tag), byte_size(B1) + 4, B2, Result}};
        <<">", Tag/binary>> ->
            parse_jump(State, remove_space_from_edge(Tag), B2, Result);
        Tag ->
            parse1(State, B2, [{n, remove_space_from_tail(Tag)} | Result])
    end;
parse3(_, _, _) ->
    error(?PARSE_ERROR).

%% @doc Loop processing part of the `parse/1'
%%
%% `{{# Tag}}' or `{{^ Tag}}' corresponds to this.
-spec parse_loop(state(), '#' | '^', Tag :: binary(), Input :: binary(), Result :: [tag()]) -> [tag()] | partial().
parse_loop(State0, Mark, Tag, Input, Result0) ->
    case parse1(State0, Input, []) of
        {partial, {State, Tag, LastTagSize, Rest, Result1}} when is_list(Result1) ->
            case Mark of
                '#' -> Source = binary:part(Input, 0, byte_size(Input) - byte_size(Rest) - LastTagSize),
                       parse1(State, Rest, [{'#', Tag, lists:reverse(Result1), Source} | Result0]);
                '^' -> parse1(State, Rest, [{'^', Tag, lists:reverse(Result1)} | Result0])
            end;
        _ ->
            error(?PARSE_ERROR)
    end.

%% @doc Partial part of the `parse/1'
-spec parse_jump(state(), Tag :: binary(), NextBin :: binary(), Result :: [tag()]) -> [tag()] | partial().
parse_jump(#state{dirname = Dirname} = State0, Tag, NextBin, Result0) ->
    Filename0 = <<Tag/binary, ".mustache">>,
    Filename  = filename:join(?COND(Dirname =:= <<>>, [Filename0], [Dirname, Filename0])),
    case file:read_file(Filename) of
        {ok, Bin} ->
            case parse1(State0, Bin, Result0) of
                {partial, _}    -> error(?PARSE_ERROR);
                {State, Result} -> parse1(State, NextBin, Result)
            end;
        _ ->
            error(?FILE_ERROR, [Filename])
    end.

%% @doc Update delimiter part of the `parse/1'
%%
%% Parse_BinaryDelimiterBin :: e.g. `{{=%% %%=}}' -> `%% %%'
-spec parse_delimiter(state(), Parse_BinaryDelimiterBin :: binary(), NextBin :: binary(), Result :: [tag()]) -> [tag()] | partial().
parse_delimiter(State0, Parse_BinaryDelimiterBin, NextBin, Result) ->
    case binary:match(Parse_BinaryDelimiterBin, <<"=">>) of
        nomatch ->
            case [X || X <- binary:split(Parse_BinaryDelimiterBin, <<" ">>, [global]), X =/= <<>>] of
                [Start, Stop] -> parse1(State0#state{start = Start, stop = Stop}, NextBin, Result);
                _             -> error(?PARSE_ERROR)
            end;
        _ ->
            error(?PARSE_ERROR)
    end.

%% @doc Remove the space from the edge.
-spec remove_space_from_edge(binary()) -> binary().
remove_space_from_edge(Bin) ->
    remove_space_from_tail(remove_space_from_head(Bin)).

%% @doc Remove the space from the head.
-spec remove_space_from_head(binary()) -> binary().
remove_space_from_head(<<" ", Rest/binary>>) -> remove_space_from_head(Rest);
remove_space_from_head(Bin)                  -> Bin.

%% @doc Remove the space from the tail.
-spec remove_space_from_tail(binary()) -> binary().
remove_space_from_tail(<<>>) -> <<>>;
remove_space_from_tail(Bin) ->
    PosList = binary:matches(Bin, <<" ">>),
    LastPos = remove_space_from_tail_impl(lists:reverse(PosList), byte_size(Bin)),
    binary:part(Bin, 0, LastPos).

%% @see remove_space_from_tail/1
-spec remove_space_from_tail_impl([{non_neg_integer(), pos_integer()}], non_neg_integer()) -> non_neg_integer().
remove_space_from_tail_impl([{X, Y} | T], Size) when Size =:= X + Y ->
    remove_space_from_tail_impl(T, X);
remove_space_from_tail_impl(_, Size) ->
    Size.

%% @doc Number to binary
-spec to_binary(number() | binary() | string()) -> binary() | string().
to_binary(Integer) when is_integer(Integer) ->
    ec_cnv:to_binary(Integer);
to_binary(Float) when is_float(Float) ->
    io_lib:format("~p", [Float]);
to_binary(X) ->
    X.

%% @doc HTML Escape
-spec escape(iodata()) -> binary().
escape(IoData) ->
    Bin = ec_cnv:to_binary(IoData),
    << <<(escape_char(X))/binary>> || <<X:8>> <= Bin >>.

%% @see escape/1
-spec escape_char(0..16#FFFF) -> binary().
escape_char($<) -> <<"&lt;">>;
escape_char($>) -> <<"&gt;">>;
escape_char($&) -> <<"&amp;">>;
escape_char($") -> <<"&quot;">>;
escape_char($') -> <<"&apos;">>;
escape_char(C)  -> <<C:8>>.

dict_get(Key, Dict, Default) ->
    case dict:find(ec_cnv:to_atom(Key), Dict) of
        {ok, Value} ->
            Value;
        error ->
            Default
    end.