erlydtl_beam_compiler.erl 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  1. %%%-------------------------------------------------------------------
  2. %%% File: erlydtl_beam_compiler.erl
  3. %%% @author Roberto Saccon <rsaccon@gmail.com> [http://rsaccon.com]
  4. %%% @author Evan Miller <emmiller@gmail.com>
  5. %%% @author Andreas Stenius <kaos@astekk.se>
  6. %%% @copyright 2008 Roberto Saccon, Evan Miller
  7. %%% @copyright 2014 Andreas Stenius
  8. %%% @doc
  9. %%% ErlyDTL template compiler for beam targets.
  10. %%% @end
  11. %%%
  12. %%% The MIT License
  13. %%%
  14. %%% Copyright (c) 2007 Roberto Saccon, Evan Miller
  15. %%% Copyright (c) 2014 Andreas Stenius
  16. %%%
  17. %%% Permission is hereby granted, free of charge, to any person obtaining a copy
  18. %%% of this software and associated documentation files (the "Software"), to deal
  19. %%% in the Software without restriction, including without limitation the rights
  20. %%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. %%% copies of the Software, and to permit persons to whom the Software is
  22. %%% furnished to do so, subject to the following conditions:
  23. %%%
  24. %%% The above copyright notice and this permission notice shall be included in
  25. %%% all copies or substantial portions of the Software.
  26. %%%
  27. %%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28. %%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29. %%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  30. %%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31. %%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  32. %%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  33. %%% THE SOFTWARE.
  34. %%%
  35. %%% @since 2007-12-16 by Roberto Saccon, Evan Miller
  36. %%% @since 2014 by Andreas Stenius
  37. %%%-------------------------------------------------------------------
  38. -module(erlydtl_beam_compiler).
  39. -author('rsaccon@gmail.com').
  40. -author('emmiller@gmail.com').
  41. -author('Andreas Stenius <kaos@astekk.se>').
  42. %% --------------------------------------------------------------------
  43. %% Definitions
  44. %% --------------------------------------------------------------------
  45. -export([compile/3, compile_dir/2, format_error/1]).
  46. %% internal use
  47. -export([
  48. is_up_to_date/2,
  49. format/1,
  50. value_ast/4,
  51. interpret_args/2
  52. ]).
  53. -import(erlydtl_compiler, [parse_file/2, do_parse_template/2]).
  54. -import(erlydtl_compiler_utils,
  55. [unescape_string_literal/1, full_path/2, push_scope/2,
  56. restore_scope/2, begin_scope/1, begin_scope/2, end_scope/4,
  57. empty_scope/0, get_current_file/1, add_errors/2,
  58. add_warnings/2, merge_info/2, call_extension/3,
  59. init_treewalker/1, resolve_variable/2, resolve_variable/3,
  60. reset_parse_trail/2, load_library/3, load_library/4,
  61. shorten_filename/2, push_auto_escape/2, pop_auto_escape/1]).
  62. -include_lib("merl/include/merl.hrl").
  63. -include("erlydtl_ext.hrl").
  64. %% --------------------------------------------------------------------
  65. %% API
  66. %% --------------------------------------------------------------------
  67. compile(DjangoParseTree, CheckSum, Context) ->
  68. compile_to_binary(DjangoParseTree, CheckSum, Context).
  69. compile_dir(Dir, Context) ->
  70. do_compile_dir(Dir, Context).
  71. format_error(no_out_dir) ->
  72. "Compiled template not saved (need out_dir option)";
  73. format_error(unexpected_extends_tag) ->
  74. "The extends tag must be at the very top of the template";
  75. format_error(circular_include) ->
  76. "Circular file inclusion!";
  77. format_error({write_file, Error}) ->
  78. io_lib:format(
  79. "Failed to write file: ~s",
  80. [file:format_error(Error)]);
  81. format_error(compile_beam) ->
  82. "Failed to compile template to BEAM code";
  83. format_error({unknown_filter, Name, Arity}) ->
  84. io_lib:format("Unknown filter '~p' (arity ~p)", [Name, Arity]);
  85. format_error({filter_args, Name, {Mod, Fun}, Arity}) ->
  86. io_lib:format("Wrong number of arguments to filter '~p' (~p:~p): ~p", [Name, Mod, Fun, Arity]);
  87. format_error({missing_tag, Name, {Mod, Fun}}) ->
  88. io_lib:format("Custom tag '~p' not exported (~p:~p)", [Name, Mod, Fun]);
  89. format_error({bad_tag, Name, {Mod, Fun}, Arity}) ->
  90. io_lib:format("Invalid tag '~p' (~p:~p/~p)", [Name, Mod, Fun, Arity]);
  91. format_error({load_code, Error}) ->
  92. io_lib:format("Failed to load BEAM code: ~p", [Error]);
  93. format_error({reserved_variable, ReservedName}) ->
  94. io_lib:format("Variable '~s' is reserved for internal use.", [ReservedName]);
  95. format_error({translation_fun, Fun}) ->
  96. io_lib:format("Invalid translation function: ~s~n",
  97. [if is_function(Fun) ->
  98. Info = erlang:fun_info(Fun),
  99. io_lib:format("~s:~s/~p", [proplists:get_value(K, Info) || K <- [module, name, arity]]);
  100. true -> io_lib:format("~p", [Fun])
  101. end]);
  102. format_error(Error) ->
  103. erlydtl_compiler:format_error(Error).
  104. %%====================================================================
  105. %% Internal functions
  106. %%====================================================================
  107. do_compile_dir(Dir, Context) ->
  108. %% Find all files in Dir (recursively), matching the regex (no
  109. %% files ending in "~").
  110. Files = filelib:fold_files(Dir, ".+[^~]$", true, fun(F1,Acc1) -> [F1 | Acc1] end, []),
  111. {ParserResults,
  112. #dtl_context{ errors=#error_info{ list=ParserErrors } }=Context1}
  113. = lists:foldl(
  114. fun (File, {ResultAcc, Ctx}) ->
  115. case filename:basename(File) of
  116. "."++_ ->
  117. {ResultAcc, Ctx};
  118. _ ->
  119. FilePath = filename:absname(File),
  120. case filelib:is_dir(FilePath) of
  121. true ->
  122. {ResultAcc, Ctx};
  123. false ->
  124. case parse_file(FilePath, Ctx) of
  125. up_to_date -> {ResultAcc, Ctx};
  126. {ok, DjangoParseTree, CheckSum} ->
  127. {[{FilePath, DjangoParseTree, CheckSum}|ResultAcc], Ctx};
  128. {error, Reason} -> {ResultAcc, ?ERR(Reason, Ctx)}
  129. end
  130. end
  131. end
  132. end,
  133. {[], Context},
  134. Files),
  135. if length(ParserErrors) == 0 ->
  136. compile_multiple_to_binary(Dir, ParserResults, Context1);
  137. true -> Context1
  138. end.
  139. compile_multiple_to_binary(Dir, ParserResults, Context) ->
  140. MatchAst = options_match_ast(Context),
  141. {Functions,
  142. {AstInfo,
  143. #treewalker{
  144. context=#dtl_context{
  145. errors=#error_info{ list=Errors }
  146. }=Context1 } }
  147. } = lists:mapfoldl(
  148. fun ({File, DjangoParseTree, CheckSum},
  149. {AstInfo, #treewalker{ context=Ctx }=TreeWalker}) ->
  150. try
  151. FilePath = full_path(File, Ctx#dtl_context.doc_root),
  152. {{BodyAst, BodyInfo}, TreeWalker1} = with_dependency(
  153. {FilePath, CheckSum},
  154. body_ast(DjangoParseTree, TreeWalker)),
  155. FunctionName = filename:rootname(filename:basename(File)),
  156. FunctionDefs = ?Q(["'@func'(Variables) -> _@func(Variables, []).",
  157. "'@func'(_Variables, RenderOptions) ->",
  158. " _@MatchAst, _@body."],
  159. [{func, erl_syntax:atom(FunctionName)},
  160. {body, stringify(BodyAst, Ctx)}]),
  161. {{FunctionName, FunctionDefs}, {merge_info(AstInfo, BodyInfo), TreeWalker1}}
  162. catch
  163. throw:Error ->
  164. {error, {AstInfo, TreeWalker#treewalker{ context=?ERR(Error, Ctx) }}}
  165. end
  166. end,
  167. {#ast_info{}, init_treewalker(Context)},
  168. ParserResults),
  169. if length(Errors) == 0 ->
  170. Forms = custom_forms(Dir, Context1#dtl_context.module, Functions, AstInfo),
  171. compile_forms(Forms, Context1);
  172. true ->
  173. Context1
  174. end.
  175. compile_to_binary(DjangoParseTree, CheckSum, Context) ->
  176. try body_ast(DjangoParseTree, init_treewalker(Context)) of
  177. {{BodyAst, BodyInfo}, BodyTreeWalker} ->
  178. try custom_tags_ast(BodyInfo#ast_info.custom_tags, BodyTreeWalker) of
  179. {CustomTags,
  180. #treewalker{
  181. context=#dtl_context{
  182. errors=#error_info{ list=Errors }
  183. } }=CustomTagsTreeWalker}
  184. when length(Errors) == 0 ->
  185. Forms = forms(
  186. {BodyAst, BodyInfo},
  187. CustomTags, CheckSum,
  188. CustomTagsTreeWalker),
  189. compile_forms(Forms, CustomTagsTreeWalker#treewalker.context);
  190. {_, #treewalker{ context=Context1 }} ->
  191. Context1
  192. catch
  193. throw:Error -> ?ERR(Error, BodyTreeWalker#treewalker.context)
  194. end
  195. catch
  196. throw:Error -> ?ERR(Error, Context)
  197. end.
  198. compile_forms(Forms, Context) ->
  199. maybe_debug_template(Forms, Context),
  200. Options = Context#dtl_context.compiler_options,
  201. case compile:forms(Forms, Options) of
  202. Compiled when element(1, Compiled) =:= ok ->
  203. [ok, Module, Bin|Info] = tuple_to_list(Compiled),
  204. lists:foldl(
  205. fun (F, C) -> F(Module, Bin, C) end,
  206. Context#dtl_context{ bin=Bin },
  207. [fun maybe_write/3,
  208. fun maybe_load/3,
  209. fun (_, _, C) ->
  210. case Info of
  211. [Ws] when length(Ws) > 0 ->
  212. add_warnings(Ws, C);
  213. _ -> C
  214. end
  215. end
  216. ]);
  217. error ->
  218. ?ERR(compile_beam, Context);
  219. {error, Es, Ws} ->
  220. add_warnings(Ws, add_errors(Es, Context))
  221. end.
  222. maybe_write(Module, Bin, Context) ->
  223. case proplists:get_value(out_dir, Context#dtl_context.all_options) of
  224. false -> Context;
  225. undefined ->
  226. ?WARN(no_out_dir, Context);
  227. OutDir ->
  228. BeamFile = filename:join([OutDir, [Module, ".beam"]]),
  229. ?LOG_INFO("Template module: ~w -> ~s\n", [Module, BeamFile], Context),
  230. case file:write_file(BeamFile, Bin) of
  231. ok -> Context;
  232. {error, Reason} ->
  233. ?ERR({write_file, Reason}, Context)
  234. end
  235. end.
  236. maybe_load(Module, Bin, Context) ->
  237. case proplists:get_bool(no_load, Context#dtl_context.all_options) of
  238. true -> Context;
  239. false -> load_code(Module, Bin, Context)
  240. end.
  241. load_code(Module, Bin, Context) ->
  242. code:purge(Module),
  243. case code:load_binary(Module, atom_to_list(Module) ++ ".erl", Bin) of
  244. {module, Module} -> Context;
  245. Error -> ?WARN({load_code, Error}, Context)
  246. end.
  247. maybe_debug_template(Forms, Context) ->
  248. case proplists:get_bool(debug_compiler, Context#dtl_context.all_options) of
  249. false -> nop;
  250. true ->
  251. Options = Context#dtl_context.compiler_options,
  252. ?LOG_DEBUG("Compiler options: ~p~n", [Options], Context),
  253. try
  254. Source = erl_prettypr:format(erl_syntax:form_list(Forms)),
  255. SourceFile = lists:concat(
  256. [proplists:get_value(source, Options),".erl"]),
  257. File = case proplists:get_value(
  258. debug_root,
  259. Context#dtl_context.all_options) of
  260. false -> undefined;
  261. undefined -> SourceFile;
  262. Dir ->
  263. Abs = filename:absname(
  264. shorten_filename(
  265. SourceFile,
  266. Context#dtl_context.doc_root),
  267. Dir),
  268. case filelib:ensure_dir(Abs) of
  269. ok -> Abs;
  270. {error, Reason} ->
  271. io:format(
  272. "Failed to ensure directories for file '~s': ~p~n",
  273. [Abs, Reason]),
  274. undefined
  275. end
  276. end,
  277. if File =/= undefined ->
  278. io:format("Saving template source to: ~s.. ~p~n",
  279. [File, file:write_file(File, Source)]);
  280. true -> ok
  281. end
  282. catch
  283. error:Err ->
  284. io:format("Pretty printing failed: ~p~n"
  285. "Context: ~n~p~n"
  286. "Forms: ~n~p~n",
  287. [Err, Context, Forms])
  288. end
  289. end.
  290. is_up_to_date(CheckSum, Context) ->
  291. Module = Context#dtl_context.module,
  292. {M, F} = Context#dtl_context.reader,
  293. case catch Module:source() of
  294. {_, CheckSum} ->
  295. case catch Module:dependencies() of
  296. L when is_list(L) ->
  297. RecompileList = lists:foldl(
  298. fun ({XFile, XCheckSum}, Acc) ->
  299. case catch M:F(XFile) of
  300. {ok, Data} ->
  301. case binary_to_list(erlang:md5(Data)) of
  302. XCheckSum ->
  303. Acc;
  304. _ ->
  305. [recompile | Acc]
  306. end;
  307. _ ->
  308. [recompile | Acc]
  309. end
  310. end, [], L),
  311. case RecompileList of
  312. [] -> true;
  313. _ -> false
  314. end;
  315. _ ->
  316. false
  317. end;
  318. _ ->
  319. false
  320. end.
  321. %%====================================================================
  322. %% AST functions
  323. %%====================================================================
  324. custom_tags_ast(CustomTags, TreeWalker) ->
  325. %% avoid adding the render_tag/3 fun if it isn't used,
  326. %% since we can't add a -compile({nowarn_unused_function, render_tag/3}).
  327. %% attribute due to a bug in syntax_tools.
  328. case custom_tags_clauses_ast(CustomTags, TreeWalker) of
  329. skip ->
  330. {{erl_syntax:comment(
  331. ["% render_tag/3 is not used in this template."]),
  332. #ast_info{}},
  333. TreeWalker};
  334. {{CustomTagsClauses, CustomTagsInfo}, TreeWalker1} ->
  335. {{erl_syntax:function(
  336. erl_syntax:atom(render_tag),
  337. CustomTagsClauses),
  338. CustomTagsInfo},
  339. TreeWalker1}
  340. end.
  341. custom_tags_clauses_ast([], _TreeWalker) -> skip;
  342. custom_tags_clauses_ast(CustomTags, TreeWalker) ->
  343. custom_tags_clauses_ast1(CustomTags, [], [], #ast_info{}, TreeWalker).
  344. custom_tags_clauses_ast1([], _ExcludeTags, ClauseAcc, InfoAcc, TreeWalker) ->
  345. {{DefaultAst, DefaultInfo}, TreeWalker1} =
  346. case call_extension(TreeWalker, custom_tag_ast, [TreeWalker]) of
  347. undefined ->
  348. {{?Q("(_TagName, _, _) -> []"), InfoAcc}, TreeWalker};
  349. {{ExtAst, ExtInfo}, ExtTreeWalker} ->
  350. Clause = ?Q("(TagName, _Variables, RenderOptions) -> _@tag",
  351. [{tag, options_match_ast(ExtTreeWalker) ++ [ExtAst]}]),
  352. {{Clause, merge_info(ExtInfo, InfoAcc)}, ExtTreeWalker}
  353. end,
  354. {{lists:reverse([DefaultAst|ClauseAcc]), DefaultInfo}, TreeWalker1};
  355. custom_tags_clauses_ast1([Tag|CustomTags], ExcludeTags, ClauseAcc, InfoAcc, TreeWalker) ->
  356. case lists:member(Tag, ExcludeTags) of
  357. true ->
  358. custom_tags_clauses_ast1(CustomTags, ExcludeTags, ClauseAcc, InfoAcc, TreeWalker);
  359. false ->
  360. Context = TreeWalker#treewalker.context,
  361. CustomTagFile = full_path(Tag, Context#dtl_context.custom_tags_dir),
  362. case filelib:is_file(CustomTagFile) of
  363. true ->
  364. case parse_file(CustomTagFile, Context) of
  365. {ok, DjangoParseTree, CheckSum} ->
  366. {{BodyAst, BodyAstInfo}, TreeWalker1} = with_dependency(
  367. {CustomTagFile, CheckSum},
  368. body_ast(DjangoParseTree, TreeWalker)),
  369. MatchAst = options_match_ast(TreeWalker1),
  370. Clause = ?Q("(_@Tag@, _Variables, RenderOptions) -> _@MatchAst, _@BodyAst"),
  371. custom_tags_clauses_ast1(
  372. CustomTags, [Tag|ExcludeTags], [Clause|ClauseAcc],
  373. merge_info(BodyAstInfo, InfoAcc), TreeWalker1);
  374. {error, Reason} ->
  375. empty_ast(?ERR(Reason, TreeWalker))
  376. end;
  377. false ->
  378. case call_extension(TreeWalker, custom_tag_ast, [Tag, TreeWalker]) of
  379. undefined ->
  380. custom_tags_clauses_ast1(
  381. CustomTags, [Tag | ExcludeTags],
  382. ClauseAcc, InfoAcc, TreeWalker);
  383. {{Ast, Info}, TW} ->
  384. Clause = ?Q("(_@Tag@, _Variables, RenderOptions) -> _@match, _@Ast",
  385. [{match, options_match_ast(TW)}]),
  386. custom_tags_clauses_ast1(
  387. CustomTags, [Tag | ExcludeTags], [Clause|ClauseAcc],
  388. merge_info(Info, InfoAcc), TW)
  389. end
  390. end
  391. end.
  392. custom_forms(Dir, Module, Functions, AstInfo) ->
  393. Dependencies = AstInfo#ast_info.dependencies,
  394. TranslatableStrings = AstInfo#ast_info.translatable_strings,
  395. erl_syntax:revert_forms(
  396. lists:flatten(
  397. ?Q(["-module('@Module@').",
  398. "-export([source_dir/0, dependencies/0, translatable_strings/0,",
  399. " render/1, render/2, render/3]).",
  400. "-export(['@__export_functions'/0]).",
  401. "source_dir() -> _@Dir@.",
  402. "dependencies() -> _@Dependencies@.",
  403. "translatable_strings() -> _@TranslatableStrings@.",
  404. "render(Tag) -> render(Tag, [], []).",
  405. "render(Tag, Vars) -> render(Tag, Vars, []).",
  406. "render(Tag, Vars, Opts) ->",
  407. " try '@Module@':Tag(Vars, Opts) of",
  408. " Val -> {ok, Val}",
  409. " catch",
  410. " Err -> {error, Err}",
  411. " end.",
  412. "'@_functions'() -> _."
  413. ],
  414. [{export_functions,
  415. erl_syntax:list(
  416. [erl_syntax:arity_qualifier(erl_syntax:atom(FName), erl_syntax:integer(Arity))
  417. || {FName, _} <- Functions, Arity <- [1, 2]])},
  418. {functions, [Ast || {_, Ast} <- Functions]}
  419. ]))
  420. ).
  421. stringify(BodyAst, #dtl_context{ binary_strings=BinaryStrings }) ->
  422. [?Q("erlydtl_runtime:stringify_final(_@BodyAst, '@BinaryStrings@')")].
  423. forms({BodyAst, BodyInfo}, {CustomTagsFunctionAst, CustomTagsInfo}, CheckSum,
  424. #treewalker{
  425. context=#dtl_context{
  426. module=Module,
  427. parse_trail=[File|_]
  428. }=Context
  429. }=TreeWalker) ->
  430. MergedInfo = merge_info(BodyInfo, CustomTagsInfo),
  431. Dependencies = MergedInfo#ast_info.dependencies,
  432. TranslatableStrings = MergedInfo#ast_info.translatable_strings,
  433. TranslatedBlocks = MergedInfo#ast_info.translated_blocks,
  434. Variables = lists:usort(MergedInfo#ast_info.var_names),
  435. DefaultVariables = lists:usort(MergedInfo#ast_info.def_names),
  436. Constants = lists:usort(MergedInfo#ast_info.const_names),
  437. FinalBodyAst = options_match_ast(TreeWalker) ++ stringify(BodyAst, Context),
  438. erl_syntax:revert_forms(
  439. ?Q(["-module('@Module@').",
  440. "-export([render/0, render/1, render/2, source/0, dependencies/0,",
  441. " translatable_strings/0, translated_blocks/0, variables/0,",
  442. " default_variables/0, constants/0]).",
  443. "source() -> {_@File@, _@CheckSum@}.",
  444. "dependencies() -> _@Dependencies@.",
  445. "variables() -> _@Variables@.",
  446. "default_variables() -> _@DefaultVariables@.",
  447. "constants() -> _@Constants@.",
  448. "translatable_strings() -> _@TranslatableStrings@.",
  449. "translated_blocks() -> _@TranslatedBlocks@.",
  450. "'@_CustomTagsFunctionAst'() -> _.",
  451. "render() -> render([], []).",
  452. "render(Variables) -> render(Variables, []).",
  453. "render(Variables, RenderOptions) ->",
  454. " try render_internal(Variables, RenderOptions) of",
  455. " Val -> {ok, Val}",
  456. " catch",
  457. " Err -> {error, Err}",
  458. " end.",
  459. "render_internal(_Variables, RenderOptions) -> _@FinalBodyAst."
  460. ])).
  461. options_match_ast(#treewalker{ context=Context }=TreeWalker) ->
  462. options_match_ast(Context, TreeWalker);
  463. options_match_ast(Context) ->
  464. options_match_ast(Context, undefined).
  465. options_match_ast(Context, TreeWalker) ->
  466. [
  467. ?Q(["_TranslationFun = erlydtl_runtime:init_translation(",
  468. " proplists:get_value(translation_fun, RenderOptions, none))"]),
  469. ?Q("_CurrentLocale = proplists:get_value(locale, RenderOptions, default)"),
  470. ?Q("_RecordInfo = _@info", [{info, merl:term(Context#dtl_context.record_info)}])
  471. | case call_extension(Context, setup_render_ast, [Context, TreeWalker]) of
  472. undefined -> [];
  473. Ast when is_list(Ast) -> Ast
  474. end].
  475. %% child templates should only consist of blocks at the top level
  476. body_ast([{'extends', {string_literal, _Pos, String}} | ThisParseTree], #treewalker{ context=Context }=TreeWalker) ->
  477. File = full_path(unescape_string_literal(String), Context#dtl_context.doc_root),
  478. case lists:member(File, Context#dtl_context.parse_trail) of
  479. true ->
  480. empty_ast(?ERR(circular_include, TreeWalker));
  481. _ ->
  482. case parse_file(File, Context) of
  483. {ok, ParentParseTree, CheckSum} ->
  484. BlockDict = lists:foldl(
  485. fun ({block, {identifier, _, Name}, Contents}, Dict) ->
  486. dict:store(Name, Contents, Dict);
  487. (_, Dict) -> Dict
  488. end,
  489. dict:new(),
  490. ThisParseTree),
  491. {Info, TreeWalker1} = with_dependency(
  492. {File, CheckSum},
  493. body_ast(
  494. ParentParseTree,
  495. TreeWalker#treewalker{
  496. context=Context#dtl_context{
  497. block_dict = dict:merge(
  498. fun(_Key, _ParentVal, ChildVal) -> ChildVal end,
  499. BlockDict, Context#dtl_context.block_dict),
  500. parse_trail = [File | Context#dtl_context.parse_trail]
  501. }
  502. })),
  503. {Info, reset_parse_trail(Context#dtl_context.parse_trail, TreeWalker1)};
  504. {error, Reason} ->
  505. empty_ast(?ERR(Reason, TreeWalker))
  506. end
  507. end;
  508. body_ast(DjangoParseTree, TreeWalker) ->
  509. body_ast(DjangoParseTree, empty_scope(), TreeWalker).
  510. body_ast(DjangoParseTree, BodyScope, TreeWalker) ->
  511. {ScopeId, TreeWalkerScope} = begin_scope(BodyScope, TreeWalker),
  512. BodyFun =
  513. fun ({'autoescape', {identifier, _, OnOrOff}, Contents}, TW) ->
  514. {Info, BodyTW} = body_ast(Contents, push_auto_escape(OnOrOff, TW)),
  515. {Info, pop_auto_escape(BodyTW)};
  516. ({'block', {identifier, Pos, Name}, Contents}, #treewalker{ context=Context }=TW) ->
  517. {Block, BlockScope} =
  518. case dict:find(Name, Context#dtl_context.block_dict) of
  519. {ok, ChildBlock} ->
  520. {{ContentsAst, _ContentsInfo}, _ContentsTW} = body_ast(Contents, TW),
  521. {ChildBlock,
  522. create_scope(
  523. [{block, ?Q("[{super, _@ContentsAst}]")}],
  524. Pos, TW)
  525. };
  526. _ ->
  527. {Contents, empty_scope()}
  528. end,
  529. body_ast(Block, BlockScope, TW);
  530. ({'blocktrans', Args, Contents, PluralContents}, TW) ->
  531. blocktrans_ast(Args, Contents, PluralContents, TW);
  532. ({'call', {identifier, _, Name}}, TW) ->
  533. call_ast(Name, TW);
  534. ({'call', {identifier, _, Name}, With}, TW) ->
  535. call_with_ast(Name, With, TW);
  536. ({'comment', _Contents}, TW) ->
  537. empty_ast(TW);
  538. ({'comment_tag', _, _}, TW) ->
  539. empty_ast(TW);
  540. ({'cycle', Names}, TW) ->
  541. cycle_ast(Names, TW);
  542. ({'cycle_compat', Names}, TW) ->
  543. cycle_compat_ast(Names, TW);
  544. ({'date', 'now', {string_literal, _Pos, FormatString}}, TW) ->
  545. now_ast(FormatString, TW);
  546. ({'filter', FilterList, Contents}, TW) ->
  547. filter_tag_ast(FilterList, Contents, TW);
  548. ({'firstof', Vars}, TW) ->
  549. firstof_ast(Vars, TW);
  550. ({'for', {'in', IteratorList, Variable, Reversed}, Contents}, TW) ->
  551. {EmptyAstInfo, TW1} = empty_ast(TW),
  552. for_loop_ast(IteratorList, Variable, Reversed, Contents, EmptyAstInfo, TW1);
  553. ({'for', {'in', IteratorList, Variable, Reversed}, Contents, EmptyPartContents}, TW) ->
  554. {EmptyAstInfo, TW1} = body_ast(EmptyPartContents, TW),
  555. for_loop_ast(IteratorList, Variable, Reversed, Contents, EmptyAstInfo, TW1);
  556. ({'if', Expression, Contents, Elif}, TW) ->
  557. {IfAstInfo, TW1} = body_ast(Contents, TW),
  558. {ElifAstInfo, TW2} = body_ast(Elif, TW1),
  559. ifelse_ast(Expression, IfAstInfo, ElifAstInfo, TW2);
  560. ({'if', Expression, Contents}, TW) ->
  561. {IfAstInfo, TW1} = body_ast(Contents, TW),
  562. {ElseAstInfo, TW2} = empty_ast(TW1),
  563. ifelse_ast(Expression, IfAstInfo, ElseAstInfo, TW2);
  564. ({'ifchanged', '$undefined', Contents}, TW) ->
  565. {IfAstInfo, TW1} = body_ast(Contents, TW),
  566. {ElseAstInfo, TW2} = empty_ast(TW1),
  567. ifchanged_contents_ast(Contents, IfAstInfo, ElseAstInfo, TW2);
  568. ({'ifchanged', Values, Contents}, TW) ->
  569. {IfAstInfo, TW1} = body_ast(Contents, TW),
  570. {ElseAstInfo, TW2} = empty_ast(TW1),
  571. ifchanged_values_ast(Values, IfAstInfo, ElseAstInfo, TW2);
  572. ({'ifchangedelse', '$undefined', IfContents, ElseContents}, TW) ->
  573. {IfAstInfo, TW1} = body_ast(IfContents, TW),
  574. {ElseAstInfo, TW2} = body_ast(ElseContents, TW1),
  575. ifchanged_contents_ast(IfContents, IfAstInfo, ElseAstInfo, TW2);
  576. ({'ifchangedelse', Values, IfContents, ElseContents}, TW) ->
  577. {IfAstInfo, TW1} = body_ast(IfContents, TW),
  578. {ElseAstInfo, TW2} = body_ast(ElseContents, TW1),
  579. ifchanged_values_ast(Values, IfAstInfo, ElseAstInfo, TW2);
  580. ({'ifelse', Expression, IfContents, ElseContents}, TW) ->
  581. {IfAstInfo, TW1} = body_ast(IfContents, TW),
  582. {ElseAstInfo, TW2} = body_ast(ElseContents, TW1),
  583. ifelse_ast(Expression, IfAstInfo, ElseAstInfo, TW2);
  584. ({'ifequal', [Arg1, Arg2], Contents}, TW) ->
  585. {IfAstInfo, TW1} = body_ast(Contents, TW),
  586. {ElseAstInfo, TW2} = empty_ast(TW1),
  587. ifelse_ast({'expr', "eq", Arg1, Arg2}, IfAstInfo, ElseAstInfo, TW2);
  588. ({'ifequalelse', [Arg1, Arg2], IfContents, ElseContents}, TW) ->
  589. {IfAstInfo, TW1} = body_ast(IfContents, TW),
  590. {ElseAstInfo, TW2} = body_ast(ElseContents,TW1),
  591. ifelse_ast({'expr', "eq", Arg1, Arg2}, IfAstInfo, ElseAstInfo, TW2);
  592. ({'ifnotequal', [Arg1, Arg2], Contents}, TW) ->
  593. {IfAstInfo, TW1} = body_ast(Contents, TW),
  594. {ElseAstInfo, TW2} = empty_ast(TW1),
  595. ifelse_ast({'expr', "ne", Arg1, Arg2}, IfAstInfo, ElseAstInfo, TW2);
  596. ({'ifnotequalelse', [Arg1, Arg2], IfContents, ElseContents}, TW) ->
  597. {IfAstInfo, TW1} = body_ast(IfContents, TW),
  598. {ElseAstInfo, TW2} = body_ast(ElseContents, TW1),
  599. ifelse_ast({'expr', "ne", Arg1, Arg2}, IfAstInfo, ElseAstInfo, TW2);
  600. ({'include', {string_literal, _, File}, Args}, #treewalker{ context=Context }=TW) ->
  601. include_ast(unescape_string_literal(File), Args, Context#dtl_context.local_scopes, TW);
  602. ({'include_only', {string_literal, _, File}, Args}, TW) ->
  603. {Info, IncTW} = include_ast(unescape_string_literal(File), Args, [], TW),
  604. {Info, restore_scope(TW, IncTW)};
  605. ({'load_libs', Libs}, TW) ->
  606. load_libs_ast(Libs, TW);
  607. ({'load_from_lib', What, Lib}, TW) ->
  608. load_from_lib_ast(What, Lib, TW);
  609. ({'regroup', {ListVariable, Grouper, {identifier, _, NewVariable}}}, TW) ->
  610. regroup_ast(ListVariable, Grouper, NewVariable, TW);
  611. ('end_regroup', TW) ->
  612. {{end_scope, #ast_info{}}, TW};
  613. ({'spaceless', Contents}, TW) ->
  614. spaceless_ast(Contents, TW);
  615. ({'ssi', Arg}, TW) ->
  616. ssi_ast(Arg, TW);
  617. ({'ssi_parsed', {string_literal, _, FileName}}, #treewalker{ context=Context }=TW) ->
  618. include_ast(unescape_string_literal(FileName), [], Context#dtl_context.local_scopes, TW);
  619. ({'string', _Pos, String}, TW) ->
  620. string_ast(String, TW);
  621. ({'tag', Name, Args}, TW) ->
  622. tag_ast(Name, Args, TW);
  623. ({'templatetag', {_, _, TagName}}, TW) ->
  624. templatetag_ast(TagName, TW);
  625. ({'trans', Value}, TW) ->
  626. translated_ast(Value, TW);
  627. ({'trans', Value, Context}, TW) ->
  628. translated_ast(Value, Context, TW);
  629. ({'widthratio', Numerator, Denominator, Scale}, TW) ->
  630. widthratio_ast(Numerator, Denominator, Scale, TW);
  631. ({'with', Args, Contents}, TW) ->
  632. with_ast(Args, Contents, TW);
  633. ({'scope_as', {identifier, _, Name}, Contents}, TW) ->
  634. scope_as(Name, Contents, TW);
  635. ({'extension', Tag}, TW) ->
  636. extension_ast(Tag, TW);
  637. ({'extends', _}, TW) ->
  638. empty_ast(?ERR(unexpected_extends_tag, TW));
  639. (ValueToken, TW) ->
  640. format(value_ast(ValueToken, true, true, TW))
  641. end,
  642. {AstInfoList, TreeWalker1} = lists:mapfoldl(BodyFun, TreeWalkerScope, DjangoParseTree),
  643. {AstList, Info} =
  644. lists:mapfoldl(
  645. fun ({Ast, Info}, InfoAcc) ->
  646. {Ast, merge_info(Info, InfoAcc)}
  647. end, #ast_info{}, AstInfoList),
  648. {Ast, TreeWalker2} = end_scope(
  649. fun ([ScopeVars|ScopeBody]) -> [?Q("begin _@ScopeVars, [_@ScopeBody] end")] end,
  650. ScopeId, AstList, TreeWalker1),
  651. {{erl_syntax:list(Ast), Info}, TreeWalker2}.
  652. value_ast(ValueToken, AsString, EmptyIfUndefined, TreeWalker) ->
  653. case ValueToken of
  654. {'expr', Operator, Value} ->
  655. {{ValueAst,InfoValue}, TreeWalker1} = value_ast(Value, false, EmptyIfUndefined, TreeWalker),
  656. Op = list_to_atom(Operator),
  657. Ast = ?Q("erlydtl_runtime:_@Op@(_@ValueAst)"),
  658. {{Ast, InfoValue}, TreeWalker1};
  659. {'expr', Operator, Value1, Value2} ->
  660. {{Value1Ast,InfoValue1}, TreeWalker1} = value_ast(Value1, false, EmptyIfUndefined, TreeWalker),
  661. {{Value2Ast,InfoValue2}, TreeWalker2} = value_ast(Value2, false, EmptyIfUndefined, TreeWalker1),
  662. Op = list_to_atom(Operator),
  663. Ast = ?Q("erlydtl_runtime:_@Op@(_@Value1Ast, _@Value2Ast)"),
  664. {{Ast, merge_info(InfoValue1,InfoValue2)}, TreeWalker2};
  665. {'string_literal', _Pos, String} ->
  666. string_ast(unescape_string_literal(String), TreeWalker);
  667. {'number_literal', _Pos, Number} ->
  668. case AsString of
  669. true -> string_ast(Number, TreeWalker);
  670. false -> {{erl_syntax:integer(Number), #ast_info{}}, TreeWalker}
  671. end;
  672. {'apply_filter', Variable, Filter} ->
  673. filter_ast(Variable, Filter, TreeWalker);
  674. {'attribute', _} = Variable ->
  675. resolve_variable_ast(Variable, EmptyIfUndefined, TreeWalker);
  676. {'variable', _} = Variable ->
  677. resolve_variable_ast(Variable, EmptyIfUndefined, TreeWalker);
  678. {extension, Tag} ->
  679. extension_ast(Tag, TreeWalker)
  680. end.
  681. extension_ast(Tag, TreeWalker) ->
  682. case call_extension(TreeWalker, compile_ast, [Tag, TreeWalker]) of
  683. undefined ->
  684. empty_ast(?WARN({unknown_extension, Tag}, TreeWalker));
  685. Result ->
  686. Result
  687. end.
  688. with_dependencies([], Args) ->
  689. Args;
  690. with_dependencies([Dependency | Rest], Args) ->
  691. with_dependencies(Rest, with_dependency(Dependency, Args)).
  692. with_dependency(FilePath, {{Ast, Info}, TreeWalker}) ->
  693. {{Ast, Info#ast_info{dependencies = [FilePath | Info#ast_info.dependencies]}}, TreeWalker}.
  694. empty_ast(TreeWalker) ->
  695. {{erl_syntax:list([]), #ast_info{}}, TreeWalker}.
  696. %%% Note: Context here refers to the translation context, not the #dtl_context{} record
  697. blocktrans_ast(Args, Contents, PluralContents, TreeWalker) ->
  698. %% get args, count and context
  699. ArgList = [{Name, Value}
  700. || {{identifier, _, Name}, Value}
  701. <- proplists:get_value(args, Args, [])],
  702. Count = proplists:get_value(count, Args),
  703. Context = case proplists:get_value(context, Args) of
  704. undefined -> undefined;
  705. {string_literal, _, S} ->
  706. unescape_string_literal(S)
  707. end,
  708. %% add new scope using 'with' values
  709. {NewScope, {ArgInfo, TreeWalker1}} =
  710. lists:mapfoldl(
  711. fun ({LocalVarName, Value}, {AstInfoAcc, TreeWalkerAcc}) ->
  712. {{Ast, Info}, TW} = value_ast(Value, false, false, TreeWalkerAcc),
  713. {{LocalVarName, Ast}, {merge_info(AstInfoAcc, Info), TW}}
  714. end,
  715. {#ast_info{}, TreeWalker},
  716. case Count of
  717. {{identifier, _, Name}, Value} ->
  718. [{Name, Value}|ArgList];
  719. _ ->
  720. ArgList
  721. end),
  722. TreeWalker2 = push_scope(NewScope, TreeWalker1),
  723. %% key for translation lookup
  724. SourceText = erlydtl_unparser:unparse(Contents),
  725. {{DefaultAst, AstInfo}, TreeWalker3} = body_ast(Contents, TreeWalker2),
  726. MergedInfo = merge_info(AstInfo, ArgInfo),
  727. #dtl_context{
  728. trans_fun = TFun,
  729. trans_locales = TLocales } = TreeWalker3#treewalker.context,
  730. if TFun =:= none; PluralContents =/= undefined ->
  731. %% translate in runtime
  732. {FinalAst, FinalTW} = blocktrans_runtime_ast(
  733. {DefaultAst, MergedInfo}, SourceText, Contents, Context,
  734. plural_contents(PluralContents, Count, TreeWalker3)),
  735. {FinalAst, restore_scope(TreeWalker1, FinalTW)};
  736. is_function(TFun, 2) ->
  737. %% translate in compile-time
  738. {FinalAstInfo, FinalTreeWalker, Clauses} =
  739. lists:foldr(
  740. fun (Locale, {AstInfoAcc, TreeWalkerAcc, ClauseAcc}) ->
  741. case TFun(SourceText, phrase_locale(Locale, Context)) of
  742. default ->
  743. {AstInfoAcc, TreeWalkerAcc, ClauseAcc};
  744. Body ->
  745. {ok, DjangoParseTree} = do_parse_template(Body, TreeWalkerAcc#treewalker.context),
  746. {{BodyAst, BodyInfo}, BodyTreeWalker} = body_ast(DjangoParseTree, TreeWalkerAcc),
  747. {merge_info(BodyInfo, AstInfoAcc), BodyTreeWalker,
  748. [?Q("_@Locale@ -> _@BodyAst")|ClauseAcc]}
  749. end
  750. end,
  751. {MergedInfo, TreeWalker3, []}, TLocales),
  752. FinalAst = ?Q("case _CurrentLocale of _@_Clauses -> _; _ -> _@DefaultAst end"),
  753. {{FinalAst, FinalAstInfo#ast_info{ translated_blocks = [SourceText] }},
  754. restore_scope(TreeWalker1, FinalTreeWalker)};
  755. true ->
  756. empty_ast(?ERR({translation_fun, TFun}, TreeWalker3))
  757. end.
  758. blocktrans_runtime_ast({DefaultAst, Info}, SourceText, Contents, Context, {Plural, TreeWalker}) ->
  759. %% Contents is flat - only strings and '{{var}}' allowed.
  760. %% build sorted list (orddict) of pre-resolved variables to pass to runtime translation function
  761. USortedVariables = lists:usort(fun({variable, {identifier, _, A}},
  762. {variable, {identifier, _, B}}) ->
  763. A =< B
  764. end, [Var || {variable, _}=Var
  765. <- Contents ++ maybe_plural_contents(Plural)]),
  766. VarBuilder = fun({variable, {identifier, _, Name}}=Var, TW) ->
  767. {{VarAst, _VarInfo}, VarTW} = resolve_variable_ast(Var, false, TW),
  768. {?Q("{_@name, _@VarAst}", [{name, merl:term(atom_to_list(Name))}]), VarTW}
  769. end,
  770. {VarAsts, TreeWalker1} = lists:mapfoldl(VarBuilder, TreeWalker, USortedVariables),
  771. VarListAst = erl_syntax:list(VarAsts),
  772. BlockTransAst = ?Q(["begin",
  773. " case erlydtl_runtime:translate_block(",
  774. " _@phrase, _@locale,",
  775. " _@VarListAst, _TranslationFun) of",
  776. " default -> _@DefaultAst;",
  777. " Text -> Text",
  778. " end",
  779. "end"],
  780. [{phrase, phrase_ast(SourceText, Plural)},
  781. {locale, phrase_locale_ast(Context)}]),
  782. {{BlockTransAst, merge_count_info(Info, Plural)}, TreeWalker1}.
  783. maybe_plural_contents(undefined) -> [];
  784. maybe_plural_contents({Contents, _}) -> Contents.
  785. merge_count_info(Info, undefined) -> Info;
  786. merge_count_info(Info, {_Contents, {_CountAst, CountInfo}}) ->
  787. merge_info(Info, CountInfo).
  788. plural_contents(undefined, _, TreeWalker) -> {undefined, TreeWalker};
  789. plural_contents(Contents, {_CountVarName, Value}, TreeWalker) ->
  790. {CountAst, TW} = value_ast(Value, false, false, TreeWalker),
  791. {{Contents, CountAst}, TW}.
  792. phrase_ast(Text, undefined) -> merl:term(Text);
  793. phrase_ast(Text, {Contents, {CountAst, _CountInfo}}) ->
  794. erl_syntax:tuple(
  795. [merl:term(Text),
  796. erl_syntax:tuple(
  797. [merl:term(erlydtl_unparser:unparse(Contents)),
  798. CountAst])
  799. ]).
  800. phrase_locale_ast(undefined) -> merl:var('_CurrentLocale');
  801. phrase_locale_ast(Context) -> erl_syntax:tuple([merl:var('_CurrentLocale'), merl:term(Context)]).
  802. phrase_locale(Locale, undefined) -> Locale;
  803. phrase_locale(Locale, Context) -> {Locale, Context}.
  804. translated_ast(Text, TreeWalker) ->
  805. translated_ast(Text, undefined, TreeWalker).
  806. translated_ast({noop, Value}, _, TreeWalker) ->
  807. value_ast(Value, true, true, TreeWalker);
  808. translated_ast(Text, {string_literal, _, Context}, TreeWalker) ->
  809. translated_ast(Text, unescape_string_literal(Context), TreeWalker);
  810. translated_ast({string_literal, _, String}, Context, TreeWalker) ->
  811. Text = unescape_string_literal(String),
  812. case call_extension(TreeWalker, translate_ast, [Text, Context, TreeWalker]) of
  813. undefined ->
  814. case TreeWalker#treewalker.context#dtl_context.trans_fun of
  815. none -> runtime_trans_ast(Text, Context, TreeWalker);
  816. Fun when is_function(Fun, 2) ->
  817. compiletime_trans_ast(Fun, Text, Context, TreeWalker);
  818. Fun when is_function(Fun, 1) ->
  819. compiletime_trans_ast(fun (T, _) -> Fun(T) end,
  820. Text, Context, TreeWalker);
  821. Fun ->
  822. empty_ast(?ERR({translation_fun, Fun}, TreeWalker))
  823. end;
  824. TranslatedAst ->
  825. TranslatedAst
  826. end;
  827. translated_ast(Value, Context, TreeWalker) ->
  828. runtime_trans_ast(value_ast(Value, true, false, TreeWalker), Context).
  829. runtime_trans_ast(Text, Context, TreeWalker) ->
  830. Info = #ast_info{ translatable_strings = [Text] },
  831. runtime_trans_ast({{merl:term(Text), Info}, TreeWalker}, Context).
  832. runtime_trans_ast({{ValueAst, AstInfo}, TreeWalker}, undefined) ->
  833. {{?Q("erlydtl_runtime:translate(_@ValueAst, _CurrentLocale, _TranslationFun)"),
  834. AstInfo}, TreeWalker};
  835. runtime_trans_ast({{ValueAst, AstInfo}, TreeWalker}, Context) ->
  836. {{?Q("erlydtl_runtime:translate(_@ValueAst, {_CurrentLocale, _@Context@}, _TranslationFun)"),
  837. AstInfo}, TreeWalker}.
  838. compiletime_trans_ast(TFun, Text, LContext,
  839. #treewalker{
  840. context=#dtl_context{
  841. trans_locales=TLocales
  842. }=Context
  843. }=TreeWalker) ->
  844. ClAst = lists:foldl(
  845. fun(Locale, ClausesAcc) ->
  846. [?Q("_@Locale@ -> _@translated",
  847. [{translated, case TFun(Text, phrase_locale(Locale, LContext)) of
  848. default -> string_ast(Text, Context);
  849. Translated -> string_ast(Translated, Context)
  850. end}])
  851. |ClausesAcc]
  852. end,
  853. [], TLocales),
  854. {{?Q(["case _CurrentLocale of",
  855. " _@_ClAst -> _;",
  856. " _ -> _@string",
  857. "end"],
  858. [{string, string_ast(Text, Context)}]),
  859. #ast_info{ translatable_strings = [Text] }},
  860. TreeWalker}.
  861. %%% end of context being translation context
  862. %% Completely unnecessary in ErlyDTL (use {{ "{%" }} etc), but implemented for compatibility.
  863. templatetag_ast("openblock", TreeWalker) ->
  864. string_ast("{%", TreeWalker);
  865. templatetag_ast("closeblock", TreeWalker) ->
  866. string_ast("%}", TreeWalker);
  867. templatetag_ast("openvariable", TreeWalker) ->
  868. string_ast("{{", TreeWalker);
  869. templatetag_ast("closevariable", TreeWalker) ->
  870. string_ast("}}", TreeWalker);
  871. templatetag_ast("openbrace", TreeWalker) ->
  872. string_ast("{", TreeWalker);
  873. templatetag_ast("closebrace", TreeWalker) ->
  874. string_ast("}", TreeWalker);
  875. templatetag_ast("opencomment", TreeWalker) ->
  876. string_ast("{#", TreeWalker);
  877. templatetag_ast("closecomment", TreeWalker) ->
  878. string_ast("#}", TreeWalker).
  879. widthratio_ast(Numerator, Denominator, Scale, TreeWalker) ->
  880. {{NumAst, NumInfo}, TreeWalker1} = value_ast(Numerator, false, true, TreeWalker),
  881. {{DenAst, DenInfo}, TreeWalker2} = value_ast(Denominator, false, true, TreeWalker1),
  882. {{ScaleAst, ScaleInfo}, TreeWalker3} = value_ast(Scale, false, true, TreeWalker2),
  883. {{format_number_ast(?Q("erlydtl_runtime:widthratio(_@NumAst, _@DenAst, _@ScaleAst)")),
  884. merge_info(ScaleInfo, merge_info(NumInfo, DenInfo))},
  885. TreeWalker3}.
  886. string_ast(Arg, #treewalker{ context=Context }=TreeWalker) ->
  887. {{string_ast(Arg, Context), #ast_info{}}, TreeWalker};
  888. string_ast(Arg, Context) ->
  889. merl:term(erlydtl_compiler_utils:to_string(Arg, Context)).
  890. include_ast(File, ArgList, Scopes, #treewalker{ context=Context }=TreeWalker) ->
  891. FilePath = full_path(File, Context#dtl_context.doc_root),
  892. case parse_file(FilePath, Context) of
  893. {ok, InclusionParseTree, CheckSum} ->
  894. {NewScope, {ArgInfo, TreeWalker1}}
  895. = lists:mapfoldl(
  896. fun ({{identifier, _, LocalVarName}, Value}, {AstInfoAcc, TreeWalkerAcc}) ->
  897. {{Ast, Info}, TW} = value_ast(Value, false, false, TreeWalkerAcc),
  898. {{LocalVarName, Ast}, {merge_info(AstInfoAcc, Info), TW}}
  899. end, {#ast_info{}, TreeWalker}, ArgList),
  900. C = TreeWalker1#treewalker.context,
  901. {{BodyAst, BodyInfo}, TreeWalker2} = with_dependency(
  902. {FilePath, CheckSum},
  903. body_ast(
  904. InclusionParseTree,
  905. TreeWalker1#treewalker{
  906. context=C#dtl_context{
  907. parse_trail = [FilePath | C#dtl_context.parse_trail],
  908. local_scopes = [NewScope|Scopes]
  909. }
  910. })),
  911. {{BodyAst, merge_info(BodyInfo, ArgInfo)},
  912. reset_parse_trail(C#dtl_context.parse_trail, TreeWalker2)};
  913. {error, Reason} ->
  914. empty_ast(?ERR(Reason, TreeWalker))
  915. end.
  916. %% include at run-time
  917. ssi_ast(FileName, #treewalker{
  918. context=#dtl_context{
  919. reader = {Mod, Fun},
  920. doc_root = Dir
  921. }
  922. }=TreeWalker) ->
  923. {{FileAst, Info}, TreeWalker1} = value_ast(FileName, true, true, TreeWalker),
  924. {{?Q("erlydtl_runtime:read_file(_@Mod@, _@Fun@, _@Dir@, _@FileAst)"), Info}, TreeWalker1}.
  925. filter_tag_ast(FilterList, Contents, TreeWalker) ->
  926. {{InnerAst, Info}, TreeWalker1} = body_ast(Contents, push_auto_escape(did, TreeWalker)),
  927. {{FilteredAst, FilteredInfo}, TreeWalker2} =
  928. lists:foldl(
  929. fun ({{identifier, _, Name}, []}, {{AstAcc, InfoAcc}, TreeWalkerAcc})
  930. when Name =:= 'escape'; Name =:= 'safe'; Name =:= 'safeseq' ->
  931. {{AstAcc, InfoAcc}, TreeWalkerAcc#treewalker{ safe = true }};
  932. (Filter, {{AstAcc, InfoAcc}, TreeWalkerAcc}) ->
  933. {{Ast, AstInfo}, TW} = filter_ast1(Filter, AstAcc, TreeWalkerAcc),
  934. {{Ast, merge_info(InfoAcc, AstInfo)}, TW}
  935. end,
  936. {{?Q("erlang:iolist_to_binary(_@InnerAst)"), Info},
  937. pop_auto_escape(TreeWalker1)},
  938. FilterList),
  939. EscapedAst = case search_for_escape_filter(
  940. lists:reverse(FilterList),
  941. TreeWalker2#treewalker.context) of
  942. on -> ?Q("erlydtl_filters:force_escape(_@FilteredAst)");
  943. _ -> FilteredAst
  944. end,
  945. {{EscapedAst, FilteredInfo}, TreeWalker2}.
  946. search_for_escape_filter(FilterList, #dtl_context{auto_escape = [on|_]}) ->
  947. search_for_safe_filter(FilterList);
  948. search_for_escape_filter(_, #dtl_context{auto_escape = [did|_]}) -> off;
  949. search_for_escape_filter([{{identifier, _, 'escape'}, []}|Rest], _Context) ->
  950. search_for_safe_filter(Rest);
  951. search_for_escape_filter([_|Rest], Context) ->
  952. search_for_escape_filter(Rest, Context);
  953. search_for_escape_filter([], _Context) -> off.
  954. search_for_safe_filter([{{identifier, _, Name}, []}|_])
  955. when Name =:= 'safe'; Name =:= 'safeseq' -> off;
  956. search_for_safe_filter([_|Rest]) -> search_for_safe_filter(Rest);
  957. search_for_safe_filter([]) -> on.
  958. filter_ast(Variable, Filter, TreeWalker) ->
  959. %% the escape filter is special; it is always applied last, so we have to go digging for it
  960. %% AutoEscape = 'did' means we (will have) decided whether to escape the current variable,
  961. %% so don't do any more escaping
  962. {{UnescapedAst, Info}, TreeWalker1} =
  963. filter_ast_noescape(
  964. Variable, Filter,
  965. push_auto_escape(did, TreeWalker)),
  966. {EscapedAst, TreeWalker2} =
  967. case search_for_escape_filter(Variable, Filter, TreeWalker#treewalker.context) of
  968. on -> {?Q("erlydtl_filters:force_escape(_@UnescapedAst)"),
  969. TreeWalker1#treewalker{ safe = true }};
  970. _ -> {UnescapedAst, TreeWalker1}
  971. end,
  972. {{EscapedAst, Info}, pop_auto_escape(TreeWalker2)}.
  973. filter_ast_noescape(Variable, {{identifier, _, Name}, []}, TreeWalker)
  974. when Name =:= 'escape'; Name =:= 'safe'; Name =:= 'safeseq' ->
  975. value_ast(Variable, true, false, TreeWalker#treewalker{safe = true});
  976. filter_ast_noescape(Variable, Filter, TreeWalker) ->
  977. {{ValueAst, Info1}, TreeWalker2} = value_ast(Variable, true, false, TreeWalker),
  978. {{VarValue, Info2}, TreeWalker3} = filter_ast1(Filter, ValueAst, TreeWalker2),
  979. {{VarValue, merge_info(Info1, Info2)}, TreeWalker3}.
  980. filter_ast1({{identifier, Pos, Name}, Args}, ValueAst, TreeWalker) ->
  981. {{ArgsAst, ArgsInfo}, TreeWalker1} =
  982. lists:foldr(
  983. fun (Arg, {{AccAst, AccInfo}, AccTreeWalker}) ->
  984. {{ArgAst, ArgInfo}, ArgTreeWalker} = value_ast(Arg, false, false, AccTreeWalker),
  985. {{[ArgAst|AccAst], merge_info(ArgInfo, AccInfo)}, ArgTreeWalker}
  986. end,
  987. {{[], #ast_info{}}, TreeWalker},
  988. Args),
  989. case filter_ast2(Name, [ValueAst|ArgsAst], TreeWalker1#treewalker.context) of
  990. {ok, FilterAst} ->
  991. {{FilterAst, ArgsInfo}, TreeWalker1};
  992. Error ->
  993. empty_ast(?WARN({Pos, Error}, TreeWalker1))
  994. end.
  995. filter_ast2(Name, Args, #dtl_context{ filters = Filters }) ->
  996. case proplists:get_value(Name, Filters) of
  997. {Mod, Fun}=Filter ->
  998. case erlang:function_exported(Mod, Fun, length(Args)) of
  999. true -> {ok, ?Q("'@Mod@':'@Fun@'(_@Args)")};
  1000. false ->
  1001. {filter_args, Name, Filter, length(Args)}
  1002. end;
  1003. undefined ->
  1004. {unknown_filter, Name, length(Args)}
  1005. end.
  1006. search_for_escape_filter(Variable, Filter, #dtl_context{auto_escape = [on|_]}) ->
  1007. search_for_safe_filter(Variable, Filter);
  1008. search_for_escape_filter(_, _, #dtl_context{auto_escape = [did|_]}) ->
  1009. off;
  1010. search_for_escape_filter(Variable, {{identifier, _, 'escape'}, []} = Filter, _Context) ->
  1011. search_for_safe_filter(Variable, Filter);
  1012. search_for_escape_filter({apply_filter, Variable, Filter}, _, Context) ->
  1013. search_for_escape_filter(Variable, Filter, Context);
  1014. search_for_escape_filter(_Variable, _Filter, _Context) ->
  1015. off.
  1016. search_for_safe_filter(_, {{identifier, _, 'safe'}, []}) ->
  1017. off;
  1018. search_for_safe_filter(_, {{identifier, _, 'safeseq'}, []}) ->
  1019. off;
  1020. search_for_safe_filter({apply_filter, Variable, Filter}, _) ->
  1021. search_for_safe_filter(Variable, Filter);
  1022. search_for_safe_filter(_Variable, _Filter) ->
  1023. on.
  1024. finder_function(true) -> {erlydtl_runtime, fetch_value};
  1025. finder_function(false) -> {erlydtl_runtime, find_value}.
  1026. finder_function(EmptyIfUndefined, TreeWalker) ->
  1027. case call_extension(TreeWalker, finder_function, [EmptyIfUndefined]) of
  1028. undefined -> finder_function(EmptyIfUndefined);
  1029. Result -> Result
  1030. end.
  1031. resolve_variable_ast({extension, Tag}, _, TreeWalker) ->
  1032. extension_ast(Tag, TreeWalker);
  1033. resolve_variable_ast(VarTuple, EmptyIfUndefined, TreeWalker)
  1034. when is_boolean(EmptyIfUndefined) ->
  1035. resolve_variable_ast(VarTuple, finder_function(EmptyIfUndefined, TreeWalker), TreeWalker);
  1036. resolve_variable_ast(VarTuple, FinderFunction, TreeWalker) ->
  1037. resolve_variable_ast1(VarTuple, FinderFunction, TreeWalker).
  1038. resolve_variable_ast1({attribute, {{_, Pos, Attr}, Variable}}, {Runtime, Finder}=FinderFunction, TreeWalker) ->
  1039. {{VarAst, VarInfo}, TreeWalker1} = resolve_variable_ast(Variable, FinderFunction, TreeWalker),
  1040. #treewalker{
  1041. context=#dtl_context{
  1042. lists_0_based = Lists0Based,
  1043. tuples_0_based = Tuples0Based
  1044. }
  1045. } = TreeWalker,
  1046. FileName = get_current_file(TreeWalker1),
  1047. {{?Q(["'@Runtime@':'@Finder@'(",
  1048. " _@Attr@, _@VarAst,",
  1049. " [{lists_0_based, _@Lists0Based@},",
  1050. " {tuples_0_based, _@Tuples0Based@},",
  1051. " {render_options, RenderOptions},",
  1052. " {record_info, _RecordInfo},",
  1053. " {filename, _@FileName@},",
  1054. " {pos, _@Pos@}",
  1055. " ])"]),
  1056. VarInfo},
  1057. TreeWalker1};
  1058. resolve_variable_ast1({variable, {identifier, Pos, VarName}}, {Runtime, Finder}, TreeWalker) ->
  1059. Ast = case resolve_variable(VarName, TreeWalker) of
  1060. {_, undefined} ->
  1061. FileName = get_current_file(TreeWalker),
  1062. {?Q(["'@Runtime@':'@Finder@'(",
  1063. " _@VarName@, _Variables,",
  1064. " [{filename, _@FileName@},",
  1065. " {pos, _@Pos@},",
  1066. " {record_info, _RecordInfo},",
  1067. " {render_options, RenderOptions}])"
  1068. ]),
  1069. #ast_info{ var_names=[VarName] }};
  1070. {default_vars, Val} ->
  1071. FileName = get_current_file(TreeWalker),
  1072. {?Q(["'@Runtime@':fetch_value(",
  1073. " _@VarName@, _Variables,",
  1074. " [{filename, _@FileName@},",
  1075. " {pos, _@Pos@},",
  1076. " {record_info, _RecordInfo},",
  1077. " {render_options, RenderOptions}],",
  1078. " _@val)"
  1079. ],
  1080. [{val, merl:term(erlydtl_filters:format_number(Val))}]),
  1081. #ast_info{ var_names=[VarName], def_names=[VarName] }};
  1082. {constant, Val} ->
  1083. {merl:term(erlydtl_filters:format_number(Val)),
  1084. #ast_info{ const_names=[VarName] }};
  1085. {scope, Val} ->
  1086. {Val, #ast_info{}}
  1087. end,
  1088. {Ast, TreeWalker}.
  1089. resolve_reserved_variable(ReservedName, TreeWalker) ->
  1090. resolve_reserved_variable(ReservedName, merl:term(undefined), TreeWalker).
  1091. resolve_reserved_variable(ReservedName, Default, TreeWalker) ->
  1092. case resolve_variable(ReservedName, Default, TreeWalker) of
  1093. {Src, Value} when Src =:= scope; Value =:= Default ->
  1094. {Value, TreeWalker};
  1095. _ ->
  1096. {Default, ?ERR({reserved_variable, ReservedName}, TreeWalker)}
  1097. end.
  1098. format({{Ast, Info}, TreeWalker}) ->
  1099. auto_escape({{format_number_ast(Ast), Info}, TreeWalker}).
  1100. format_number_ast(Ast) ->
  1101. ?Q("erlydtl_filters:format_number(_@Ast)").
  1102. auto_escape({AstInfo, #treewalker{ safe = true }=TW}) ->
  1103. {AstInfo, TW#treewalker{ safe = false }};
  1104. auto_escape({{Value, Info}, #treewalker{ context=#dtl_context{auto_escape=[on|_]} }=TW}) ->
  1105. {{?Q("erlydtl_filters:force_escape(_@Value)"), Info}, TW};
  1106. auto_escape(Value) -> Value.
  1107. firstof_ast(Vars, TreeWalker) ->
  1108. body_ast(
  1109. [lists:foldr(
  1110. fun ({L, _, _}=Var, [])
  1111. when L=:=string_literal;L=:=number_literal ->
  1112. Var;
  1113. ({L, _, _}, _)
  1114. when L=:=string_literal;L=:=number_literal ->
  1115. erlang:error(errbadliteral);
  1116. (Var, []) ->
  1117. {'ifelse', Var, [Var], []};
  1118. (Var, Acc) ->
  1119. {'ifelse', Var, [Var], [Acc]}
  1120. end,
  1121. [], Vars)
  1122. ],
  1123. TreeWalker).
  1124. ifelse_ast(Expression, {IfContentsAst, IfContentsInfo}, {ElseContentsAst, ElseContentsInfo}, TreeWalker) ->
  1125. Info = merge_info(IfContentsInfo, ElseContentsInfo),
  1126. {{Ast, ExpressionInfo}, TreeWalker1} = value_ast(Expression, false, false, TreeWalker),
  1127. {{?Q(["case erlydtl_runtime:is_true(_@Ast) of",
  1128. " true -> _@IfContentsAst;",
  1129. " _ -> _@ElseContentsAst",
  1130. "end"]),
  1131. merge_info(ExpressionInfo, Info)},
  1132. TreeWalker1}.
  1133. with_ast(ArgList, Contents, TreeWalker) ->
  1134. {ArgAstList, {ArgInfo, TreeWalker1}} =
  1135. lists:mapfoldl(
  1136. fun ({{identifier, _, _LocalVarName}, Value}, {AstInfoAcc, TreeWalkerAcc}) ->
  1137. {{Ast, Info}, TW} = value_ast(Value, false, false, TreeWalkerAcc),
  1138. {Ast, {merge_info(AstInfoAcc, Info), TW}}
  1139. end,
  1140. {#ast_info{}, TreeWalker},
  1141. ArgList),
  1142. NewScope = lists:map(
  1143. fun ({{identifier, _, LocalVarName}, _Value}) ->
  1144. {LocalVarName, varname_ast(LocalVarName)}
  1145. end,
  1146. ArgList),
  1147. {{InnerAst, InnerInfo}, TreeWalker2} =
  1148. body_ast(
  1149. Contents,
  1150. push_scope(NewScope, TreeWalker1)),
  1151. {{?Q("fun (_@args) -> _@InnerAst end (_@ArgAstList)",
  1152. [{args, element(2, lists:unzip(NewScope))}]),
  1153. merge_info(ArgInfo, InnerInfo)},
  1154. restore_scope(TreeWalker1, TreeWalker2)}.
  1155. scope_as(VarName, Contents, TreeWalker) ->
  1156. {{ContentsAst, ContentsInfo}, TreeWalker1} = body_ast(Contents, TreeWalker),
  1157. VarAst = varname_ast(VarName),
  1158. {Id, TreeWalker2} = begin_scope(
  1159. {[{VarName, VarAst}],
  1160. [?Q("_@VarAst = _@ContentsAst")]},
  1161. TreeWalker1),
  1162. {{Id, ContentsInfo}, TreeWalker2}.
  1163. regroup_ast(ListVariable, GrouperVariable, LocalVarName, TreeWalker) ->
  1164. {{ListAst, ListInfo}, TreeWalker1} = value_ast(ListVariable, false, true, TreeWalker),
  1165. LocalVarAst = varname_ast(LocalVarName),
  1166. {Id, TreeWalker2} = begin_scope(
  1167. {[{LocalVarName, LocalVarAst}],
  1168. [?Q("_@LocalVarAst = erlydtl_runtime:regroup(_@ListAst, _@regroup)",
  1169. [{regroup, regroup_filter(GrouperVariable, [])}])
  1170. ]},
  1171. TreeWalker1),
  1172. {{Id, ListInfo}, TreeWalker2}.
  1173. regroup_filter({attribute,{{identifier,_,Ident},Next}},Acc) ->
  1174. regroup_filter(Next,[erl_syntax:atom(Ident)|Acc]);
  1175. regroup_filter({variable,{identifier,_,Var}},Acc) ->
  1176. erl_syntax:list([erl_syntax:atom(Var)|Acc]).
  1177. to_list_ast(Value, IsReversed) ->
  1178. ?Q("erlydtl_runtime:to_list(_@Value, _@IsReversed)").
  1179. to_list_ast(Value, IsReversed, TreeWalker) ->
  1180. case call_extension(TreeWalker, to_list_ast, [Value, IsReversed, TreeWalker]) of
  1181. undefined -> to_list_ast(Value, IsReversed);
  1182. Result -> Result
  1183. end.
  1184. for_loop_ast(IteratorList, LoopValue, IsReversed, Contents,
  1185. {EmptyContentsAst, EmptyContentsInfo},
  1186. #treewalker{ context=Context }=TreeWalker) ->
  1187. %% create unique namespace for this instance
  1188. Level = length(Context#dtl_context.local_scopes),
  1189. {Row, Col} = element(2, hd(IteratorList)),
  1190. ForId = lists:concat(["/", Level, "_", Row, ":", Col]),
  1191. Counters = merl:var(lists:concat(["Counters", ForId])),
  1192. Vars = merl:var(lists:concat(["Vars", ForId])),
  1193. %% setup
  1194. VarScope = lists:map(
  1195. fun({identifier, {R, C}, Iterator}) ->
  1196. {Iterator, varname_ast(lists:concat([
  1197. Iterator,"/", Level, "_", R, ":", C]))}
  1198. end, IteratorList),
  1199. {Iterators, IteratorVars} = lists:unzip(VarScope),
  1200. IteratorCount = length(IteratorVars),
  1201. {{LoopBodyAst, Info}, TreeWalker1} =
  1202. body_ast(
  1203. Contents,
  1204. push_scope([{'forloop', Counters} | VarScope],
  1205. TreeWalker)),
  1206. {{LoopValueAst, LoopValueInfo}, TreeWalker2} =
  1207. value_ast(LoopValue, false, true, restore_scope(TreeWalker, TreeWalker1)),
  1208. LoopValueAst0 = to_list_ast(LoopValueAst, merl:term(IsReversed), TreeWalker2),
  1209. {ParentLoop, TreeWalker3} = resolve_reserved_variable('forloop', TreeWalker2),
  1210. %% call for loop
  1211. {{?Q(["case erlydtl_runtime:forloop(",
  1212. " fun (_@Vars, _@Counters) ->",
  1213. " {_@IteratorVars} = if is_tuple(_@Vars), size(_@Vars) == _@IteratorCount@ -> _@Vars;",
  1214. " _@___ifclauses -> _",
  1215. " end,",
  1216. " {_@LoopBodyAst, erlydtl_runtime:increment_counter_stats(_@Counters)}",
  1217. " end,",
  1218. " _@LoopValueAst0, _@ParentLoop)",
  1219. "of",
  1220. " empty -> _@EmptyContentsAst;",
  1221. " {L, _} -> L",
  1222. "end"],
  1223. [{ifclauses, if IteratorCount > 1 ->
  1224. ?Q(["() when is_list(_@Vars), length(_@Vars) == _@IteratorCount@ ->",
  1225. " list_to_tuple(_@Vars);",
  1226. "() when true -> throw({for_loop, _@Iterators@, _@Vars})"]);
  1227. true ->
  1228. ?Q("() when true -> {_@Vars}")
  1229. end}]),
  1230. merge_info(merge_info(Info, EmptyContentsInfo), LoopValueInfo)},
  1231. TreeWalker3}.
  1232. ifchanged_values_ast(Values, {IfContentsAst, IfContentsInfo}, {ElseContentsAst, ElseContentsInfo}, TreeWalker) ->
  1233. Info = merge_info(IfContentsInfo, ElseContentsInfo),
  1234. ValueAstFun = fun (Expr, {LTreeWalker, LInfo, Acc}) ->
  1235. {{EAst, EInfo}, ETw} = value_ast(Expr, false, true, LTreeWalker),
  1236. {ETw, merge_info(LInfo, EInfo),
  1237. [?Q("{_@hash, _@EAst}",
  1238. [{hash, merl:term(erlang:phash2(Expr))}])
  1239. |Acc]}
  1240. end,
  1241. {TreeWalker1, MergedInfo, Changed} = lists:foldl(ValueAstFun, {TreeWalker, Info, []}, Values),
  1242. {{?Q(["case erlydtl_runtime:ifchanged([_@Changed]) of",
  1243. " true -> _@IfContentsAst;",
  1244. " _ -> _@ElseContentsAst",
  1245. "end"]),
  1246. MergedInfo},
  1247. TreeWalker1}.
  1248. ifchanged_contents_ast(Contents, {IfContentsAst, IfContentsInfo}, {ElseContentsAst, ElseContentsInfo}, TreeWalker) ->
  1249. {{?Q(["case erlydtl_runtime:ifchanged([{_@hash, _@IfContentsAst}]) of",
  1250. " true -> _@IfContentsAst;",
  1251. " _ -> _@ElseContentsAst",
  1252. "end"],
  1253. [{hash, merl:term(erlang:phash2(Contents))}]),
  1254. merge_info(IfContentsInfo, ElseContentsInfo)},
  1255. TreeWalker}.
  1256. cycle_ast(Names, #treewalker{ context=Context }=TreeWalker) ->
  1257. {NamesTuple, VarNames}
  1258. = lists:mapfoldl(
  1259. fun ({string_literal, _, Str}, VarNamesAcc) ->
  1260. S = string_ast(unescape_string_literal(Str), Context),
  1261. {S, VarNamesAcc};
  1262. ({variable, _}=Var, VarNamesAcc) ->
  1263. {{V, #ast_info{ var_names=[VarName] }}, _} = resolve_variable_ast(Var, true, TreeWalker),
  1264. {V, [VarName|VarNamesAcc]};
  1265. ({number_literal, _, Num}, VarNamesAcc) ->
  1266. {format_number_ast(erl_syntax:integer(Num)), VarNamesAcc};
  1267. (_, VarNamesAcc) ->
  1268. {[], VarNamesAcc}
  1269. end, [], Names),
  1270. {ForLoop, TreeWalker1} = resolve_reserved_variable('forloop', TreeWalker),
  1271. {{?Q("erlydtl_runtime:cycle({_@NamesTuple}, _@ForLoop)"),
  1272. #ast_info{ var_names = VarNames }},
  1273. TreeWalker1}.
  1274. %% Older Django templates treat cycle with comma-delimited elements as strings
  1275. cycle_compat_ast(Names, #treewalker{ context=Context }=TreeWalker) ->
  1276. NamesTuple = lists:map(
  1277. fun ({identifier, _, X}) ->
  1278. string_ast(X, Context)
  1279. end, Names),
  1280. {ForLoop, TreeWalker1} = resolve_reserved_variable('forloop', TreeWalker),
  1281. {{?Q("erlydtl_runtime:cycle({_@NamesTuple}, _@ForLoop)"),
  1282. #ast_info{}},
  1283. TreeWalker1}.
  1284. now_ast(FormatString, TreeWalker) ->
  1285. %% Note: we can't use unescape_string_literal here
  1286. %% because we want to allow escaping in the format string.
  1287. %% We only want to remove the surrounding escapes,
  1288. %% i.e. \"foo\" becomes "foo"
  1289. UnescapeOuter = string:strip(FormatString, both, 34),
  1290. {{StringAst, Info}, TreeWalker1} = string_ast(UnescapeOuter, TreeWalker),
  1291. {{?Q("erlydtl_dateformat:format(_@StringAst)"), Info}, TreeWalker1}.
  1292. spaceless_ast(Contents, TreeWalker) ->
  1293. {{Ast, Info}, TreeWalker1} = body_ast(Contents, TreeWalker),
  1294. {{?Q("erlydtl_runtime:spaceless(_@Ast)"), Info}, TreeWalker1}.
  1295. load_libs_ast(Libs, TreeWalker) ->
  1296. TreeWalker1 = lists:foldl(
  1297. fun ({identifier, Pos, Lib}, TW) ->
  1298. load_library(Pos, Lib, TW)
  1299. end,
  1300. TreeWalker, Libs),
  1301. empty_ast(TreeWalker1).
  1302. load_from_lib_ast(What, {identifier, Pos, Lib}, TreeWalker) ->
  1303. Names = lists:foldl(
  1304. fun ({identifier, _, Name}, Acc) -> [Name|Acc] end,
  1305. [], What),
  1306. empty_ast(load_library(Pos, Lib, Names, TreeWalker)).
  1307. %%-------------------------------------------------------------------
  1308. %% Custom tags
  1309. %%-------------------------------------------------------------------
  1310. interpret_value({trans, StringLiteral}, TreeWalker) ->
  1311. translated_ast(StringLiteral, TreeWalker);
  1312. interpret_value(Value, TreeWalker) ->
  1313. value_ast(Value, false, false, TreeWalker).
  1314. interpret_args(Args, TreeWalker) ->
  1315. lists:foldr(
  1316. fun ({{identifier, _, Key}, Value}, {{ArgsAcc, AstInfoAcc}, TreeWalkerAcc}) ->
  1317. {{Ast0, AstInfo0}, TreeWalker0} = interpret_value(Value, TreeWalkerAcc),
  1318. {{[?Q("{_@Key@, _@Ast0}")|ArgsAcc], merge_info(AstInfo0, AstInfoAcc)}, TreeWalker0};
  1319. (Value, {{ArgsAcc, AstInfoAcc}, TreeWalkerAcc}) ->
  1320. {{Ast0, AstInfo0}, TreeWalker0} = value_ast(Value, false, false, TreeWalkerAcc),
  1321. {{[Ast0|ArgsAcc], merge_info(AstInfo0, AstInfoAcc)}, TreeWalker0}
  1322. end, {{[], #ast_info{}}, TreeWalker}, Args).
  1323. tag_ast(Name, Args, TreeWalker) ->
  1324. {{InterpretedArgs, AstInfo1}, TreeWalker1} = interpret_args(Args, TreeWalker),
  1325. {{RenderAst, RenderInfo}, TreeWalker2} = custom_tags_modules_ast(Name, InterpretedArgs, TreeWalker1),
  1326. {{RenderAst, merge_info(AstInfo1, RenderInfo)}, TreeWalker2}.
  1327. custom_tags_modules_ast({identifier, Pos, Name}, InterpretedArgs,
  1328. #treewalker{
  1329. context=#dtl_context{
  1330. tags = Tags,
  1331. module = Module,
  1332. is_compiling_dir=IsCompilingDir
  1333. }
  1334. }=TreeWalker) ->
  1335. case proplists:get_value(Name, Tags) of
  1336. {Mod, Fun}=Tag ->
  1337. case lists:max([-1] ++ [I || {N,I} <- Mod:module_info(exports), N =:= Fun]) of
  1338. 2 ->
  1339. {{?Q("'@Mod@':'@Fun@'([_@InterpretedArgs], RenderOptions)"),
  1340. #ast_info{}}, TreeWalker};
  1341. 1 ->
  1342. {{?Q("'@Mod@':'@Fun@'([_@InterpretedArgs])"),
  1343. #ast_info{}}, TreeWalker};
  1344. -1 ->
  1345. empty_ast(?WARN({Pos, {missing_tag, Name, Tag}}, TreeWalker));
  1346. I ->
  1347. empty_ast(?WARN({Pos, {bad_tag, Name, Tag, I}}, TreeWalker))
  1348. end;
  1349. undefined ->
  1350. if IsCompilingDir =/= false ->
  1351. {{?Q("'@Module@':'@Name@'([_@InterpretedArgs], RenderOptions)"),
  1352. #ast_info{ custom_tags = [Name] }}, TreeWalker};
  1353. true ->
  1354. {{?Q("render_tag(_@Name@, [_@InterpretedArgs], RenderOptions)"),
  1355. #ast_info{ custom_tags = [Name] }}, TreeWalker}
  1356. end
  1357. end.
  1358. call_ast(Module, TreeWalker) ->
  1359. call_ast(Module, merl:var("_Variables"), #ast_info{}, TreeWalker).
  1360. call_with_ast(Module, Variable, TreeWalker) ->
  1361. {{VarAst, VarInfo}, TreeWalker2} = resolve_variable_ast(Variable, false, TreeWalker),
  1362. call_ast(Module, VarAst, VarInfo, TreeWalker2).
  1363. call_ast(Module, Variable, AstInfo, TreeWalker) ->
  1364. Ast = ?Q(["case '@Module@':render(_@Variable, RenderOptions) of",
  1365. " {ok, Rendered} -> Rendered;",
  1366. " {error, Reason} -> io_lib:format(\"error: ~p\", [Reason])",
  1367. "end"]),
  1368. with_dependencies(Module:dependencies(), {{Ast, AstInfo}, TreeWalker}).
  1369. create_scope(Vars, VarScope) ->
  1370. {Scope, Values} =
  1371. lists:foldl(
  1372. fun ({Name, Value}, {VarAcc, ValueAcc}) ->
  1373. NameAst = varname_ast(lists:concat(["_", Name, VarScope])),
  1374. {[{Name, NameAst}|VarAcc],
  1375. [?Q("_@NameAst = _@Value")|ValueAcc]
  1376. }
  1377. end,
  1378. empty_scope(),
  1379. Vars),
  1380. {Scope, [Values]}.
  1381. create_scope(Vars, {Row, Col}, #treewalker{ context=Context }) ->
  1382. Level = length(Context#dtl_context.local_scopes),
  1383. create_scope(Vars, lists:concat(["/", Level, "_", Row, ":", Col])).
  1384. varname_ast([$_|VarName]) ->
  1385. merl:var(lists:concat(["_Var__", VarName]));
  1386. varname_ast(VarName) ->
  1387. merl:var(lists:concat(["Var_", VarName])).