erlydtl_runtime.erl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. fetch_value(Key, Data, Options) ->
  104. fetch_value(Key, Data, Options, []).
  105. fetch_value(Key, Data, Options, Default) ->
  106. case find_value(Key, Data, Options) of
  107. undefined -> Default;
  108. Val -> Val
  109. end.
  110. find_deep_value([Key|Rest],Item) ->
  111. case find_value(Key,Item) of
  112. undefined -> undefined;
  113. NewItem -> find_deep_value(Rest,NewItem)
  114. end;
  115. find_deep_value([],Item) -> Item.
  116. regroup(List, Attribute) ->
  117. regroup(List, Attribute, []).
  118. regroup([], _, []) ->
  119. [];
  120. regroup([], _, [[{grouper, LastGrouper}, {list, LastList}]|Acc]) ->
  121. lists:reverse([[{grouper, LastGrouper}, {list, lists:reverse(LastList)}]|Acc]);
  122. regroup([Item|Rest], Attribute, []) ->
  123. regroup(Rest, Attribute, [[{grouper, find_deep_value(Attribute, Item)}, {list, [Item]}]]);
  124. regroup([Item|Rest], Attribute, [[{grouper, PrevGrouper}, {list, PrevList}]|Acc]) ->
  125. case find_deep_value(Attribute, Item) of
  126. Value when Value =:= PrevGrouper ->
  127. regroup(Rest, Attribute, [[{grouper, PrevGrouper}, {list, [Item|PrevList]}]|Acc]);
  128. Value ->
  129. regroup(Rest, Attribute, [[{grouper, Value}, {list, [Item]}], [{grouper, PrevGrouper}, {list, lists:reverse(PrevList)}]|Acc])
  130. end.
  131. -spec init_translation(init_translation()) -> none | translate_fun().
  132. init_translation(none) -> none;
  133. init_translation(Fun) when is_function(Fun, 0) ->
  134. init_translation(Fun());
  135. init_translation({M, F}) ->
  136. init_translation({M, F, []});
  137. init_translation({M, F, A}) ->
  138. init_translation(apply(M, F, A));
  139. init_translation(Fun)
  140. when is_function(Fun, 1); is_function(Fun, 2) -> Fun;
  141. init_translation(Other) ->
  142. throw({translation_fun, Other}).
  143. -spec translate(Phrase, Locale, Fun) -> iodata() | default when
  144. Phrase :: phrase(),
  145. Locale :: locale(),
  146. Fun :: none | translate_fun().
  147. translate(Phrase, Locale, TranslationFun) ->
  148. translate(Phrase, Locale, TranslationFun, trans_text(Phrase)).
  149. translate(_Phrase, _Locale, none, Default) -> Default;
  150. translate(Phrase, Locale, TranslationFun, Default) ->
  151. case do_translate(Phrase, Locale, TranslationFun) of
  152. default -> Default;
  153. <<"">> -> Default;
  154. "" -> Default;
  155. Translated ->
  156. Translated
  157. end.
  158. trans_text({Text, _}) -> Text;
  159. trans_text(Text) -> Text.
  160. do_translate(Phrase, _Locale, TranslationFun)
  161. when is_function(TranslationFun, 1) ->
  162. TranslationFun(trans_text(Phrase));
  163. do_translate(Phrase, Locale, TranslationFun)
  164. when is_function(TranslationFun, 2) ->
  165. TranslationFun(Phrase, Locale).
  166. %% @doc Translate and interpolate 'blocktrans' content.
  167. %% Pre-requisites:
  168. %% * `Variables' should be sorted
  169. %% * Each interpolation variable should exist
  170. %% (String="{{a}}", Variables=[{"b", "b-val"}] will fall)
  171. %% * Orddict keys should be string(), not binary()
  172. -spec translate_block(phrase(), locale(), orddict:orddict(), none | translate_fun()) -> iodata().
  173. translate_block(Phrase, Locale, Variables, TranslationFun) ->
  174. case translate(Phrase, Locale, TranslationFun, default) of
  175. default -> default;
  176. Translated ->
  177. try interpolate_variables(Translated, Variables)
  178. catch
  179. {no_close_var, T} ->
  180. io:format(standard_error, "Warning: template translation: variable not closed: \"~s\"~n", [T]),
  181. default;
  182. _:_ -> default
  183. end
  184. end.
  185. interpolate_variables(Tpl, []) ->
  186. Tpl;
  187. interpolate_variables(Tpl, Variables) ->
  188. BTpl = iolist_to_binary(Tpl),
  189. interpolate_variables1(BTpl, Variables).
  190. interpolate_variables1(Tpl, Vars) ->
  191. %% pre-compile binary patterns?
  192. case binary:split(Tpl, <<"{{">>) of
  193. [Tpl]=NoVars -> NoVars; %% need to enclose in list due to list tail call below..
  194. [Pre, Post] ->
  195. case binary:split(Post, <<"}}">>) of
  196. [_] -> throw({no_close_var, Tpl});
  197. [Var, Post1] ->
  198. Var1 = string:strip(binary_to_list(Var)),
  199. Value = orddict:fetch(Var1, Vars),
  200. [Pre, Value | interpolate_variables1(Post1, Vars)]
  201. end
  202. end.
  203. are_equal(Arg1, Arg2) when Arg1 =:= Arg2 ->
  204. true;
  205. are_equal(Arg1, Arg2) when is_binary(Arg1) ->
  206. are_equal(binary_to_list(Arg1), Arg2);
  207. are_equal(Arg1, Arg2) when is_binary(Arg2) ->
  208. are_equal(Arg1, binary_to_list(Arg2));
  209. are_equal(Arg1, Arg2) when is_integer(Arg1) ->
  210. are_equal(integer_to_list(Arg1), Arg2);
  211. are_equal(Arg1, Arg2) when is_integer(Arg2) ->
  212. are_equal(Arg1, integer_to_list(Arg2));
  213. are_equal(Arg1, Arg2) when is_atom(Arg1), is_list(Arg2) ->
  214. are_equal(atom_to_list(Arg1), Arg2);
  215. are_equal(Arg1, Arg2) when is_list(Arg1), is_atom(Arg2) ->
  216. are_equal(Arg1, atom_to_list(Arg2));
  217. are_equal(_, _) ->
  218. false.
  219. is_false("") -> true;
  220. is_false(false) -> true;
  221. is_false(undefined) -> true;
  222. is_false(0) -> true;
  223. is_false("0") -> true;
  224. is_false(<<"0">>) -> true;
  225. is_false(<<>>) -> true;
  226. is_false(_) -> false.
  227. is_true(V) -> not is_false(V).
  228. 'in'(Sublist, [Sublist|_]) ->
  229. true;
  230. 'in'(Sublist, List) when is_atom(List) ->
  231. 'in'(Sublist, atom_to_list(List));
  232. 'in'(Sublist, List) when is_binary(Sublist) ->
  233. 'in'(binary_to_list(Sublist), List);
  234. 'in'(Sublist, List) when is_binary(List) ->
  235. 'in'(Sublist, binary_to_list(List));
  236. 'in'(Sublist, [C|Rest]) when is_list(Sublist) andalso is_binary(C) ->
  237. 'in'(Sublist, [binary_to_list(C)|Rest]);
  238. 'in'(Sublist, [C|Rest]) when is_list(Sublist) andalso is_list(C) ->
  239. 'in'(Sublist, Rest);
  240. 'in'(Sublist, List) when is_list(Sublist) andalso is_list(List) ->
  241. string:str(List, Sublist) > 0;
  242. 'in'(Element, List) when is_list(List) ->
  243. lists:member(Element, List);
  244. 'in'(_, _) ->
  245. false.
  246. 'not'(Value) ->
  247. not is_true(Value).
  248. 'or'(Value1, Value2) ->
  249. is_true(Value1) or is_true(Value2).
  250. 'and'(Value1, Value2) ->
  251. is_true(Value1) and is_true(Value2).
  252. 'eq'(Value1, Value2) ->
  253. are_equal(Value1, Value2).
  254. 'ne'(Value1, Value2) ->
  255. not are_equal(Value1, Value2).
  256. 'le'(Value1, Value2) ->
  257. not 'gt'(Value1, Value2).
  258. 'ge'(Value1, Value2) ->
  259. not 'lt'(Value1, Value2).
  260. 'gt'(Value1, Value2) when is_list(Value1) ->
  261. 'gt'(list_to_integer(Value1), Value2);
  262. 'gt'(Value1, Value2) when is_list(Value2) ->
  263. 'gt'(Value1, list_to_integer(Value2));
  264. 'gt'(Value1, Value2) when Value1 > Value2 ->
  265. true;
  266. 'gt'(_, _) ->
  267. false.
  268. 'lt'(Value1, Value2) when is_list(Value1) ->
  269. 'lt'(list_to_integer(Value1), Value2);
  270. 'lt'(Value1, Value2) when is_list(Value2) ->
  271. 'lt'(Value1, list_to_integer(Value2));
  272. 'lt'(Value1, Value2) when Value1 < Value2 ->
  273. true;
  274. 'lt'(_, _) ->
  275. false.
  276. stringify_final(In, BinaryStrings) ->
  277. stringify_final(In, [], BinaryStrings).
  278. stringify_final([], Out, _) ->
  279. lists:reverse(Out);
  280. stringify_final([El | Rest], Out, false = BinaryStrings) when is_atom(El) ->
  281. stringify_final(Rest, [atom_to_list(El) | Out], BinaryStrings);
  282. stringify_final([El | Rest], Out, true = BinaryStrings) when is_atom(El) ->
  283. stringify_final(Rest, [atom_to_binary(El, latin1) | Out], BinaryStrings);
  284. stringify_final([El | Rest], Out, BinaryStrings) when is_list(El) ->
  285. stringify_final(Rest, [stringify_final(El, BinaryStrings) | Out], BinaryStrings);
  286. stringify_final([El | Rest], Out, false = BinaryStrings) when is_tuple(El) ->
  287. stringify_final(Rest, [io_lib:print(El) | Out], BinaryStrings);
  288. stringify_final([El | Rest], Out, true = BinaryStrings) when is_tuple(El) ->
  289. stringify_final(Rest, [list_to_binary(io_lib:print(El)) | Out], BinaryStrings);
  290. stringify_final([El | Rest], Out, BinaryStrings) ->
  291. stringify_final(Rest, [El | Out], BinaryStrings).
  292. to_list(Value, true) ->
  293. lists:reverse(to_list(Value, false));
  294. to_list(Value, false) when is_list(Value) ->
  295. Value;
  296. to_list(Value, false) when is_tuple(Value) ->
  297. case element(1, Value) of
  298. 'Elixir.Ecto.Associations.HasMany' ->
  299. Value:to_list();
  300. _ ->
  301. tuple_to_list(Value)
  302. end.
  303. init_counter_stats(List) ->
  304. init_counter_stats(List, undefined).
  305. init_counter_stats(List, Parent) when is_list(List) ->
  306. ListLen = length(List),
  307. [{counter, 1},
  308. {counter0, 0},
  309. {revcounter, ListLen},
  310. {revcounter0, ListLen - 1},
  311. {first, true},
  312. {last, ListLen =:= 1},
  313. {parentloop, Parent}].
  314. increment_counter_stats([{counter, Counter}, {counter0, Counter0}, {revcounter, RevCounter},
  315. {revcounter0, RevCounter0}, {first, _}, {last, _}, {parentloop, Parent}]) ->
  316. [{counter, Counter + 1},
  317. {counter0, Counter0 + 1},
  318. {revcounter, RevCounter - 1},
  319. {revcounter0, RevCounter0 - 1},
  320. {first, false}, {last, RevCounter0 =:= 1},
  321. {parentloop, Parent}].
  322. forloop(_Fun, [], _Parent) -> empty;
  323. forloop(Fun, Values, Parent) ->
  324. push_ifchanged_context(),
  325. Result = lists:mapfoldl(Fun, init_counter_stats(Values, Parent), Values),
  326. pop_ifchanged_context(),
  327. Result.
  328. push_ifchanged_context() ->
  329. IfChangedContextStack = case get(?IFCHANGED_CONTEXT_VARIABLE) of
  330. undefined -> [];
  331. Stack -> Stack
  332. end,
  333. put(?IFCHANGED_CONTEXT_VARIABLE, [[]|IfChangedContextStack]).
  334. pop_ifchanged_context() ->
  335. [_|Rest] = get(?IFCHANGED_CONTEXT_VARIABLE),
  336. put(?IFCHANGED_CONTEXT_VARIABLE, Rest).
  337. ifchanged(Expressions) ->
  338. [IfChangedContext|Rest] = get(?IFCHANGED_CONTEXT_VARIABLE),
  339. {Result, NewContext} = lists:foldl(fun (Expr, {ProvResult, Context}) when ProvResult == true ->
  340. {_, NContext} = ifchanged2(Expr, Context),
  341. {true, NContext};
  342. (Expr, {_ProvResult, Context}) ->
  343. ifchanged2(Expr, Context)
  344. end, {false, IfChangedContext}, Expressions),
  345. put(?IFCHANGED_CONTEXT_VARIABLE, [NewContext|Rest]),
  346. Result.
  347. ifchanged2({Key, Value}, IfChangedContext) ->
  348. PreviousValue = proplists:get_value(Key, IfChangedContext),
  349. if
  350. PreviousValue =:= Value ->
  351. {false, IfChangedContext};
  352. true ->
  353. NewContext = [{Key, Value}|proplists:delete(Key, IfChangedContext)],
  354. {true, NewContext}
  355. end.
  356. cycle(NamesTuple, Counters) when is_tuple(NamesTuple) ->
  357. element(find_value(counter0, Counters) rem size(NamesTuple) + 1, NamesTuple).
  358. widthratio(Numerator, Denominator, Scale) ->
  359. round(Numerator / Denominator * Scale).
  360. spaceless(Contents) ->
  361. Contents1 = lists:flatten(Contents),
  362. Contents2 = re:replace(Contents1, "^\\s+<", "<", [{return,list}]),
  363. Contents3 = re:replace(Contents2, ">\\s+$", ">", [{return,list}]),
  364. Contents4 = re:replace(Contents3, ">\\s+<", "><", [global, {return,list}]),
  365. Contents4.
  366. read_file(Module, Function, DocRoot, FileName) ->
  367. AbsName = case filename:absname(FileName) of
  368. FileName -> FileName;
  369. _ -> filename:join([DocRoot, FileName])
  370. end,
  371. case Module:Function(AbsName) of
  372. {ok, Data} -> Data;
  373. {error, Reason} ->
  374. throw({read_file, AbsName, Reason})
  375. end.