1 /**
2   * Description of global functions
3   *
4   * Copyright:
5   *     Copyright (c) 2018, Maxim Tyapkin.
6   * Authors:
7   *     Maxim Tyapkin
8   * License:
9   *     This software is licensed under the terms of the BSD 3-clause license.
10   *     The full terms of the license can be found in the LICENSE.md file.
11   */
12 
13 module djinja.algo.functions;
14 
15 private
16 {
17     import djinja.algo.wrapper;
18     import djinja.exception : assertJinja = assertJinjaException;
19     import djinja.uninode;
20 
21     import std.functional : toDelegate;
22     import std.format : fmt = format;
23 }
24 
25 
26 Function[string] globalFunctions()
27 {
28     return cast(immutable)
29         [
30             "range": toDelegate(&range),
31             "length": wrapper!length,
32             "count": wrapper!length,
33             "namespace": wrapper!namespace,
34         ];
35 }
36 
37 
38 UniNode range(UniNode params)
39 {
40     import std.range : iota;
41     import std.array : array;
42     import std.algorithm : map;
43 
44     assertJinja(params.kind == UniNode.Kind.object, "Non object params");
45     assertJinja(cast(bool)("varargs" in params), "Missing varargs in params");
46 
47     if (params["varargs"].length > 0)
48     {
49         auto length = params["varargs"][0].get!long;
50         auto arr = iota(length).map!(a => UniNode(a)).array;
51         return UniNode(arr);
52     }
53 
54     assertJinja(0);
55     assert(0);
56 }
57 
58 
59 long length(UniNode value)
60 {
61     switch (value.kind) with (UniNode.Kind)
62     {
63         case array:
64         case object:
65             return value.length;
66         case text:
67             return value.get!string.length;
68         default:
69             assertJinja(0, "Object of type `%s` has no length()".fmt(value.kind));
70     }
71     assert(0);
72 }
73 
74 
75 UniNode namespace(UniNode kwargs)
76 {
77     return kwargs;
78 }