codegen.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. # mako/codegen.py
  2. # Copyright (C) 2006-2012 the Mako authors and contributors <see AUTHORS file>
  3. #
  4. # This module is part of Mako and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. """provides functionality for rendering a parsetree constructing into module
  7. source code."""
  8. import time
  9. import re
  10. from mako.pygen import PythonPrinter
  11. from mako import util, ast, parsetree, filters, exceptions
  12. from mako import compat
  13. MAGIC_NUMBER = 8
  14. # names which are hardwired into the
  15. # template and are not accessed via the
  16. # context itself
  17. RESERVED_NAMES = set(['context', 'loop', 'UNDEFINED'])
  18. def compile(node,
  19. uri,
  20. filename=None,
  21. default_filters=None,
  22. buffer_filters=None,
  23. imports=None,
  24. future_imports=None,
  25. source_encoding=None,
  26. generate_magic_comment=True,
  27. disable_unicode=False,
  28. strict_undefined=False,
  29. enable_loop=True,
  30. reserved_names=frozenset()):
  31. """Generate module source code given a parsetree node,
  32. uri, and optional source filename"""
  33. # if on Py2K, push the "source_encoding" string to be
  34. # a bytestring itself, as we will be embedding it into
  35. # the generated source and we don't want to coerce the
  36. # result into a unicode object, in "disable_unicode" mode
  37. if not compat.py3k and isinstance(source_encoding, compat.text_type):
  38. source_encoding = source_encoding.encode(source_encoding)
  39. buf = util.FastEncodingBuffer()
  40. printer = PythonPrinter(buf)
  41. _GenerateRenderMethod(printer,
  42. _CompileContext(uri,
  43. filename,
  44. default_filters,
  45. buffer_filters,
  46. imports,
  47. future_imports,
  48. source_encoding,
  49. generate_magic_comment,
  50. disable_unicode,
  51. strict_undefined,
  52. enable_loop,
  53. reserved_names),
  54. node)
  55. return buf.getvalue()
  56. class _CompileContext(object):
  57. def __init__(self,
  58. uri,
  59. filename,
  60. default_filters,
  61. buffer_filters,
  62. imports,
  63. future_imports,
  64. source_encoding,
  65. generate_magic_comment,
  66. disable_unicode,
  67. strict_undefined,
  68. enable_loop,
  69. reserved_names):
  70. self.uri = uri
  71. self.filename = filename
  72. self.default_filters = default_filters
  73. self.buffer_filters = buffer_filters
  74. self.imports = imports
  75. self.future_imports = future_imports
  76. self.source_encoding = source_encoding
  77. self.generate_magic_comment = generate_magic_comment
  78. self.disable_unicode = disable_unicode
  79. self.strict_undefined = strict_undefined
  80. self.enable_loop = enable_loop
  81. self.reserved_names = reserved_names
  82. class _GenerateRenderMethod(object):
  83. """A template visitor object which generates the
  84. full module source for a template.
  85. """
  86. def __init__(self, printer, compiler, node):
  87. self.printer = printer
  88. self.last_source_line = -1
  89. self.compiler = compiler
  90. self.node = node
  91. self.identifier_stack = [None]
  92. self.in_def = isinstance(node, (parsetree.DefTag, parsetree.BlockTag))
  93. if self.in_def:
  94. name = "render_%s" % node.funcname
  95. args = node.get_argument_expressions()
  96. filtered = len(node.filter_args.args) > 0
  97. buffered = eval(node.attributes.get('buffered', 'False'))
  98. cached = eval(node.attributes.get('cached', 'False'))
  99. defs = None
  100. pagetag = None
  101. if node.is_block and not node.is_anonymous:
  102. args += ['**pageargs']
  103. else:
  104. defs = self.write_toplevel()
  105. pagetag = self.compiler.pagetag
  106. name = "render_body"
  107. if pagetag is not None:
  108. args = pagetag.body_decl.get_argument_expressions()
  109. if not pagetag.body_decl.kwargs:
  110. args += ['**pageargs']
  111. cached = eval(pagetag.attributes.get('cached', 'False'))
  112. self.compiler.enable_loop = self.compiler.enable_loop or eval(
  113. pagetag.attributes.get(
  114. 'enable_loop', 'False')
  115. )
  116. else:
  117. args = ['**pageargs']
  118. cached = False
  119. buffered = filtered = False
  120. if args is None:
  121. args = ['context']
  122. else:
  123. args = [a for a in ['context'] + args]
  124. self.write_render_callable(
  125. pagetag or node,
  126. name, args,
  127. buffered, filtered, cached)
  128. if defs is not None:
  129. for node in defs:
  130. _GenerateRenderMethod(printer, compiler, node)
  131. @property
  132. def identifiers(self):
  133. return self.identifier_stack[-1]
  134. def write_toplevel(self):
  135. """Traverse a template structure for module-level directives and
  136. generate the start of module-level code.
  137. """
  138. inherit = []
  139. namespaces = {}
  140. module_code = []
  141. self.compiler.pagetag = None
  142. class FindTopLevel(object):
  143. def visitInheritTag(s, node):
  144. inherit.append(node)
  145. def visitNamespaceTag(s, node):
  146. namespaces[node.name] = node
  147. def visitPageTag(s, node):
  148. self.compiler.pagetag = node
  149. def visitCode(s, node):
  150. if node.ismodule:
  151. module_code.append(node)
  152. f = FindTopLevel()
  153. for n in self.node.nodes:
  154. n.accept_visitor(f)
  155. self.compiler.namespaces = namespaces
  156. module_ident = set()
  157. for n in module_code:
  158. module_ident = module_ident.union(n.declared_identifiers())
  159. module_identifiers = _Identifiers(self.compiler)
  160. module_identifiers.declared = module_ident
  161. # module-level names, python code
  162. if self.compiler.generate_magic_comment and \
  163. self.compiler.source_encoding:
  164. self.printer.writeline("# -*- encoding:%s -*-" %
  165. self.compiler.source_encoding)
  166. if self.compiler.future_imports:
  167. self.printer.writeline("from __future__ import %s" %
  168. (", ".join(self.compiler.future_imports),))
  169. self.printer.writeline("from mako import runtime, filters, cache")
  170. self.printer.writeline("UNDEFINED = runtime.UNDEFINED")
  171. self.printer.writeline("__M_dict_builtin = dict")
  172. self.printer.writeline("__M_locals_builtin = locals")
  173. self.printer.writeline("_magic_number = %r" % MAGIC_NUMBER)
  174. self.printer.writeline("_modified_time = %r" % time.time())
  175. self.printer.writeline("_enable_loop = %r" % self.compiler.enable_loop)
  176. self.printer.writeline(
  177. "_template_filename = %r" % self.compiler.filename)
  178. self.printer.writeline("_template_uri = %r" % self.compiler.uri)
  179. self.printer.writeline(
  180. "_source_encoding = %r" % self.compiler.source_encoding)
  181. if self.compiler.imports:
  182. buf = ''
  183. for imp in self.compiler.imports:
  184. buf += imp + "\n"
  185. self.printer.writeline(imp)
  186. impcode = ast.PythonCode(
  187. buf,
  188. source='', lineno=0,
  189. pos=0,
  190. filename='template defined imports')
  191. else:
  192. impcode = None
  193. main_identifiers = module_identifiers.branch(self.node)
  194. module_identifiers.topleveldefs = \
  195. module_identifiers.topleveldefs.\
  196. union(main_identifiers.topleveldefs)
  197. module_identifiers.declared.add("UNDEFINED")
  198. if impcode:
  199. module_identifiers.declared.update(impcode.declared_identifiers)
  200. self.compiler.identifiers = module_identifiers
  201. self.printer.writeline("_exports = %r" %
  202. [n.name for n in
  203. main_identifiers.topleveldefs.values()]
  204. )
  205. self.printer.write("\n\n")
  206. if len(module_code):
  207. self.write_module_code(module_code)
  208. if len(inherit):
  209. self.write_namespaces(namespaces)
  210. self.write_inherit(inherit[-1])
  211. elif len(namespaces):
  212. self.write_namespaces(namespaces)
  213. return list(main_identifiers.topleveldefs.values())
  214. def write_render_callable(self, node, name, args, buffered, filtered,
  215. cached):
  216. """write a top-level render callable.
  217. this could be the main render() method or that of a top-level def."""
  218. if self.in_def:
  219. decorator = node.decorator
  220. if decorator:
  221. self.printer.writeline(
  222. "@runtime._decorate_toplevel(%s)" % decorator)
  223. self.printer.writelines(
  224. "def %s(%s):" % (name, ','.join(args)),
  225. # push new frame, assign current frame to __M_caller
  226. "__M_caller = context.caller_stack._push_frame()",
  227. "try:"
  228. )
  229. if buffered or filtered or cached:
  230. self.printer.writeline("context._push_buffer()")
  231. self.identifier_stack.append(
  232. self.compiler.identifiers.branch(self.node))
  233. if (not self.in_def or self.node.is_block) and '**pageargs' in args:
  234. self.identifier_stack[-1].argument_declared.add('pageargs')
  235. if not self.in_def and (
  236. len(self.identifiers.locally_assigned) > 0 or
  237. len(self.identifiers.argument_declared) > 0
  238. ):
  239. self.printer.writeline("__M_locals = __M_dict_builtin(%s)" %
  240. ','.join([
  241. "%s=%s" % (x, x) for x in
  242. self.identifiers.argument_declared
  243. ]))
  244. self.write_variable_declares(self.identifiers, toplevel=True)
  245. for n in self.node.nodes:
  246. n.accept_visitor(self)
  247. self.write_def_finish(self.node, buffered, filtered, cached)
  248. self.printer.writeline(None)
  249. self.printer.write("\n\n")
  250. if cached:
  251. self.write_cache_decorator(
  252. node, name,
  253. args, buffered,
  254. self.identifiers, toplevel=True)
  255. def write_module_code(self, module_code):
  256. """write module-level template code, i.e. that which
  257. is enclosed in <%! %> tags in the template."""
  258. for n in module_code:
  259. self.write_source_comment(n)
  260. self.printer.write_indented_block(n.text)
  261. def write_inherit(self, node):
  262. """write the module-level inheritance-determination callable."""
  263. self.printer.writelines(
  264. "def _mako_inherit(template, context):",
  265. "_mako_generate_namespaces(context)",
  266. "return runtime._inherit_from(context, %s, _template_uri)" %
  267. (node.parsed_attributes['file']),
  268. None
  269. )
  270. def write_namespaces(self, namespaces):
  271. """write the module-level namespace-generating callable."""
  272. self.printer.writelines(
  273. "def _mako_get_namespace(context, name):",
  274. "try:",
  275. "return context.namespaces[(__name__, name)]",
  276. "except KeyError:",
  277. "_mako_generate_namespaces(context)",
  278. "return context.namespaces[(__name__, name)]",
  279. None, None
  280. )
  281. self.printer.writeline("def _mako_generate_namespaces(context):")
  282. for node in namespaces.values():
  283. if 'import' in node.attributes:
  284. self.compiler.has_ns_imports = True
  285. self.write_source_comment(node)
  286. if len(node.nodes):
  287. self.printer.writeline("def make_namespace():")
  288. export = []
  289. identifiers = self.compiler.identifiers.branch(node)
  290. self.in_def = True
  291. class NSDefVisitor(object):
  292. def visitDefTag(s, node):
  293. s.visitDefOrBase(node)
  294. def visitBlockTag(s, node):
  295. s.visitDefOrBase(node)
  296. def visitDefOrBase(s, node):
  297. if node.is_anonymous:
  298. raise exceptions.CompileException(
  299. "Can't put anonymous blocks inside "
  300. "<%namespace>",
  301. **node.exception_kwargs
  302. )
  303. self.write_inline_def(node, identifiers, nested=False)
  304. export.append(node.funcname)
  305. vis = NSDefVisitor()
  306. for n in node.nodes:
  307. n.accept_visitor(vis)
  308. self.printer.writeline("return [%s]" % (','.join(export)))
  309. self.printer.writeline(None)
  310. self.in_def = False
  311. callable_name = "make_namespace()"
  312. else:
  313. callable_name = "None"
  314. if 'file' in node.parsed_attributes:
  315. self.printer.writeline(
  316. "ns = runtime.TemplateNamespace(%r,"
  317. " context._clean_inheritance_tokens(),"
  318. " templateuri=%s, callables=%s, "
  319. " calling_uri=_template_uri)" %
  320. (
  321. node.name,
  322. node.parsed_attributes.get('file', 'None'),
  323. callable_name,
  324. )
  325. )
  326. elif 'module' in node.parsed_attributes:
  327. self.printer.writeline(
  328. "ns = runtime.ModuleNamespace(%r,"
  329. " context._clean_inheritance_tokens(),"
  330. " callables=%s, calling_uri=_template_uri,"
  331. " module=%s)" %
  332. (
  333. node.name,
  334. callable_name,
  335. node.parsed_attributes.get('module', 'None')
  336. )
  337. )
  338. else:
  339. self.printer.writeline(
  340. "ns = runtime.Namespace(%r,"
  341. " context._clean_inheritance_tokens(),"
  342. " callables=%s, calling_uri=_template_uri)" %
  343. (
  344. node.name,
  345. callable_name,
  346. )
  347. )
  348. if eval(node.attributes.get('inheritable', "False")):
  349. self.printer.writeline("context['self'].%s = ns" % (node.name))
  350. self.printer.writeline(
  351. "context.namespaces[(__name__, %s)] = ns" % repr(node.name))
  352. self.printer.write("\n")
  353. if not len(namespaces):
  354. self.printer.writeline("pass")
  355. self.printer.writeline(None)
  356. def write_variable_declares(self, identifiers, toplevel=False, limit=None):
  357. """write variable declarations at the top of a function.
  358. the variable declarations are in the form of callable
  359. definitions for defs and/or name lookup within the
  360. function's context argument. the names declared are based
  361. on the names that are referenced in the function body,
  362. which don't otherwise have any explicit assignment
  363. operation. names that are assigned within the body are
  364. assumed to be locally-scoped variables and are not
  365. separately declared.
  366. for def callable definitions, if the def is a top-level
  367. callable then a 'stub' callable is generated which wraps
  368. the current Context into a closure. if the def is not
  369. top-level, it is fully rendered as a local closure.
  370. """
  371. # collection of all defs available to us in this scope
  372. comp_idents = dict([(c.funcname, c) for c in identifiers.defs])
  373. to_write = set()
  374. # write "context.get()" for all variables we are going to
  375. # need that arent in the namespace yet
  376. to_write = to_write.union(identifiers.undeclared)
  377. # write closure functions for closures that we define
  378. # right here
  379. to_write = to_write.union(
  380. [c.funcname for c in identifiers.closuredefs.values()])
  381. # remove identifiers that are declared in the argument
  382. # signature of the callable
  383. to_write = to_write.difference(identifiers.argument_declared)
  384. # remove identifiers that we are going to assign to.
  385. # in this way we mimic Python's behavior,
  386. # i.e. assignment to a variable within a block
  387. # means that variable is now a "locally declared" var,
  388. # which cannot be referenced beforehand.
  389. to_write = to_write.difference(identifiers.locally_declared)
  390. if self.compiler.enable_loop:
  391. has_loop = "loop" in to_write
  392. to_write.discard("loop")
  393. else:
  394. has_loop = False
  395. # if a limiting set was sent, constraint to those items in that list
  396. # (this is used for the caching decorator)
  397. if limit is not None:
  398. to_write = to_write.intersection(limit)
  399. if toplevel and getattr(self.compiler, 'has_ns_imports', False):
  400. self.printer.writeline("_import_ns = {}")
  401. self.compiler.has_imports = True
  402. for ident, ns in self.compiler.namespaces.items():
  403. if 'import' in ns.attributes:
  404. self.printer.writeline(
  405. "_mako_get_namespace(context, %r)."\
  406. "_populate(_import_ns, %r)" %
  407. (
  408. ident,
  409. re.split(r'\s*,\s*', ns.attributes['import'])
  410. ))
  411. if has_loop:
  412. self.printer.writeline(
  413. 'loop = __M_loop = runtime.LoopStack()'
  414. )
  415. for ident in to_write:
  416. if ident in comp_idents:
  417. comp = comp_idents[ident]
  418. if comp.is_block:
  419. if not comp.is_anonymous:
  420. self.write_def_decl(comp, identifiers)
  421. else:
  422. self.write_inline_def(comp, identifiers, nested=True)
  423. else:
  424. if comp.is_root():
  425. self.write_def_decl(comp, identifiers)
  426. else:
  427. self.write_inline_def(comp, identifiers, nested=True)
  428. elif ident in self.compiler.namespaces:
  429. self.printer.writeline(
  430. "%s = _mako_get_namespace(context, %r)" %
  431. (ident, ident)
  432. )
  433. else:
  434. if getattr(self.compiler, 'has_ns_imports', False):
  435. if self.compiler.strict_undefined:
  436. self.printer.writelines(
  437. "%s = _import_ns.get(%r, UNDEFINED)" %
  438. (ident, ident),
  439. "if %s is UNDEFINED:" % ident,
  440. "try:",
  441. "%s = context[%r]" % (ident, ident),
  442. "except KeyError:",
  443. "raise NameError(\"'%s' is not defined\")" %
  444. ident,
  445. None, None
  446. )
  447. else:
  448. self.printer.writeline(
  449. "%s = _import_ns.get(%r, context.get(%r, UNDEFINED))" %
  450. (ident, ident, ident))
  451. else:
  452. if self.compiler.strict_undefined:
  453. self.printer.writelines(
  454. "try:",
  455. "%s = context[%r]" % (ident, ident),
  456. "except KeyError:",
  457. "raise NameError(\"'%s' is not defined\")" %
  458. ident,
  459. None
  460. )
  461. else:
  462. self.printer.writeline(
  463. "%s = context.get(%r, UNDEFINED)" % (ident, ident)
  464. )
  465. self.printer.writeline("__M_writer = context.writer()")
  466. def write_source_comment(self, node):
  467. """write a source comment containing the line number of the
  468. corresponding template line."""
  469. if self.last_source_line != node.lineno:
  470. self.printer.writeline("# SOURCE LINE %d" % node.lineno)
  471. self.last_source_line = node.lineno
  472. def write_def_decl(self, node, identifiers):
  473. """write a locally-available callable referencing a top-level def"""
  474. funcname = node.funcname
  475. namedecls = node.get_argument_expressions()
  476. nameargs = node.get_argument_expressions(include_defaults=False)
  477. if not self.in_def and (
  478. len(self.identifiers.locally_assigned) > 0 or
  479. len(self.identifiers.argument_declared) > 0):
  480. nameargs.insert(0, 'context.locals_(__M_locals)')
  481. else:
  482. nameargs.insert(0, 'context')
  483. self.printer.writeline("def %s(%s):" % (funcname, ",".join(namedecls)))
  484. self.printer.writeline(
  485. "return render_%s(%s)" % (funcname, ",".join(nameargs)))
  486. self.printer.writeline(None)
  487. def write_inline_def(self, node, identifiers, nested):
  488. """write a locally-available def callable inside an enclosing def."""
  489. namedecls = node.get_argument_expressions()
  490. decorator = node.decorator
  491. if decorator:
  492. self.printer.writeline(
  493. "@runtime._decorate_inline(context, %s)" % decorator)
  494. self.printer.writeline(
  495. "def %s(%s):" % (node.funcname, ",".join(namedecls)))
  496. filtered = len(node.filter_args.args) > 0
  497. buffered = eval(node.attributes.get('buffered', 'False'))
  498. cached = eval(node.attributes.get('cached', 'False'))
  499. self.printer.writelines(
  500. # push new frame, assign current frame to __M_caller
  501. "__M_caller = context.caller_stack._push_frame()",
  502. "try:"
  503. )
  504. if buffered or filtered or cached:
  505. self.printer.writelines(
  506. "context._push_buffer()",
  507. )
  508. identifiers = identifiers.branch(node, nested=nested)
  509. self.write_variable_declares(identifiers)
  510. self.identifier_stack.append(identifiers)
  511. for n in node.nodes:
  512. n.accept_visitor(self)
  513. self.identifier_stack.pop()
  514. self.write_def_finish(node, buffered, filtered, cached)
  515. self.printer.writeline(None)
  516. if cached:
  517. self.write_cache_decorator(node, node.funcname,
  518. namedecls, False, identifiers,
  519. inline=True, toplevel=False)
  520. def write_def_finish(self, node, buffered, filtered, cached,
  521. callstack=True):
  522. """write the end section of a rendering function, either outermost or
  523. inline.
  524. this takes into account if the rendering function was filtered,
  525. buffered, etc. and closes the corresponding try: block if any, and
  526. writes code to retrieve captured content, apply filters, send proper
  527. return value."""
  528. if not buffered and not cached and not filtered:
  529. self.printer.writeline("return ''")
  530. if callstack:
  531. self.printer.writelines(
  532. "finally:",
  533. "context.caller_stack._pop_frame()",
  534. None
  535. )
  536. if buffered or filtered or cached:
  537. if buffered or cached:
  538. # in a caching scenario, don't try to get a writer
  539. # from the context after popping; assume the caching
  540. # implemenation might be using a context with no
  541. # extra buffers
  542. self.printer.writelines(
  543. "finally:",
  544. "__M_buf = context._pop_buffer()"
  545. )
  546. else:
  547. self.printer.writelines(
  548. "finally:",
  549. "__M_buf, __M_writer = context._pop_buffer_and_writer()"
  550. )
  551. if callstack:
  552. self.printer.writeline("context.caller_stack._pop_frame()")
  553. s = "__M_buf.getvalue()"
  554. if filtered:
  555. s = self.create_filter_callable(node.filter_args.args, s,
  556. False)
  557. self.printer.writeline(None)
  558. if buffered and not cached:
  559. s = self.create_filter_callable(self.compiler.buffer_filters,
  560. s, False)
  561. if buffered or cached:
  562. self.printer.writeline("return %s" % s)
  563. else:
  564. self.printer.writelines(
  565. "__M_writer(%s)" % s,
  566. "return ''"
  567. )
  568. def write_cache_decorator(self, node_or_pagetag, name,
  569. args, buffered, identifiers,
  570. inline=False, toplevel=False):
  571. """write a post-function decorator to replace a rendering
  572. callable with a cached version of itself."""
  573. self.printer.writeline("__M_%s = %s" % (name, name))
  574. cachekey = node_or_pagetag.parsed_attributes.get('cache_key',
  575. repr(name))
  576. cache_args = {}
  577. if self.compiler.pagetag is not None:
  578. cache_args.update(
  579. (
  580. pa[6:],
  581. self.compiler.pagetag.parsed_attributes[pa]
  582. )
  583. for pa in self.compiler.pagetag.parsed_attributes
  584. if pa.startswith('cache_') and pa != 'cache_key'
  585. )
  586. cache_args.update(
  587. (
  588. pa[6:],
  589. node_or_pagetag.parsed_attributes[pa]
  590. ) for pa in node_or_pagetag.parsed_attributes
  591. if pa.startswith('cache_') and pa != 'cache_key'
  592. )
  593. if 'timeout' in cache_args:
  594. cache_args['timeout'] = int(eval(cache_args['timeout']))
  595. self.printer.writeline("def %s(%s):" % (name, ','.join(args)))
  596. # form "arg1, arg2, arg3=arg3, arg4=arg4", etc.
  597. pass_args = [
  598. '=' in a and "%s=%s" % ((a.split('=')[0],)*2) or a
  599. for a in args
  600. ]
  601. self.write_variable_declares(
  602. identifiers,
  603. toplevel=toplevel,
  604. limit=node_or_pagetag.undeclared_identifiers()
  605. )
  606. if buffered:
  607. s = "context.get('local')."\
  608. "cache._ctx_get_or_create("\
  609. "%s, lambda:__M_%s(%s), context, %s__M_defname=%r)" % \
  610. (cachekey, name, ','.join(pass_args),
  611. ''.join(["%s=%s, " % (k, v)
  612. for k, v in cache_args.items()]),
  613. name
  614. )
  615. # apply buffer_filters
  616. s = self.create_filter_callable(self.compiler.buffer_filters, s,
  617. False)
  618. self.printer.writelines("return " + s, None)
  619. else:
  620. self.printer.writelines(
  621. "__M_writer(context.get('local')."
  622. "cache._ctx_get_or_create("\
  623. "%s, lambda:__M_%s(%s), context, %s__M_defname=%r))" %
  624. (cachekey, name, ','.join(pass_args),
  625. ''.join(["%s=%s, " % (k, v)
  626. for k, v in cache_args.items()]),
  627. name,
  628. ),
  629. "return ''",
  630. None
  631. )
  632. def create_filter_callable(self, args, target, is_expression):
  633. """write a filter-applying expression based on the filters
  634. present in the given filter names, adjusting for the global
  635. 'default' filter aliases as needed."""
  636. def locate_encode(name):
  637. if re.match(r'decode\..+', name):
  638. return "filters." + name
  639. elif self.compiler.disable_unicode:
  640. return filters.NON_UNICODE_ESCAPES.get(name, name)
  641. else:
  642. return filters.DEFAULT_ESCAPES.get(name, name)
  643. if 'n' not in args:
  644. if is_expression:
  645. if self.compiler.pagetag:
  646. args = self.compiler.pagetag.filter_args.args + args
  647. if self.compiler.default_filters:
  648. args = self.compiler.default_filters + args
  649. for e in args:
  650. # if filter given as a function, get just the identifier portion
  651. if e == 'n':
  652. continue
  653. m = re.match(r'(.+?)(\(.*\))', e)
  654. if m:
  655. (ident, fargs) = m.group(1,2)
  656. f = locate_encode(ident)
  657. e = f + fargs
  658. else:
  659. x = e
  660. e = locate_encode(e)
  661. assert e is not None
  662. target = "%s(%s)" % (e, target)
  663. return target
  664. def visitExpression(self, node):
  665. self.write_source_comment(node)
  666. if len(node.escapes) or \
  667. (
  668. self.compiler.pagetag is not None and
  669. len(self.compiler.pagetag.filter_args.args)
  670. ) or \
  671. len(self.compiler.default_filters):
  672. s = self.create_filter_callable(node.escapes_code.args,
  673. "%s" % node.text, True)
  674. self.printer.writeline("__M_writer(%s)" % s)
  675. else:
  676. self.printer.writeline("__M_writer(%s)" % node.text)
  677. def visitControlLine(self, node):
  678. if node.isend:
  679. self.printer.writeline(None)
  680. if node.has_loop_context:
  681. self.printer.writeline('finally:')
  682. self.printer.writeline("loop = __M_loop._exit()")
  683. self.printer.writeline(None)
  684. else:
  685. self.write_source_comment(node)
  686. if self.compiler.enable_loop and node.keyword == 'for':
  687. text = mangle_mako_loop(node, self.printer)
  688. else:
  689. text = node.text
  690. self.printer.writeline(text)
  691. children = node.get_children()
  692. # this covers the three situations where we want to insert a pass:
  693. # 1) a ternary control line with no children,
  694. # 2) a primary control line with nothing but its own ternary
  695. # and end control lines, and
  696. # 3) any control line with no content other than comments
  697. if not children or (
  698. compat.all(isinstance(c, (parsetree.Comment,
  699. parsetree.ControlLine))
  700. for c in children) and
  701. compat.all((node.is_ternary(c.keyword) or c.isend)
  702. for c in children
  703. if isinstance(c, parsetree.ControlLine))):
  704. self.printer.writeline("pass")
  705. def visitText(self, node):
  706. self.write_source_comment(node)
  707. self.printer.writeline("__M_writer(%s)" % repr(node.content))
  708. def visitTextTag(self, node):
  709. filtered = len(node.filter_args.args) > 0
  710. if filtered:
  711. self.printer.writelines(
  712. "__M_writer = context._push_writer()",
  713. "try:",
  714. )
  715. for n in node.nodes:
  716. n.accept_visitor(self)
  717. if filtered:
  718. self.printer.writelines(
  719. "finally:",
  720. "__M_buf, __M_writer = context._pop_buffer_and_writer()",
  721. "__M_writer(%s)" %
  722. self.create_filter_callable(
  723. node.filter_args.args,
  724. "__M_buf.getvalue()",
  725. False),
  726. None
  727. )
  728. def visitCode(self, node):
  729. if not node.ismodule:
  730. self.write_source_comment(node)
  731. self.printer.write_indented_block(node.text)
  732. if not self.in_def and len(self.identifiers.locally_assigned) > 0:
  733. # if we are the "template" def, fudge locally
  734. # declared/modified variables into the "__M_locals" dictionary,
  735. # which is used for def calls within the same template,
  736. # to simulate "enclosing scope"
  737. self.printer.writeline(
  738. '__M_locals_builtin_stored = __M_locals_builtin()')
  739. self.printer.writeline(
  740. '__M_locals.update(__M_dict_builtin([(__M_key,'
  741. ' __M_locals_builtin_stored[__M_key]) for __M_key in'
  742. ' [%s] if __M_key in __M_locals_builtin_stored]))' %
  743. ','.join([repr(x) for x in node.declared_identifiers()]))
  744. def visitIncludeTag(self, node):
  745. self.write_source_comment(node)
  746. args = node.attributes.get('args')
  747. if args:
  748. self.printer.writeline(
  749. "runtime._include_file(context, %s, _template_uri, %s)" %
  750. (node.parsed_attributes['file'], args))
  751. else:
  752. self.printer.writeline(
  753. "runtime._include_file(context, %s, _template_uri)" %
  754. (node.parsed_attributes['file']))
  755. def visitNamespaceTag(self, node):
  756. pass
  757. def visitDefTag(self, node):
  758. pass
  759. def visitBlockTag(self, node):
  760. if node.is_anonymous:
  761. self.printer.writeline("%s()" % node.funcname)
  762. else:
  763. nameargs = node.get_argument_expressions(include_defaults=False)
  764. nameargs += ['**pageargs']
  765. self.printer.writeline("if 'parent' not in context._data or "
  766. "not hasattr(context._data['parent'], '%s'):"
  767. % node.funcname)
  768. self.printer.writeline(
  769. "context['self'].%s(%s)" % (node.funcname, ",".join(nameargs)))
  770. self.printer.writeline("\n")
  771. def visitCallNamespaceTag(self, node):
  772. # TODO: we can put namespace-specific checks here, such
  773. # as ensure the given namespace will be imported,
  774. # pre-import the namespace, etc.
  775. self.visitCallTag(node)
  776. def visitCallTag(self, node):
  777. self.printer.writeline("def ccall(caller):")
  778. export = ['body']
  779. callable_identifiers = self.identifiers.branch(node, nested=True)
  780. body_identifiers = callable_identifiers.branch(node, nested=False)
  781. # we want the 'caller' passed to ccall to be used
  782. # for the body() function, but for other non-body()
  783. # <%def>s within <%call> we want the current caller
  784. # off the call stack (if any)
  785. body_identifiers.add_declared('caller')
  786. self.identifier_stack.append(body_identifiers)
  787. class DefVisitor(object):
  788. def visitDefTag(s, node):
  789. s.visitDefOrBase(node)
  790. def visitBlockTag(s, node):
  791. s.visitDefOrBase(node)
  792. def visitDefOrBase(s, node):
  793. self.write_inline_def(node, callable_identifiers, nested=False)
  794. if not node.is_anonymous:
  795. export.append(node.funcname)
  796. # remove defs that are within the <%call> from the
  797. # "closuredefs" defined in the body, so they dont render twice
  798. if node.funcname in body_identifiers.closuredefs:
  799. del body_identifiers.closuredefs[node.funcname]
  800. vis = DefVisitor()
  801. for n in node.nodes:
  802. n.accept_visitor(vis)
  803. self.identifier_stack.pop()
  804. bodyargs = node.body_decl.get_argument_expressions()
  805. self.printer.writeline("def body(%s):" % ','.join(bodyargs))
  806. # TODO: figure out best way to specify
  807. # buffering/nonbuffering (at call time would be better)
  808. buffered = False
  809. if buffered:
  810. self.printer.writelines(
  811. "context._push_buffer()",
  812. "try:"
  813. )
  814. self.write_variable_declares(body_identifiers)
  815. self.identifier_stack.append(body_identifiers)
  816. for n in node.nodes:
  817. n.accept_visitor(self)
  818. self.identifier_stack.pop()
  819. self.write_def_finish(node, buffered, False, False, callstack=False)
  820. self.printer.writelines(
  821. None,
  822. "return [%s]" % (','.join(export)),
  823. None
  824. )
  825. self.printer.writelines(
  826. # push on caller for nested call
  827. "context.caller_stack.nextcaller = "
  828. "runtime.Namespace('caller', context, "
  829. "callables=ccall(__M_caller))",
  830. "try:")
  831. self.write_source_comment(node)
  832. self.printer.writelines(
  833. "__M_writer(%s)" % self.create_filter_callable(
  834. [], node.expression, True),
  835. "finally:",
  836. "context.caller_stack.nextcaller = None",
  837. None
  838. )
  839. class _Identifiers(object):
  840. """tracks the status of identifier names as template code is rendered."""
  841. def __init__(self, compiler, node=None, parent=None, nested=False):
  842. if parent is not None:
  843. # if we are the branch created in write_namespaces(),
  844. # we don't share any context from the main body().
  845. if isinstance(node, parsetree.NamespaceTag):
  846. self.declared = set()
  847. self.topleveldefs = util.SetLikeDict()
  848. else:
  849. # things that have already been declared
  850. # in an enclosing namespace (i.e. names we can just use)
  851. self.declared = set(parent.declared).\
  852. union([c.name for c in parent.closuredefs.values()]).\
  853. union(parent.locally_declared).\
  854. union(parent.argument_declared)
  855. # if these identifiers correspond to a "nested"
  856. # scope, it means whatever the parent identifiers
  857. # had as undeclared will have been declared by that parent,
  858. # and therefore we have them in our scope.
  859. if nested:
  860. self.declared = self.declared.union(parent.undeclared)
  861. # top level defs that are available
  862. self.topleveldefs = util.SetLikeDict(**parent.topleveldefs)
  863. else:
  864. self.declared = set()
  865. self.topleveldefs = util.SetLikeDict()
  866. self.compiler = compiler
  867. # things within this level that are referenced before they
  868. # are declared (e.g. assigned to)
  869. self.undeclared = set()
  870. # things that are declared locally. some of these things
  871. # could be in the "undeclared" list as well if they are
  872. # referenced before declared
  873. self.locally_declared = set()
  874. # assignments made in explicit python blocks.
  875. # these will be propagated to
  876. # the context of local def calls.
  877. self.locally_assigned = set()
  878. # things that are declared in the argument
  879. # signature of the def callable
  880. self.argument_declared = set()
  881. # closure defs that are defined in this level
  882. self.closuredefs = util.SetLikeDict()
  883. self.node = node
  884. if node is not None:
  885. node.accept_visitor(self)
  886. illegal_names = self.compiler.reserved_names.intersection(
  887. self.locally_declared)
  888. if illegal_names:
  889. raise exceptions.NameConflictError(
  890. "Reserved words declared in template: %s" %
  891. ", ".join(illegal_names))
  892. def branch(self, node, **kwargs):
  893. """create a new Identifiers for a new Node, with
  894. this Identifiers as the parent."""
  895. return _Identifiers(self.compiler, node, self, **kwargs)
  896. @property
  897. def defs(self):
  898. return set(self.topleveldefs.union(self.closuredefs).values())
  899. def __repr__(self):
  900. return "Identifiers(declared=%r, locally_declared=%r, "\
  901. "undeclared=%r, topleveldefs=%r, closuredefs=%r, "\
  902. "argumentdeclared=%r)" %\
  903. (
  904. list(self.declared),
  905. list(self.locally_declared),
  906. list(self.undeclared),
  907. [c.name for c in self.topleveldefs.values()],
  908. [c.name for c in self.closuredefs.values()],
  909. self.argument_declared)
  910. def check_declared(self, node):
  911. """update the state of this Identifiers with the undeclared
  912. and declared identifiers of the given node."""
  913. for ident in node.undeclared_identifiers():
  914. if ident != 'context' and\
  915. ident not in self.declared.union(self.locally_declared):
  916. self.undeclared.add(ident)
  917. for ident in node.declared_identifiers():
  918. self.locally_declared.add(ident)
  919. def add_declared(self, ident):
  920. self.declared.add(ident)
  921. if ident in self.undeclared:
  922. self.undeclared.remove(ident)
  923. def visitExpression(self, node):
  924. self.check_declared(node)
  925. def visitControlLine(self, node):
  926. self.check_declared(node)
  927. def visitCode(self, node):
  928. if not node.ismodule:
  929. self.check_declared(node)
  930. self.locally_assigned = self.locally_assigned.union(
  931. node.declared_identifiers())
  932. def visitNamespaceTag(self, node):
  933. # only traverse into the sub-elements of a
  934. # <%namespace> tag if we are the branch created in
  935. # write_namespaces()
  936. if self.node is node:
  937. for n in node.nodes:
  938. n.accept_visitor(self)
  939. def _check_name_exists(self, collection, node):
  940. existing = collection.get(node.funcname)
  941. collection[node.funcname] = node
  942. if existing is not None and \
  943. existing is not node and \
  944. (node.is_block or existing.is_block):
  945. raise exceptions.CompileException(
  946. "%%def or %%block named '%s' already "
  947. "exists in this template." %
  948. node.funcname, **node.exception_kwargs)
  949. def visitDefTag(self, node):
  950. if node.is_root() and not node.is_anonymous:
  951. self._check_name_exists(self.topleveldefs, node)
  952. elif node is not self.node:
  953. self._check_name_exists(self.closuredefs, node)
  954. for ident in node.undeclared_identifiers():
  955. if ident != 'context' and\
  956. ident not in self.declared.union(self.locally_declared):
  957. self.undeclared.add(ident)
  958. # visit defs only one level deep
  959. if node is self.node:
  960. for ident in node.declared_identifiers():
  961. self.argument_declared.add(ident)
  962. for n in node.nodes:
  963. n.accept_visitor(self)
  964. def visitBlockTag(self, node):
  965. if node is not self.node and \
  966. not node.is_anonymous:
  967. if isinstance(self.node, parsetree.DefTag):
  968. raise exceptions.CompileException(
  969. "Named block '%s' not allowed inside of def '%s'"
  970. % (node.name, self.node.name), **node.exception_kwargs)
  971. elif isinstance(self.node,
  972. (parsetree.CallTag, parsetree.CallNamespaceTag)):
  973. raise exceptions.CompileException(
  974. "Named block '%s' not allowed inside of <%%call> tag"
  975. % (node.name, ), **node.exception_kwargs)
  976. for ident in node.undeclared_identifiers():
  977. if ident != 'context' and \
  978. ident not in self.declared.union(self.locally_declared):
  979. self.undeclared.add(ident)
  980. if not node.is_anonymous:
  981. self._check_name_exists(self.topleveldefs, node)
  982. self.undeclared.add(node.funcname)
  983. elif node is not self.node:
  984. self._check_name_exists(self.closuredefs, node)
  985. for ident in node.declared_identifiers():
  986. self.argument_declared.add(ident)
  987. for n in node.nodes:
  988. n.accept_visitor(self)
  989. def visitTextTag(self, node):
  990. for ident in node.undeclared_identifiers():
  991. if ident != 'context' and \
  992. ident not in self.declared.union(self.locally_declared):
  993. self.undeclared.add(ident)
  994. def visitIncludeTag(self, node):
  995. self.check_declared(node)
  996. def visitPageTag(self, node):
  997. for ident in node.declared_identifiers():
  998. self.argument_declared.add(ident)
  999. self.check_declared(node)
  1000. def visitCallNamespaceTag(self, node):
  1001. self.visitCallTag(node)
  1002. def visitCallTag(self, node):
  1003. if node is self.node:
  1004. for ident in node.undeclared_identifiers():
  1005. if ident != 'context' and\
  1006. ident not in self.declared.union(self.locally_declared):
  1007. self.undeclared.add(ident)
  1008. for ident in node.declared_identifiers():
  1009. self.argument_declared.add(ident)
  1010. for n in node.nodes:
  1011. n.accept_visitor(self)
  1012. else:
  1013. for ident in node.undeclared_identifiers():
  1014. if ident != 'context' and\
  1015. ident not in self.declared.union(self.locally_declared):
  1016. self.undeclared.add(ident)
  1017. _FOR_LOOP = re.compile(
  1018. r'^for\s+((?:\(?)\s*[A-Za-z_][A-Za-z_0-9]*'
  1019. r'(?:\s*,\s*(?:[A-Za-z_][A-Za-z0-9_]*),??)*\s*(?:\)?))\s+in\s+(.*):'
  1020. )
  1021. def mangle_mako_loop(node, printer):
  1022. """converts a for loop into a context manager wrapped around a for loop
  1023. when access to the `loop` variable has been detected in the for loop body
  1024. """
  1025. loop_variable = LoopVariable()
  1026. node.accept_visitor(loop_variable)
  1027. if loop_variable.detected:
  1028. node.nodes[-1].has_loop_context = True
  1029. match = _FOR_LOOP.match(node.text)
  1030. if match:
  1031. printer.writelines(
  1032. 'loop = __M_loop._enter(%s)' % match.group(2),
  1033. 'try:'
  1034. #'with __M_loop(%s) as loop:' % match.group(2)
  1035. )
  1036. text = 'for %s in loop:' % match.group(1)
  1037. else:
  1038. raise SyntaxError("Couldn't apply loop context: %s" % node.text)
  1039. else:
  1040. text = node.text
  1041. return text
  1042. class LoopVariable(object):
  1043. """A node visitor which looks for the name 'loop' within undeclared
  1044. identifiers."""
  1045. def __init__(self):
  1046. self.detected = False
  1047. def _loop_reference_detected(self, node):
  1048. if 'loop' in node.undeclared_identifiers():
  1049. self.detected = True
  1050. else:
  1051. for n in node.get_children():
  1052. n.accept_visitor(self)
  1053. def visitControlLine(self, node):
  1054. self._loop_reference_detected(node)
  1055. def visitCode(self, node):
  1056. self._loop_reference_detected(node)
  1057. def visitExpression(self, node):
  1058. self._loop_reference_detected(node)