changeset: 540:29c28e46b4a8 branch: loop_instrumentation tag: tip user: Benjamin Trofatter date: Sun Mar 18 14:08:30 2012 -0500 files: mako/codegen.py mako/lexer.py mako/parsetree.py mako/runtime.py test/test_loop.py description: Added loop instrumentation diff -r 2d31dd9bb37c -r 29c28e46b4a8 mako/codegen.py --- a/mako/codegen.py Mon Mar 12 14:22:46 2012 -0400 +++ b/mako/codegen.py Sun Mar 18 14:08:30 2012 -0500 @@ -169,6 +169,7 @@ self.printer.writeline("# -*- encoding:%s -*-" % self.compiler.source_encoding) + self.printer.writeline("from __future__ import with_statement") self.printer.writeline("from mako import runtime, filters, cache") self.printer.writeline("UNDEFINED = runtime.UNDEFINED") self.printer.writeline("__M_dict_builtin = dict") @@ -476,6 +477,12 @@ None ) else: + # insert method-level __M_loop if an undefined loop + # variable is found + if ident == 'loop': + self.printer.writeline( + '__M_loop = runtime.LoopStack()' + ) self.printer.writeline( "%s = context.get(%r, UNDEFINED)" % (ident, ident) ) @@ -708,10 +715,17 @@ if node.isend: if not node.get_children(): self.printer.writeline("pass") + # manually dedent when exiting loop context + if node.keyword == 'for' and node.with_loop_context: + self.printer.indent -= 1 self.printer.writeline(None) else: self.write_source_comment(node) - self.printer.writeline(node.text) + if node.keyword == 'for': + text = mangle_mako_loop(node, self.printer) + else: + text = node.text + self.printer.writeline(text) def visitText(self, node): self.write_source_comment(node) @@ -739,6 +753,9 @@ ) def visitCode(self, node): + # mangle loop variables within the scope of a loop context, + # if applicable + mangle_python_loop(self, node) if not node.ismodule: self.write_source_comment(node) self.printer.write_indented_block(node.text) @@ -1055,3 +1072,78 @@ if ident != 'context' and ident not in self.declared.union(self.locally_declared): self.undeclared.add(ident) + +_FOR_LOOP = re.compile( + r'^for\s+((?:\(?)\s*[A-Za-z_][A-Za-z_0-9]*' + r'(?:\s*,\s*(?:[A-Za-z_][A-Za-z0-9_]*),??)*\s*(?:\)?))\s+in\s+(.*):' + ) + +def mangle_python_loop(renderer, node): + """mangles references to the `loop` variable in in-line python code to + make special loop context attributes available + """ + in_loop_context = False + for n in [n for n in renderer.node.get_children() + if n.lineno > node.lineno]: + try: + in_loop_context = n.with_loop_context + except AttributeError: + pass + if in_loop_context and 'loop' in node.undeclared_identifiers(): + node.text = re.sub(r'\bloop\b', '__M_loop', node.text) + + +def mangle_mako_loop(node, printer): + """converts a for loop into a context manager wrapped around a for loop + when access to the `loop` variable has been detected in the for loop body + """ + loop_variable = LoopVariable() + for n in node.get_children(): + n.accept_visitor(loop_variable) + if loop_variable.detected: + node.with_loop_context = True + node.nodes[-1].with_loop_context = True + match = _FOR_LOOP.match(node.text) + if match: + printer.writeline( + 'with __M_loop(%s):' % match.group(2) + ) + text = 'for %s in __M_loop:' % match.group(1) + else: + raise SyntaxError("This didn't parse correctly: %s" % node.text) + else: + text = node.text + return text + + +class LoopVariable(object): + """A node visitor capable of looking forward into the mako parse tree at + the body of a for block to detect the use of the special `loop` variable. + Upon detection, each reference to the `loop` variable is mangled into the + function body variable __M_loop. + """ + + def __init__(self): + self.detected = False + + def _loop_reference_detected(self, node): + if 'loop' in node.declared_identifiers(): + raise TypeError("You can't assign to the loop variable") + if 'loop' in node.undeclared_identifiers(): + self.detected = True + return True + return False + + def visitControlLine(self, node): + if self._loop_reference_detected(node): + node.text = re.sub(r'\bloop\b', '__M_loop', node.text) + if node.keyword == 'for': + raise parsetree.TraversalInterupt + + def visitCode(self, node): + if self._loop_reference_detected(node): + node.text = re.sub(r'\bloop\b', '__M_loop', node.text) + + def visitExpression(self, node): + if self._loop_reference_detected(node): + node.text = re.sub(r'\bloop\b', '__M_loop', node.text) diff -r 2d31dd9bb37c -r 29c28e46b4a8 mako/lexer.py --- a/mako/lexer.py Mon Mar 12 14:22:46 2012 -0400 +++ b/mako/lexer.py Sun Mar 18 14:08:30 2012 -0500 @@ -128,6 +128,10 @@ self.tag[-1].nodes.append(node) else: self.template.nodes.append(node) + # build a set of child nodes for the control line + # (used for loop variable detection) + if self.control_line: + self.control_line[-1].nodes.append(node) if isinstance(node, parsetree.Tag): if len(self.tag): node.parent = self.tag[-1] diff -r 2d31dd9bb37c -r 29c28e46b4a8 mako/parsetree.py --- a/mako/parsetree.py Mon Mar 12 14:22:46 2012 -0400 +++ b/mako/parsetree.py Sun Mar 18 14:08:30 2012 -0500 @@ -8,6 +8,9 @@ from mako import exceptions, ast, util, filters import re + +class TraversalInterupt(Exception): + pass class Node(object): """base class for a Node in the parse tree.""" @@ -28,9 +31,16 @@ def accept_visitor(self, visitor): def traverse(node): for n in node.get_children(): - n.accept_visitor(visitor) + try: + n.accept_visitor(visitor) + except TraversalInterupt: + pass + method = getattr(visitor, "visit" + self.__class__.__name__, traverse) - method(self) + try: + method(self) + except TraversalInterupt: + pass class TemplateNode(Node): """a 'container' node that stores the overall collection of nodes.""" @@ -64,7 +74,9 @@ self.text = text self.keyword = keyword self.isend = isend - self.is_primary = keyword in ['for','if', 'while', 'try', 'with'] + self.is_primary = keyword in ['for', 'if', 'while', 'try', 'with'] + self.nodes = [] + self.with_loop_context = False if self.isend: self._declared_identifiers = [] self._undeclared_identifiers = [] @@ -73,6 +85,9 @@ self._declared_identifiers = code.declared_identifiers self._undeclared_identifiers = code.undeclared_identifiers + def get_children(self): + return self.nodes + def declared_identifiers(self): return self._declared_identifiers diff -r 2d31dd9bb37c -r 29c28e46b4a8 mako/runtime.py --- a/mako/runtime.py Mon Mar 12 14:22:46 2012 -0400 +++ b/mako/runtime.py Sun Mar 18 14:08:30 2012 -0500 @@ -187,6 +187,113 @@ UNDEFINED = Undefined() +class LoopStack(object): + """a stack for LoopContexts that implements the context manager protocol + to automatically pop off the top of the stack on context exit + """ + + def __init__(self): + self.stack = [] + + def __call__(self, iterable): + self._push(iterable) + return self + + @property + def _top(self): + return self.stack[-1] + + def _pop(self): + return self.stack.pop() + + def _push(self, iterable): + new = LoopContext(iterable) + if self.stack: + new.parent = self.stack[-1] + return self.stack.append(new) + + def __getattr__(self, key): + try: + return getattr(self.stack[-1], key) + except (IndexError, AttributeError): + return object.__getattribute__(self, key) + + def __iter__(self): + return iter(self._top) + + def __enter__(self): + pass + + def __exit__(self, type, value, traceback): + self._pop() + + +class LoopContext(object): + """A magic loop variable. + Automatically accessible in any %for block. + + :attr:`parent` -> LoopContext or None + The parent loop, if one exists + :attr:`index` -> int + The 0-based iteration count + :attr:`reverse_index` -> int + The number of iterations remaining + :attr:`first` -> bool + `True` on the first iteration, `False` otherwise + :attr:`last` -> bool + `True` on the last iteration, `False` otherwise + :attr:`even` -> bool + `True` when `index` is even + :attr:`odd` -> bool + `True` when `index` is odd + """ + + def __init__(self, iterable): + self._iterable = iterable + self.index = 0 + try: + self._length = len(iterable) + except (TypeError, AttributeError): + self._length = None + self.parent = None + + def __iter__(self): + for i in self._iterable: + yield i + self.index += 1 + raise StopIteration + + def __len__(self): + return self._length + + @property + def reverse_index(self): + return len(self) - self.index - 1 + + @property + def first(self): + return self.index == 0 + + @property + def last(self): + return self.index == len(self)-1 + + @property + def even(self): + return not self.odd + + @property + def odd(self): + return bool(self.index % 2) + + def cycle(self, *values): + """cycle through values as the loop progresses + """ + if not values: + raise ValueError("You must provide values to cycle through") + return values[self.index % len(values)] + + class _NSAttr(object): def __init__(self, parent): self.__parent = parent diff -r 2d31dd9bb37c -r 29c28e46b4a8 test/test_loop.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/test_loop.py Sun Mar 18 14:08:30 2012 -0500 @@ -0,0 +1,192 @@ +import re +import unittest + +from mako.template import Template +from mako.codegen import ( + _FOR_LOOP, mangle_python_loop, mangle_mako_loop, LoopVariable + ) +from mako.runtime import LoopStack, LoopContext + + +class TestLoop(unittest.TestCase): + + def test__FOR_LOOP(self): + for statement, target_list, expression_list in ( + ('for x in y:', 'x', 'y'), + ('for x, y in z:', 'x, y', 'z'), + ('for (x,y) in z:', '(x,y)', 'z'), + ('for ( x, y, z) in a:', '( x, y, z)', 'a'), + ('for x in [1, 2, 3]:', 'x', '[1, 2, 3]'), + ('for x in "spam":', 'x', '"spam"'), + ('for k,v in dict(a=1,b=2).items():', 'k,v', + 'dict(a=1,b=2).items()'), + ('for x in [y+1 for y in [1, 2, 3]]:', 'x', + '[y+1 for y in [1, 2, 3]]') + ): + match = _FOR_LOOP.match(statement) + assert match and match.groups() == (target_list, expression_list) + + def test_no_loop(self): + template = Template("""% for x in 'spam': +${x} +% endfor""") + code = template.code + assert not re.match(r"with __M_loop(.*):", code), "No need to "\ + "generate a loop context if the loop variable wasn't accessed" + print template.render() + + def test_loop_demo(self): + template = Template("""x|index|reverse_index|first|last|cycle|even|odd +% for x in 'ham': +${x}|${loop.index}|${loop.reverse_index}|${loop.first}|${loop.last}|${loop.cycle('even', 'odd')}|${loop.even}|${loop.odd} +% endfor""") + expected = [ + "x|index|reverse_index|first|last|cycle|even|odd", + "h|0|2|True|False|even|True|False", + "a|1|1|False|False|odd|False|True", + "m|2|0|False|True|even|True|False" + ] + code = template.code + assert "with __M_loop(" in code, "Generated a loop context since "\ + "the loop variable was accessed" + rendered = template.render() + print rendered + for line in expected: + assert line in rendered, "Loop variables give information about "\ + "the progress of the loop" + + def test_nested_loops(self): + template = Template("""% for x in 'ab': +${x} ${loop.index} <- start in outer loop +% for y in [0, 1]: +${y} ${loop.index} <- go to inner loop +% endfor +${x} ${loop.index} <- back to outer loop +% endfor""") + code = template.code + rendered = template.render() + expected = [ + "a 0 <- start in outer loop", + "0 0 <- go to inner loop", + "1 1 <- go to inner loop", + "a 0 <- back to outer loop", + "b 1 <- start in outer loop", + "0 0 <- go to inner loop", + "1 1 <- go to inner loop", + "b 1 <- back to outer loop", + ] + for line in expected: + assert line in rendered, "The LoopStack allows you to take "\ + "advantage of the loop variable even in embedded loops" + + def test_parent_loops(self): + template = Template("""% for x in 'ab': +${x} ${loop.index} <- outer loop +% for y in [0, 1]: +${y} ${loop.index} <- inner loop +${x} ${loop.parent.index} <- parent loop +% endfor +${x} ${loop.index} <- outer loop +% endfor""") + code = template.code + rendered = template.render() + expected = [ + "a 0 <- outer loop", + "a 0 <- parent loop", + "b 1 <- outer loop", + "b 1 <- parent loop" + ] + for line in expected: + print code + assert line in rendered, "The parent attribute of a loop gives "\ + "you the previous loop context in the stack" + + +class TestLoopStack(unittest.TestCase): + + def setUp(self): + self.stack = LoopStack() + self.bottom = 'spam' + self.stack.stack = [self.bottom] + + def test___call__(self): + iterable = 'ham' + s = self.stack(iterable) + assert s is self.stack, "Calling the stack with an iterable returns "\ + "the stack" + assert iterable == self.stack.stack[-1]._iterable, "and pushes the "\ + "iterable on the top of the stack" + + def test__top(self): + assert self.bottom == self.stack._top, "_top returns the last item "\ + "on the stack" + + def test__pop(self): + assert len(self.stack.stack) == 1 + top = self.stack._pop() + assert top == self.bottom + assert len(self.stack.stack) == 0 + + def test__push(self): + assert len(self.stack.stack) == 1 + iterable = 'ham' + self.stack._push(iterable) + assert len(self.stack.stack) == 2 + assert iterable is self.stack._top._iterable + + def test___exit__(self): + before = len(self.stack.stack) + with self.stack: + pass + after = len(self.stack.stack) + assert before == (after + 1), "Exiting a context pops the stack" + + +class TestLoopContext(unittest.TestCase): + + def setUp(self): + self.iterable = [1, 2, 3] + self.ctx = LoopContext(self.iterable) + + def test___len__(self): + assert len(self.iterable) == len(self.ctx), "The LoopContext is the "\ + "same length as the iterable" + + def test_index(self): + expected = tuple(range(len(self.iterable))) + actual = tuple(self.ctx.index for i in self.ctx) + assert expected == actual, "The index is consistent with the current "\ + "iteration count" + + def test_reverse_index(self): + length = len(self.iterable) + expected = tuple([length-i-1 for i in range(length)]) + actual = tuple(self.ctx.reverse_index for i in self.ctx) + print expected, actual + assert expected == actual, "The reverse_index is the number of "\ + "iterations until the end" + + def test_first(self): + expected = (True, False, False) + actual = tuple(self.ctx.first for i in self.ctx) + assert expected == actual, "first is only true on the first iteration" + + def test_last(self): + expected = (False, False, True) + actual = tuple(self.ctx.last for i in self.ctx) + assert expected == actual, "last is only true on the last iteration" + + def test_even(self): + expected = (True, False, True) + actual = tuple(self.ctx.even for i in self.ctx) + assert expected == actual, "even is true on even iterations" + + def test_odd(self): + expected = (False, True, False) + actual = tuple(self.ctx.odd for i in self.ctx) + assert expected == actual, "odd is true on odd iterations" + + def test_cycle(self): + expected = ('a', 'b', 'a') + actual = tuple(self.ctx.cycle('a', 'b') for i in self.ctx) + assert expected == actual, "cycle endlessly cycles through the values"