erlydtl_runtime.erl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. -module(erlydtl_runtime).
  2. -compile(export_all).
  3. -type text() :: string() | binary().
  4. -type phrase() :: text() | {text(), {PluralPhrase::text(), non_neg_integer()}}.
  5. -type locale() :: term() | {Locale::term(), Context::binary()}.
  6. -type old_translate_fun() :: fun((text()) -> iodata() | default).
  7. -type new_translate_fun() :: fun((phrase(), locale()) -> iodata() | default).
  8. -type translate_fun() :: new_translate_fun() | old_translate_fun().
  9. -type init_translation() :: none
  10. | fun (() -> init_translation())
  11. | {M::atom(), F::atom()}
  12. | {M::atom(), F::atom(), A::list()}
  13. | translate_fun().
  14. -define(IFCHANGED_CONTEXT_VARIABLE, erlydtl_ifchanged_context).
  15. find_value(Key, Data, Options) when is_atom(Key), is_tuple(Data) ->
  16. Rec = element(1, Data),
  17. Info = proplists:get_value(record_info, Options, []),
  18. case proplists:get_value(Rec, Info) of
  19. Fields when is_list(Fields), length(Fields) == size(Data) - 1 ->
  20. case proplists:get_value(Key, Fields) of
  21. Idx when is_integer(Idx) -> element(Idx, Data);
  22. _ -> undefined
  23. end;
  24. _ -> find_value(Key, Data)
  25. end;
  26. find_value(Key, Data, Options) when is_integer(Key), is_list(Data) ->
  27. find_value(adjust_index(Key, 1, lists_0_based, Options), Data);
  28. find_value(Key, Data, Options) when is_integer(Key), is_tuple(Data) ->
  29. find_value(adjust_index(Key, 1, tuples_0_based, Options), Data);
  30. find_value(Key, Data, _Options) ->
  31. find_value(Key, Data).
  32. adjust_index(Key, Off, Opt, Options) when is_list(Options) ->
  33. case proplists:get_value(Opt, Options) of
  34. defer ->
  35. adjust_index(
  36. Key, Off, Opt,
  37. proplists:get_value(render_options, Options));
  38. true ->
  39. Key + Off;
  40. _ ->
  41. Key
  42. end;
  43. adjust_index(Key, _Off, _Opt, _Options) -> Key.
  44. find_value(_, undefined) ->
  45. undefined;
  46. find_value(Key, Fun) when is_function(Fun, 1) ->
  47. Fun(Key);
  48. find_value(Key, L) when is_atom(Key), is_list(L) ->
  49. case lists:keyfind(Key, 1, L) of
  50. false -> find_value(atom_to_list(Key), L);
  51. {Key, Value} -> Value
  52. end;
  53. find_value(Key, L) when is_list(Key), is_list(L) ->
  54. case lists:keyfind(Key, 1, L) of
  55. false -> find_value(list_to_binary(Key), L);
  56. {Key, Value} -> Value
  57. end;
  58. find_value(Key, L) when is_binary(Key), is_list(L) ->
  59. case lists:keyfind(Key, 1, L) of
  60. false -> undefined;
  61. {Key, Value} -> Value
  62. end;
  63. find_value(Key, L) when is_integer(Key), is_list(L) ->
  64. if Key =< length(L) -> lists:nth(Key, L);
  65. true -> undefined
  66. end;
  67. find_value(Key, {GBSize, GBData}) when is_integer(GBSize) ->
  68. case gb_trees:lookup(Key, {GBSize, GBData}) of
  69. {value, Val} ->
  70. Val;
  71. _ ->
  72. undefined
  73. end;
  74. find_value(Key, Tuple) when is_tuple(Tuple) ->
  75. case element(1, Tuple) of
  76. dict ->
  77. case dict:find(Key, Tuple) of
  78. {ok, Val} ->
  79. Val;
  80. _ ->
  81. undefined
  82. end;
  83. _ when is_integer(Key) ->
  84. if Key =< size(Tuple) -> element(Key, Tuple);
  85. true -> undefined
  86. end;
  87. Module ->
  88. case lists:member({Key, 1}, Module:module_info(exports)) of
  89. true ->
  90. case Tuple:Key() of
  91. Val when is_tuple(Val) ->
  92. case element(1, Val) of
  93. 'Elixir.Ecto.Associations.BelongsTo' -> Val:get();
  94. 'Elixir.Ecto.Associations.HasOne' -> Val:get();
  95. _ -> Val
  96. end;
  97. Val -> Val
  98. end;
  99. _ ->
  100. undefined
  101. end
  102. end;
  103. find_value(_, _) ->
  104. undefined.
  105. fetch_value(Key, Data, Options) ->
  106. fetch_value(Key, Data, Options, []).
  107. fetch_value(Key, Data, Options, Default) ->
  108. case find_value(Key, Data, Options) of
  109. undefined -> Default;
  110. Val -> Val
  111. end.
  112. find_deep_value(Key, Data) ->
  113. find_deep_value(Key, Data, []).
  114. find_deep_value([Key|Rest], Item, Opts) ->
  115. case find_value(Key, Item, Opts) of
  116. undefined -> undefined;
  117. NewItem -> find_deep_value(Rest, NewItem, Opts)
  118. end;
  119. find_deep_value([], Item, _Opts) -> Item.
  120. regroup(List, Attribute) ->
  121. do_regroup(List, Attribute, [], []).
  122. regroup(List, Attribute, Options) ->
  123. do_regroup(List, Attribute, Options, []).
  124. do_regroup([], _, _, []) -> [];
  125. do_regroup([], _, _, [[{grouper, LastGrouper}, {list, LastList}]|Acc]) ->
  126. lists:reverse([[{grouper, LastGrouper}, {list, lists:reverse(LastList)}]|Acc]);
  127. do_regroup([Item|Rest], Attribute, Options, []) ->
  128. do_regroup(Rest, Attribute, Options, [[{grouper, find_deep_value(Attribute, Item, Options)}, {list, [Item]}]]);
  129. do_regroup([Item|Rest], Attribute, Options, [[{grouper, PrevGrouper}, {list, PrevList}]|Acc]) ->
  130. case find_deep_value(Attribute, Item, Options) of
  131. Value when Value =:= PrevGrouper ->
  132. do_regroup(Rest, Attribute, Options, [[{grouper, PrevGrouper}, {list, [Item|PrevList]}]|Acc]);
  133. Value ->
  134. do_regroup(Rest, Attribute, Options, [[{grouper, Value}, {list, [Item]}], [{grouper, PrevGrouper}, {list, lists:reverse(PrevList)}]|Acc])
  135. end.
  136. -spec init_translation(init_translation()) -> none | translate_fun().
  137. init_translation(none) -> none;
  138. init_translation(Fun) when is_function(Fun, 0) ->
  139. init_translation(Fun());
  140. init_translation({M, F}) ->
  141. init_translation({M, F, []});
  142. init_translation({M, F, A}) ->
  143. init_translation(apply(M, F, A));
  144. init_translation(Fun)
  145. when is_function(Fun, 1); is_function(Fun, 2) -> Fun;
  146. init_translation(Other) ->
  147. throw({translation_fun, Other}).
  148. -spec translate(Phrase, Locale, Fun) -> iodata() | default when
  149. Phrase :: phrase(),
  150. Locale :: locale(),
  151. Fun :: none | translate_fun().
  152. translate(Phrase, Locale, TranslationFun) ->
  153. translate(Phrase, Locale, TranslationFun, trans_text(Phrase)).
  154. translate(_Phrase, _Locale, none, Default) -> Default;
  155. translate(Phrase, Locale, TranslationFun, Default) ->
  156. case do_translate(Phrase, Locale, TranslationFun) of
  157. default -> Default;
  158. <<"">> -> Default;
  159. "" -> Default;
  160. Translated ->
  161. Translated
  162. end.
  163. trans_text({Text, _}) -> Text;
  164. trans_text(Text) -> Text.
  165. do_translate(Phrase, _Locale, TranslationFun)
  166. when is_function(TranslationFun, 1) ->
  167. TranslationFun(trans_text(Phrase));
  168. do_translate(Phrase, Locale, TranslationFun)
  169. when is_function(TranslationFun, 2) ->
  170. TranslationFun(Phrase, Locale).
  171. %% @doc Translate and interpolate 'blocktrans' content.
  172. %% Pre-requisites:
  173. %% * `Variables' should be sorted
  174. %% * Each interpolation variable should exist
  175. %% (String="{{a}}", Variables=[{"b", "b-val"}] will fall)
  176. %% * Orddict keys should be string(), not binary()
  177. -spec translate_block(phrase(), locale(), orddict:orddict(), none | translate_fun()) -> iodata().
  178. translate_block(Phrase, Locale, Variables, TranslationFun) ->
  179. case translate(Phrase, Locale, TranslationFun, default) of
  180. default -> default;
  181. Translated ->
  182. try interpolate_variables(Translated, Variables)
  183. catch
  184. {no_close_var, T} ->
  185. io:format(standard_error, "Warning: template translation: variable not closed: \"~s\"~n", [T]),
  186. default;
  187. _:_ -> default
  188. end
  189. end.
  190. interpolate_variables(Tpl, []) ->
  191. Tpl;
  192. interpolate_variables(Tpl, Variables) ->
  193. BTpl = iolist_to_binary(Tpl),
  194. interpolate_variables1(BTpl, Variables).
  195. interpolate_variables1(Tpl, Vars) ->
  196. %% pre-compile binary patterns?
  197. case binary:split(Tpl, <<"{{">>) of
  198. [Tpl]=NoVars -> NoVars; %% need to enclose in list due to list tail call below..
  199. [Pre, Post] ->
  200. case binary:split(Post, <<"}}">>) of
  201. [_] -> throw({no_close_var, Tpl});
  202. [Var, Post1] ->
  203. Var1 = string:strip(binary_to_list(Var)),
  204. Value = orddict:fetch(Var1, Vars),
  205. [Pre, Value | interpolate_variables1(Post1, Vars)]
  206. end
  207. end.
  208. are_equal(Arg1, Arg2) when Arg1 =:= Arg2 ->
  209. true;
  210. are_equal(Arg1, Arg2) when is_binary(Arg1) ->
  211. are_equal(binary_to_list(Arg1), Arg2);
  212. are_equal(Arg1, Arg2) when is_binary(Arg2) ->
  213. are_equal(Arg1, binary_to_list(Arg2));
  214. are_equal(Arg1, Arg2) when is_integer(Arg1) ->
  215. are_equal(integer_to_list(Arg1), Arg2);
  216. are_equal(Arg1, Arg2) when is_integer(Arg2) ->
  217. are_equal(Arg1, integer_to_list(Arg2));
  218. are_equal(Arg1, Arg2) when is_atom(Arg1), is_list(Arg2) ->
  219. are_equal(atom_to_list(Arg1), Arg2);
  220. are_equal(Arg1, Arg2) when is_list(Arg1), is_atom(Arg2) ->
  221. are_equal(Arg1, atom_to_list(Arg2));
  222. are_equal(_, _) ->
  223. false.
  224. is_false("") -> true;
  225. is_false(false) -> true;
  226. is_false(undefined) -> true;
  227. is_false(null) -> true;
  228. is_false(0) -> true;
  229. is_false("0") -> true;
  230. is_false(<<"0">>) -> true;
  231. is_false(<<>>) -> true;
  232. is_false(_) -> false.
  233. is_true(V) -> not is_false(V).
  234. 'in'(Sublist, [Sublist|_]) ->
  235. true;
  236. 'in'(Sublist, List) when is_atom(List) ->
  237. 'in'(Sublist, atom_to_list(List));
  238. 'in'(Sublist, List) when is_binary(Sublist) ->
  239. 'in'(binary_to_list(Sublist), List);
  240. 'in'(Sublist, List) when is_binary(List) ->
  241. 'in'(Sublist, binary_to_list(List));
  242. 'in'(Sublist, [C|Rest]) when is_list(Sublist) andalso is_binary(C) ->
  243. 'in'(Sublist, [binary_to_list(C)|Rest]);
  244. 'in'(Sublist, [C|Rest]) when is_list(Sublist) andalso is_list(C) ->
  245. 'in'(Sublist, Rest);
  246. 'in'(Sublist, List) when is_list(Sublist) andalso is_list(List) ->
  247. string:str(List, Sublist) > 0;
  248. 'in'(Element, List) when is_list(List) ->
  249. lists:member(Element, List);
  250. 'in'(_, _) ->
  251. false.
  252. 'not'(Value) ->
  253. not is_true(Value).
  254. 'or'(Value1, Value2) ->
  255. is_true(Value1) or is_true(Value2).
  256. 'and'(Value1, Value2) ->
  257. is_true(Value1) and is_true(Value2).
  258. 'eq'(Value1, Value2) ->
  259. are_equal(Value1, Value2).
  260. 'ne'(Value1, Value2) ->
  261. not are_equal(Value1, Value2).
  262. 'le'(Value1, Value2) ->
  263. not 'gt'(Value1, Value2).
  264. 'ge'(Value1, Value2) ->
  265. not 'lt'(Value1, Value2).
  266. 'gt'(Value1, Value2) when is_list(Value1) ->
  267. 'gt'(list_to_integer(Value1), Value2);
  268. 'gt'(Value1, Value2) when is_list(Value2) ->
  269. 'gt'(Value1, list_to_integer(Value2));
  270. 'gt'(Value1, Value2) when Value1 > Value2 ->
  271. true;
  272. 'gt'(_, _) ->
  273. false.
  274. 'lt'(Value1, Value2) when is_list(Value1) ->
  275. 'lt'(list_to_integer(Value1), Value2);
  276. 'lt'(Value1, Value2) when is_list(Value2) ->
  277. 'lt'(Value1, list_to_integer(Value2));
  278. 'lt'(Value1, Value2) when Value1 < Value2 ->
  279. true;
  280. 'lt'(_, _) ->
  281. false.
  282. stringify_final(In, BinaryStrings) ->
  283. stringify_final(In, [], BinaryStrings).
  284. stringify_final([], Out, _) ->
  285. lists:reverse(Out);
  286. stringify_final([El | Rest], Out, false = BinaryStrings) when is_atom(El) ->
  287. stringify_final(Rest, [atom_to_list(El) | Out], BinaryStrings);
  288. stringify_final([El | Rest], Out, true = BinaryStrings) when is_atom(El) ->
  289. stringify_final(Rest, [atom_to_binary(El, latin1) | Out], BinaryStrings);
  290. stringify_final([El | Rest], Out, BinaryStrings) when is_list(El) ->
  291. stringify_final(Rest, [stringify_final(El, BinaryStrings) | Out], BinaryStrings);
  292. stringify_final([El | Rest], Out, false = BinaryStrings) when is_tuple(El) ->
  293. stringify_final(Rest, [io_lib:print(El) | Out], BinaryStrings);
  294. stringify_final([El | Rest], Out, true = BinaryStrings) when is_tuple(El) ->
  295. stringify_final(Rest, [list_to_binary(io_lib:print(El)) | Out], BinaryStrings);
  296. stringify_final([El | Rest], Out, BinaryStrings) ->
  297. stringify_final(Rest, [El | Out], BinaryStrings).
  298. to_list(Value, true) ->
  299. lists:reverse(to_list(Value, false));
  300. to_list(Value, false) when is_list(Value) ->
  301. Value;
  302. to_list(Value, false) when is_tuple(Value) ->
  303. case element(1, Value) of
  304. 'Elixir.Ecto.Associations.HasMany' ->
  305. Value:to_list();
  306. _ ->
  307. tuple_to_list(Value)
  308. end.
  309. init_counter_stats(List) ->
  310. init_counter_stats(List, undefined).
  311. init_counter_stats(List, Parent) when is_list(List) ->
  312. ListLen = length(List),
  313. [{counter, 1},
  314. {counter0, 0},
  315. {revcounter, ListLen},
  316. {revcounter0, ListLen - 1},
  317. {first, true},
  318. {last, ListLen =:= 1},
  319. {parentloop, Parent}].
  320. increment_counter_stats([{counter, Counter}, {counter0, Counter0}, {revcounter, RevCounter},
  321. {revcounter0, RevCounter0}, {first, _}, {last, _}, {parentloop, Parent}]) ->
  322. [{counter, Counter + 1},
  323. {counter0, Counter0 + 1},
  324. {revcounter, RevCounter - 1},
  325. {revcounter0, RevCounter0 - 1},
  326. {first, false}, {last, RevCounter0 =:= 1},
  327. {parentloop, Parent}].
  328. forloop(_Fun, [], _Parent, Default) -> Default;
  329. forloop(Fun, Values, Parent, _Default) ->
  330. push_ifchanged_context(),
  331. {Result, _Acc} = lists:mapfoldl(Fun, init_counter_stats(Values, Parent), Values),
  332. pop_ifchanged_context(),
  333. Result.
  334. %% keep old version for backwards compatibility..
  335. forloop(_Fun, [], _Parent) -> empty;
  336. forloop(Fun, Values, Parent) ->
  337. {forloop(Fun, Values, Parent, undefined), undefined}.
  338. push_ifchanged_context() ->
  339. IfChangedContextStack = case get(?IFCHANGED_CONTEXT_VARIABLE) of
  340. undefined -> [];
  341. Stack -> Stack
  342. end,
  343. put(?IFCHANGED_CONTEXT_VARIABLE, [[]|IfChangedContextStack]).
  344. pop_ifchanged_context() ->
  345. [_|Rest] = get(?IFCHANGED_CONTEXT_VARIABLE),
  346. put(?IFCHANGED_CONTEXT_VARIABLE, Rest).
  347. ifchanged(Expressions) ->
  348. [IfChangedContext|Rest] = get(?IFCHANGED_CONTEXT_VARIABLE),
  349. {Result, NewContext} = lists:foldl(fun (Expr, {ProvResult, Context}) when ProvResult == true ->
  350. {_, NContext} = ifchanged2(Expr, Context),
  351. {true, NContext};
  352. (Expr, {_ProvResult, Context}) ->
  353. ifchanged2(Expr, Context)
  354. end, {false, IfChangedContext}, Expressions),
  355. put(?IFCHANGED_CONTEXT_VARIABLE, [NewContext|Rest]),
  356. Result.
  357. ifchanged2({Key, Value}, IfChangedContext) ->
  358. PreviousValue = proplists:get_value(Key, IfChangedContext),
  359. if
  360. PreviousValue =:= Value ->
  361. {false, IfChangedContext};
  362. true ->
  363. NewContext = [{Key, Value}|proplists:delete(Key, IfChangedContext)],
  364. {true, NewContext}
  365. end.
  366. cycle(NamesTuple, Counters) when is_tuple(NamesTuple) ->
  367. element(find_value(counter0, Counters) rem size(NamesTuple) + 1, NamesTuple).
  368. widthratio(Numerator, Denominator, Scale) ->
  369. round(Numerator / Denominator * Scale).
  370. spaceless(Contents) ->
  371. Contents1 = lists:flatten(Contents),
  372. Contents2 = re:replace(Contents1, "^\\s+<", "<", [{return,list}]),
  373. Contents3 = re:replace(Contents2, ">\\s+$", ">", [{return,list}]),
  374. Contents4 = re:replace(Contents3, ">\\s+<", "><", [global, {return,list}]),
  375. Contents4.
  376. read_file(Module, Function, DocRoot, FileName) ->
  377. AbsName = case filename:absname(FileName) of
  378. FileName -> FileName;
  379. _ -> filename:join([DocRoot, FileName])
  380. end,
  381. case Module:Function(AbsName) of
  382. {ok, Data} -> Data;
  383. {error, Reason} ->
  384. throw({read_file, AbsName, Reason})
  385. end.