erlydtl_beam_compiler.erl 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  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. {{?Q(["erlydtl_runtime:forloop(",
  1211. " fun (_@Vars, _@Counters) ->",
  1212. " {_@IteratorVars} = if is_tuple(_@Vars), size(_@Vars) == _@IteratorCount@ -> _@Vars;",
  1213. " _@___ifclauses -> _",
  1214. " end,",
  1215. " {_@LoopBodyAst, erlydtl_runtime:increment_counter_stats(_@Counters)}",
  1216. " end,",
  1217. " _@LoopValueAst0, _@ParentLoop, _@EmptyContentsAst)"],
  1218. [{ifclauses, if IteratorCount > 1 ->
  1219. ?Q(["() when is_list(_@Vars), length(_@Vars) == _@IteratorCount@ ->",
  1220. " list_to_tuple(_@Vars);",
  1221. "() when true -> throw({for_loop, _@Iterators@, _@Vars})"]);
  1222. true ->
  1223. ?Q("() when true -> {_@Vars}")
  1224. end}]),
  1225. merge_info(merge_info(Info, EmptyContentsInfo), LoopValueInfo)},
  1226. TreeWalker3}.
  1227. ifchanged_values_ast(Values, {IfContentsAst, IfContentsInfo}, {ElseContentsAst, ElseContentsInfo}, TreeWalker) ->
  1228. Info = merge_info(IfContentsInfo, ElseContentsInfo),
  1229. ValueAstFun = fun (Expr, {LTreeWalker, LInfo, Acc}) ->
  1230. {{EAst, EInfo}, ETw} = value_ast(Expr, false, true, LTreeWalker),
  1231. {ETw, merge_info(LInfo, EInfo),
  1232. [?Q("{_@hash, _@EAst}",
  1233. [{hash, merl:term(erlang:phash2(Expr))}])
  1234. |Acc]}
  1235. end,
  1236. {TreeWalker1, MergedInfo, Changed} = lists:foldl(ValueAstFun, {TreeWalker, Info, []}, Values),
  1237. {{?Q(["case erlydtl_runtime:ifchanged([_@Changed]) of",
  1238. " true -> _@IfContentsAst;",
  1239. " _ -> _@ElseContentsAst",
  1240. "end"]),
  1241. MergedInfo},
  1242. TreeWalker1}.
  1243. ifchanged_contents_ast(Contents, {IfContentsAst, IfContentsInfo}, {ElseContentsAst, ElseContentsInfo}, TreeWalker) ->
  1244. {{?Q(["case erlydtl_runtime:ifchanged([{_@hash, _@IfContentsAst}]) of",
  1245. " true -> _@IfContentsAst;",
  1246. " _ -> _@ElseContentsAst",
  1247. "end"],
  1248. [{hash, merl:term(erlang:phash2(Contents))}]),
  1249. merge_info(IfContentsInfo, ElseContentsInfo)},
  1250. TreeWalker}.
  1251. cycle_ast(Names, #treewalker{ context=Context }=TreeWalker) ->
  1252. {NamesTuple, VarNames}
  1253. = lists:mapfoldl(
  1254. fun ({string_literal, _, Str}, VarNamesAcc) ->
  1255. S = string_ast(unescape_string_literal(Str), Context),
  1256. {S, VarNamesAcc};
  1257. ({variable, _}=Var, VarNamesAcc) ->
  1258. {{V, #ast_info{ var_names=[VarName] }}, _} = resolve_variable_ast(Var, true, TreeWalker),
  1259. {V, [VarName|VarNamesAcc]};
  1260. ({number_literal, _, Num}, VarNamesAcc) ->
  1261. {format_number_ast(erl_syntax:integer(Num)), VarNamesAcc};
  1262. (_, VarNamesAcc) ->
  1263. {[], VarNamesAcc}
  1264. end, [], Names),
  1265. {ForLoop, TreeWalker1} = resolve_reserved_variable('forloop', TreeWalker),
  1266. {{?Q("erlydtl_runtime:cycle({_@NamesTuple}, _@ForLoop)"),
  1267. #ast_info{ var_names = VarNames }},
  1268. TreeWalker1}.
  1269. %% Older Django templates treat cycle with comma-delimited elements as strings
  1270. cycle_compat_ast(Names, #treewalker{ context=Context }=TreeWalker) ->
  1271. NamesTuple = lists:map(
  1272. fun ({identifier, _, X}) ->
  1273. string_ast(X, Context)
  1274. end, Names),
  1275. {ForLoop, TreeWalker1} = resolve_reserved_variable('forloop', TreeWalker),
  1276. {{?Q("erlydtl_runtime:cycle({_@NamesTuple}, _@ForLoop)"),
  1277. #ast_info{}},
  1278. TreeWalker1}.
  1279. now_ast(FormatString, TreeWalker) ->
  1280. %% Note: we can't use unescape_string_literal here
  1281. %% because we want to allow escaping in the format string.
  1282. %% We only want to remove the surrounding escapes,
  1283. %% i.e. \"foo\" becomes "foo"
  1284. UnescapeOuter = string:strip(FormatString, both, 34),
  1285. {{StringAst, Info}, TreeWalker1} = string_ast(UnescapeOuter, TreeWalker),
  1286. {{?Q("erlydtl_dateformat:format(_@StringAst)"), Info}, TreeWalker1}.
  1287. spaceless_ast(Contents, TreeWalker) ->
  1288. {{Ast, Info}, TreeWalker1} = body_ast(Contents, TreeWalker),
  1289. {{?Q("erlydtl_runtime:spaceless(_@Ast)"), Info}, TreeWalker1}.
  1290. load_libs_ast(Libs, TreeWalker) ->
  1291. TreeWalker1 = lists:foldl(
  1292. fun ({identifier, Pos, Lib}, TW) ->
  1293. load_library(Pos, Lib, TW)
  1294. end,
  1295. TreeWalker, Libs),
  1296. empty_ast(TreeWalker1).
  1297. load_from_lib_ast(What, {identifier, Pos, Lib}, TreeWalker) ->
  1298. Names = lists:foldl(
  1299. fun ({identifier, _, Name}, Acc) -> [Name|Acc] end,
  1300. [], What),
  1301. empty_ast(load_library(Pos, Lib, Names, TreeWalker)).
  1302. %%-------------------------------------------------------------------
  1303. %% Custom tags
  1304. %%-------------------------------------------------------------------
  1305. interpret_value({trans, StringLiteral}, TreeWalker) ->
  1306. translated_ast(StringLiteral, TreeWalker);
  1307. interpret_value(Value, TreeWalker) ->
  1308. value_ast(Value, false, false, TreeWalker).
  1309. interpret_args(Args, TreeWalker) ->
  1310. lists:foldr(
  1311. fun ({{identifier, _, Key}, Value}, {{ArgsAcc, AstInfoAcc}, TreeWalkerAcc}) ->
  1312. {{Ast0, AstInfo0}, TreeWalker0} = interpret_value(Value, TreeWalkerAcc),
  1313. {{[?Q("{_@Key@, _@Ast0}")|ArgsAcc], merge_info(AstInfo0, AstInfoAcc)}, TreeWalker0};
  1314. (Value, {{ArgsAcc, AstInfoAcc}, TreeWalkerAcc}) ->
  1315. {{Ast0, AstInfo0}, TreeWalker0} = value_ast(Value, false, false, TreeWalkerAcc),
  1316. {{[Ast0|ArgsAcc], merge_info(AstInfo0, AstInfoAcc)}, TreeWalker0}
  1317. end, {{[], #ast_info{}}, TreeWalker}, Args).
  1318. tag_ast(Name, Args, TreeWalker) ->
  1319. {{InterpretedArgs, AstInfo1}, TreeWalker1} = interpret_args(Args, TreeWalker),
  1320. {{RenderAst, RenderInfo}, TreeWalker2} = custom_tags_modules_ast(Name, InterpretedArgs, TreeWalker1),
  1321. {{RenderAst, merge_info(AstInfo1, RenderInfo)}, TreeWalker2}.
  1322. custom_tags_modules_ast({identifier, Pos, Name}, InterpretedArgs,
  1323. #treewalker{
  1324. context=#dtl_context{
  1325. tags = Tags,
  1326. module = Module,
  1327. is_compiling_dir=IsCompilingDir
  1328. }
  1329. }=TreeWalker) ->
  1330. case proplists:get_value(Name, Tags) of
  1331. {Mod, Fun}=Tag ->
  1332. case lists:max([-1] ++ [I || {N,I} <- Mod:module_info(exports), N =:= Fun]) of
  1333. 2 ->
  1334. {{?Q("'@Mod@':'@Fun@'([_@InterpretedArgs], RenderOptions)"),
  1335. #ast_info{}}, TreeWalker};
  1336. 1 ->
  1337. {{?Q("'@Mod@':'@Fun@'([_@InterpretedArgs])"),
  1338. #ast_info{}}, TreeWalker};
  1339. -1 ->
  1340. empty_ast(?WARN({Pos, {missing_tag, Name, Tag}}, TreeWalker));
  1341. I ->
  1342. empty_ast(?WARN({Pos, {bad_tag, Name, Tag, I}}, TreeWalker))
  1343. end;
  1344. undefined ->
  1345. if IsCompilingDir =/= false ->
  1346. {{?Q("'@Module@':'@Name@'([_@InterpretedArgs], RenderOptions)"),
  1347. #ast_info{ custom_tags = [Name] }}, TreeWalker};
  1348. true ->
  1349. {{?Q("render_tag(_@Name@, [_@InterpretedArgs], RenderOptions)"),
  1350. #ast_info{ custom_tags = [Name] }}, TreeWalker}
  1351. end
  1352. end.
  1353. call_ast(Module, TreeWalker) ->
  1354. call_ast(Module, merl:var("_Variables"), #ast_info{}, TreeWalker).
  1355. call_with_ast(Module, Variable, TreeWalker) ->
  1356. {{VarAst, VarInfo}, TreeWalker2} = resolve_variable_ast(Variable, false, TreeWalker),
  1357. call_ast(Module, VarAst, VarInfo, TreeWalker2).
  1358. call_ast(Module, Variable, AstInfo, TreeWalker) ->
  1359. Ast = ?Q(["case '@Module@':render(_@Variable, RenderOptions) of",
  1360. " {ok, Rendered} -> Rendered;",
  1361. " {error, Reason} -> io_lib:format(\"error: ~p\", [Reason])",
  1362. "end"]),
  1363. with_dependencies(Module:dependencies(), {{Ast, AstInfo}, TreeWalker}).
  1364. create_scope(Vars, VarScope) ->
  1365. {Scope, Values} =
  1366. lists:foldl(
  1367. fun ({Name, Value}, {VarAcc, ValueAcc}) ->
  1368. NameAst = varname_ast(lists:concat(["_", Name, VarScope])),
  1369. {[{Name, NameAst}|VarAcc],
  1370. [?Q("_@NameAst = _@Value")|ValueAcc]
  1371. }
  1372. end,
  1373. empty_scope(),
  1374. Vars),
  1375. {Scope, [Values]}.
  1376. create_scope(Vars, {Row, Col}, #treewalker{ context=Context }) ->
  1377. Level = length(Context#dtl_context.local_scopes),
  1378. create_scope(Vars, lists:concat(["/", Level, "_", Row, ":", Col])).
  1379. varname_ast([$_|VarName]) ->
  1380. merl:var(lists:concat(["_Var__", VarName]));
  1381. varname_ast(VarName) ->
  1382. merl:var(lists:concat(["Var_", VarName])).