Skip to content
Myr

parser.py

This file

Path

jinja2/parser.py

783 lines · 30.0 KiB · Python

Last changed by

Added support for optional `scoped` modifier to blocks.Armin Ronacherbefore adoption74a0cd9

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    jinja2.parser4    ~~~~~~~~~~~~~56    Implements the template parser.78    :copyright: (c) 2009 by the Jinja Team.9    :license: BSD, see LICENSE for more details.10"""11from jinja2 import nodes12from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError131415_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',16                                 'macro', 'include', 'from', 'import',17                                 'set'])18_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])192021class Parser(object):22    """This is the central parsing class Jinja2 uses.  It's passed to23    extensions and can be used to parse expressions or statements.24    """2526    def __init__(self, environment, source, name=None, filename=None,27                 state=None):28        self.environment = environment29        self.stream = environment._tokenize(source, name, filename, state)30        self.name = name31        self.filename = filename32        self.closed = False33        self.extensions = {}34        for extension in environment.extensions.itervalues():35            for tag in extension.tags:36                self.extensions[tag] = extension.parse37        self._last_identifier = 03839    def fail(self, msg, lineno=None, exc=TemplateSyntaxError):40        """Convenience method that raises `exc` with the message, passed41        line number or last line number as well as the current name and42        filename.43        """44        if lineno is None:45            lineno = self.stream.current.lineno46        raise exc(msg, lineno, self.name, self.filename)4748    def is_tuple_end(self, extra_end_rules=None):49        """Are we at the end of a tuple?"""50        if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):51            return True52        elif extra_end_rules is not None:53            return self.stream.current.test_any(extra_end_rules)54        return False5556    def free_identifier(self, lineno=None):57        """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""58        self._last_identifier += 159        rv = object.__new__(nodes.InternalName)60        nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)61        return rv6263    def parse_statement(self):64        """Parse a single statement."""65        token = self.stream.current66        if token.type != 'name':67            self.fail('tag name expected', token.lineno)68        if token.value in _statement_keywords:69            return getattr(self, 'parse_' + self.stream.current.value)()70        if token.value == 'call':71            return self.parse_call_block()72        if token.value == 'filter':73            return self.parse_filter_block()74        ext = self.extensions.get(token.value)75        if ext is not None:76            return ext(self)77        self.fail('unknown tag %r' % token.value, token.lineno)7879    def parse_statements(self, end_tokens, drop_needle=False):80        """Parse multiple statements into a list until one of the end tokens81        is reached.  This is used to parse the body of statements as it also82        parses template data if appropriate.  The parser checks first if the83        current token is a colon and skips it if there is one.  Then it checks84        for the block end and parses until if one of the `end_tokens` is85        reached.  Per default the active token in the stream at the end of86        the call is the matched end token.  If this is not wanted `drop_needle`87        can be set to `True` and the end token is removed.88        """89        # the first token may be a colon for python compatibility90        self.stream.skip_if('colon')9192        # in the future it would be possible to add whole code sections93        # by adding some sort of end of statement token and parsing those here.94        self.stream.expect('block_end')95        result = self.subparse(end_tokens)9697        if drop_needle:98            self.stream.next()99        return result100101    def parse_set(self):102        """Parse an assign statement."""103        lineno = self.stream.next().lineno104        target = self.parse_assign_target()105        self.stream.expect('assign')106        expr = self.parse_tuple()107        return nodes.Assign(target, expr, lineno=lineno)108109    def parse_for(self):110        """Parse a for loop."""111        lineno = self.stream.expect('name:for').lineno112        target = self.parse_assign_target(extra_end_rules=('name:in',))113        self.stream.expect('name:in')114        iter = self.parse_tuple(with_condexpr=False,115                                extra_end_rules=('name:recursive',))116        test = None117        if self.stream.skip_if('name:if'):118            test = self.parse_expression()119        recursive = self.stream.skip_if('name:recursive')120        body = self.parse_statements(('name:endfor', 'name:else'))121        if self.stream.next().value == 'endfor':122            else_ = []123        else:124            else_ = self.parse_statements(('name:endfor',), drop_needle=True)125        return nodes.For(target, iter, body, else_, test,126                         recursive, lineno=lineno)127128    def parse_if(self):129        """Parse an if construct."""130        node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)131        while 1:132            node.test = self.parse_tuple(with_condexpr=False)133            node.body = self.parse_statements(('name:elif', 'name:else',134                                               'name:endif'))135            token = self.stream.next()136            if token.test('name:elif'):137                new_node = nodes.If(lineno=self.stream.current.lineno)138                node.else_ = [new_node]139                node = new_node140                continue141            elif token.test('name:else'):142                node.else_ = self.parse_statements(('name:endif',),143                                                   drop_needle=True)144            else:145                node.else_ = []146            break147        return result148149    def parse_block(self):150        node = nodes.Block(lineno=self.stream.next().lineno)151        node.name = self.stream.expect('name').value152        node.scoped = self.stream.skip_if('name:scoped')153        node.body = self.parse_statements(('name:endblock',), drop_needle=True)154        self.stream.skip_if('name:' + node.name)155        return node156157    def parse_extends(self):158        node = nodes.Extends(lineno=self.stream.next().lineno)159        node.template = self.parse_expression()160        return node161162    def parse_import_context(self, node, default):163        if self.stream.current.test_any('name:with', 'name:without') and \164           self.stream.look().test('name:context'):165            node.with_context = self.stream.next().value == 'with'166            self.stream.skip()167        else:168            node.with_context = default169        return node170171    def parse_include(self):172        node = nodes.Include(lineno=self.stream.next().lineno)173        node.template = self.parse_expression()174        if self.stream.current.test('name:ignore') and \175           self.stream.look().test('name:missing'):176            node.ignore_missing = True177            self.stream.skip(2)178        else:179            node.ignore_missing = False180        return self.parse_import_context(node, True)181182    def parse_import(self):183        node = nodes.Import(lineno=self.stream.next().lineno)184        node.template = self.parse_expression()185        self.stream.expect('name:as')186        node.target = self.parse_assign_target(name_only=True).name187        return self.parse_import_context(node, False)188189    def parse_from(self):190        node = nodes.FromImport(lineno=self.stream.next().lineno)191        node.template = self.parse_expression()192        self.stream.expect('name:import')193        node.names = []194195        def parse_context():196            if self.stream.current.value in ('with', 'without') and \197               self.stream.look().test('name:context'):198                node.with_context = self.stream.next().value == 'with'199                self.stream.skip()200                return True201            return False202203        while 1:204            if node.names:205                self.stream.expect('comma')206            if self.stream.current.type == 'name':207                if parse_context():208                    break209                target = self.parse_assign_target(name_only=True)210                if target.name.startswith('_'):211                    self.fail('names starting with an underline can not '212                              'be imported', target.lineno,213                              exc=TemplateAssertionError)214                if self.stream.skip_if('name:as'):215                    alias = self.parse_assign_target(name_only=True)216                    node.names.append((target.name, alias.name))217                else:218                    node.names.append(target.name)219                if parse_context() or self.stream.current.type != 'comma':220                    break221            else:222                break223        if not hasattr(node, 'with_context'):224            node.with_context = False225            self.stream.skip_if('comma')226        return node227228    def parse_signature(self, node):229        node.args = args = []230        node.defaults = defaults = []231        self.stream.expect('lparen')232        while self.stream.current.type != 'rparen':233            if args:234                self.stream.expect('comma')235            arg = self.parse_assign_target(name_only=True)236            arg.set_ctx('param')237            if self.stream.skip_if('assign'):238                defaults.append(self.parse_expression())239            args.append(arg)240        self.stream.expect('rparen')241242    def parse_call_block(self):243        node = nodes.CallBlock(lineno=self.stream.next().lineno)244        if self.stream.current.type == 'lparen':245            self.parse_signature(node)246        else:247            node.args = []248            node.defaults = []249250        node.call = self.parse_expression()251        if not isinstance(node.call, nodes.Call):252            self.fail('expected call', node.lineno)253        node.body = self.parse_statements(('name:endcall',), drop_needle=True)254        return node255256    def parse_filter_block(self):257        node = nodes.FilterBlock(lineno=self.stream.next().lineno)258        node.filter = self.parse_filter(None, start_inline=True)259        node.body = self.parse_statements(('name:endfilter',),260                                          drop_needle=True)261        return node262263    def parse_macro(self):264        node = nodes.Macro(lineno=self.stream.next().lineno)265        node.name = self.parse_assign_target(name_only=True).name266        self.parse_signature(node)267        node.body = self.parse_statements(('name:endmacro',),268                                          drop_needle=True)269        return node270271    def parse_print(self):272        node = nodes.Output(lineno=self.stream.next().lineno)273        node.nodes = []274        while self.stream.current.type != 'block_end':275            if node.nodes:276                self.stream.expect('comma')277            node.nodes.append(self.parse_expression())278        return node279280    def parse_assign_target(self, with_tuple=True, name_only=False,281                            extra_end_rules=None):282        """Parse an assignment target.  As Jinja2 allows assignments to283        tuples, this function can parse all allowed assignment targets.  Per284        default assignments to tuples are parsed, that can be disable however285        by setting `with_tuple` to `False`.  If only assignments to names are286        wanted `name_only` can be set to `True`.  The `extra_end_rules`287        parameter is forwarded to the tuple parsing function.288        """289        if name_only:290            token = self.stream.expect('name')291            target = nodes.Name(token.value, 'store', lineno=token.lineno)292        else:293            if with_tuple:294                target = self.parse_tuple(simplified=True,295                                          extra_end_rules=extra_end_rules)296            else:297                target = self.parse_primary(with_postfix=False)298            target.set_ctx('store')299        if not target.can_assign():300            self.fail('can\'t assign to %r' % target.__class__.301                      __name__.lower(), target.lineno)302        return target303304    def parse_expression(self, with_condexpr=True):305        """Parse an expression.  Per default all expressions are parsed, if306        the optional `with_condexpr` parameter is set to `False` conditional307        expressions are not parsed.308        """309        if with_condexpr:310            return self.parse_condexpr()311        return self.parse_or()312313    def parse_condexpr(self):314        lineno = self.stream.current.lineno315        expr1 = self.parse_or()316        while self.stream.skip_if('name:if'):317            expr2 = self.parse_or()318            if self.stream.skip_if('name:else'):319                expr3 = self.parse_condexpr()320            else:321                expr3 = None322            expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)323            lineno = self.stream.current.lineno324        return expr1325326    def parse_or(self):327        lineno = self.stream.current.lineno328        left = self.parse_and()329        while self.stream.skip_if('name:or'):330            right = self.parse_and()331            left = nodes.Or(left, right, lineno=lineno)332            lineno = self.stream.current.lineno333        return left334335    def parse_and(self):336        lineno = self.stream.current.lineno337        left = self.parse_not()338        while self.stream.skip_if('name:and'):339            right = self.parse_not()340            left = nodes.And(left, right, lineno=lineno)341            lineno = self.stream.current.lineno342        return left343344    def parse_not(self):345        if self.stream.current.test('name:not'):346            lineno = self.stream.next().lineno347            return nodes.Not(self.parse_not(), lineno=lineno)348        return self.parse_compare()349350    def parse_compare(self):351        lineno = self.stream.current.lineno352        expr = self.parse_add()353        ops = []354        while 1:355            token_type = self.stream.current.type356            if token_type in _compare_operators:357                self.stream.next()358                ops.append(nodes.Operand(token_type, self.parse_add()))359            elif self.stream.skip_if('name:in'):360                ops.append(nodes.Operand('in', self.parse_add()))361            elif self.stream.current.test('name:not') and \362                 self.stream.look().test('name:in'):363                self.stream.skip(2)364                ops.append(nodes.Operand('notin', self.parse_add()))365            else:366                break367            lineno = self.stream.current.lineno368        if not ops:369            return expr370        return nodes.Compare(expr, ops, lineno=lineno)371372    def parse_add(self):373        lineno = self.stream.current.lineno374        left = self.parse_sub()375        while self.stream.current.type == 'add':376            self.stream.next()377            right = self.parse_sub()378            left = nodes.Add(left, right, lineno=lineno)379            lineno = self.stream.current.lineno380        return left381382    def parse_sub(self):383        lineno = self.stream.current.lineno384        left = self.parse_concat()385        while self.stream.current.type == 'sub':386            self.stream.next()387            right = self.parse_concat()388            left = nodes.Sub(left, right, lineno=lineno)389            lineno = self.stream.current.lineno390        return left391392    def parse_concat(self):393        lineno = self.stream.current.lineno394        args = [self.parse_mul()]395        while self.stream.current.type == 'tilde':396            self.stream.next()397            args.append(self.parse_mul())398        if len(args) == 1:399            return args[0]400        return nodes.Concat(args, lineno=lineno)401402    def parse_mul(self):403        lineno = self.stream.current.lineno404        left = self.parse_div()405        while self.stream.current.type == 'mul':406            self.stream.next()407            right = self.parse_div()408            left = nodes.Mul(left, right, lineno=lineno)409            lineno = self.stream.current.lineno410        return left411412    def parse_div(self):413        lineno = self.stream.current.lineno414        left = self.parse_floordiv()415        while self.stream.current.type == 'div':416            self.stream.next()417            right = self.parse_floordiv()418            left = nodes.Div(left, right, lineno=lineno)419            lineno = self.stream.current.lineno420        return left421422    def parse_floordiv(self):423        lineno = self.stream.current.lineno424        left = self.parse_mod()425        while self.stream.current.type == 'floordiv':426            self.stream.next()427            right = self.parse_mod()428            left = nodes.FloorDiv(left, right, lineno=lineno)429            lineno = self.stream.current.lineno430        return left431432    def parse_mod(self):433        lineno = self.stream.current.lineno434        left = self.parse_pow()435        while self.stream.current.type == 'mod':436            self.stream.next()437            right = self.parse_pow()438            left = nodes.Mod(left, right, lineno=lineno)439            lineno = self.stream.current.lineno440        return left441442    def parse_pow(self):443        lineno = self.stream.current.lineno444        left = self.parse_unary()445        while self.stream.current.type == 'pow':446            self.stream.next()447            right = self.parse_unary()448            left = nodes.Pow(left, right, lineno=lineno)449            lineno = self.stream.current.lineno450        return left451452    def parse_unary(self):453        token_type = self.stream.current.type454        lineno = self.stream.current.lineno455        if token_type == 'sub':456            self.stream.next()457            node = self.parse_unary()458            return nodes.Neg(node, lineno=lineno)459        if token_type == 'add':460            self.stream.next()461            node = self.parse_unary()462            return nodes.Pos(node, lineno=lineno)463        return self.parse_primary()464465    def parse_primary(self, with_postfix=True):466        token = self.stream.current467        if token.type == 'name':468            if token.value in ('true', 'false', 'True', 'False'):469                node = nodes.Const(token.value in ('true', 'True'),470                                   lineno=token.lineno)471            elif token.value in ('none', 'None'):472                node = nodes.Const(None, lineno=token.lineno)473            else:474                node = nodes.Name(token.value, 'load', lineno=token.lineno)475            self.stream.next()476        elif token.type == 'string':477            self.stream.next()478            buf = [token.value]479            lineno = token.lineno480            while self.stream.current.type == 'string':481                buf.append(self.stream.current.value)482                self.stream.next()483            node = nodes.Const(''.join(buf), lineno=lineno)484        elif token.type in ('integer', 'float'):485            self.stream.next()486            node = nodes.Const(token.value, lineno=token.lineno)487        elif token.type == 'lparen':488            self.stream.next()489            node = self.parse_tuple()490            self.stream.expect('rparen')491        elif token.type == 'lbracket':492            node = self.parse_list()493        elif token.type == 'lbrace':494            node = self.parse_dict()495        else:496            self.fail("unexpected token '%s'" % (token,), token.lineno)497        if with_postfix:498            node = self.parse_postfix(node)499        return node500501    def parse_tuple(self, simplified=False, with_condexpr=True,502                    extra_end_rules=None):503        """Works like `parse_expression` but if multiple expressions are504        delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.505        This method could also return a regular expression instead of a tuple506        if no commas where found.507508        The default parsing mode is a full tuple.  If `simplified` is `True`509        only names and literals are parsed.  The `no_condexpr` parameter is510        forwarded to :meth:`parse_expression`.511512        Because tuples do not require delimiters and may end in a bogus comma513        an extra hint is needed that marks the end of a tuple.  For example514        for loops support tuples between `for` and `in`.  In that case the515        `extra_end_rules` is set to ``['name:in']``.516        """517        lineno = self.stream.current.lineno518        if simplified:519            parse = lambda: self.parse_primary(with_postfix=False)520        elif with_condexpr:521            parse = self.parse_expression522        else:523            parse = lambda: self.parse_expression(with_condexpr=False)524        args = []525        is_tuple = False526        while 1:527            if args:528                self.stream.expect('comma')529            if self.is_tuple_end(extra_end_rules):530                break531            args.append(parse())532            if self.stream.current.type == 'comma':533                is_tuple = True534            else:535                break536            lineno = self.stream.current.lineno537        if not is_tuple and args:538            return args[0]539        return nodes.Tuple(args, 'load', lineno=lineno)540541    def parse_list(self):542        token = self.stream.expect('lbracket')543        items = []544        while self.stream.current.type != 'rbracket':545            if items:546                self.stream.expect('comma')547            if self.stream.current.type == 'rbracket':548                break549            items.append(self.parse_expression())550        self.stream.expect('rbracket')551        return nodes.List(items, lineno=token.lineno)552553    def parse_dict(self):554        token = self.stream.expect('lbrace')555        items = []556        while self.stream.current.type != 'rbrace':557            if items:558                self.stream.expect('comma')559            if self.stream.current.type == 'rbrace':560                break561            key = self.parse_expression()562            self.stream.expect('colon')563            value = self.parse_expression()564            items.append(nodes.Pair(key, value, lineno=key.lineno))565        self.stream.expect('rbrace')566        return nodes.Dict(items, lineno=token.lineno)567568    def parse_postfix(self, node):569        while 1:570            token_type = self.stream.current.type571            if token_type == 'dot' or token_type == 'lbracket':572                node = self.parse_subscript(node)573            elif token_type == 'lparen':574                node = self.parse_call(node)575            elif token_type == 'pipe':576                node = self.parse_filter(node)577            elif token_type == 'name' and self.stream.current.value == 'is':578                node = self.parse_test(node)579            else:580                break581        return node582583    def parse_subscript(self, node):584        token = self.stream.next()585        if token.type == 'dot':586            attr_token = self.stream.current587            self.stream.next()588            if attr_token.type == 'name':589                return nodes.Getattr(node, attr_token.value, 'load',590                                     lineno=token.lineno)591            elif attr_token.type != 'integer':592                self.fail('expected name or number', attr_token.lineno)593            arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)594            return nodes.Getitem(node, arg, 'load', lineno=token.lineno)595        if token.type == 'lbracket':596            priority_on_attribute = False597            args = []598            while self.stream.current.type != 'rbracket':599                if args:600                    self.stream.expect('comma')601                args.append(self.parse_subscribed())602            self.stream.expect('rbracket')603            if len(args) == 1:604                arg = args[0]605            else:606                arg = nodes.Tuple(args, 'load', lineno=token.lineno)607            return nodes.Getitem(node, arg, 'load', lineno=token.lineno)608        self.fail('expected subscript expression', self.lineno)609610    def parse_subscribed(self):611        lineno = self.stream.current.lineno612613        if self.stream.current.type == 'colon':614            self.stream.next()615            args = [None]616        else:617            node = self.parse_expression()618            if self.stream.current.type != 'colon':619                return node620            self.stream.next()621            args = [node]622623        if self.stream.current.type == 'colon':624            args.append(None)625        elif self.stream.current.type not in ('rbracket', 'comma'):626            args.append(self.parse_expression())627        else:628            args.append(None)629630        if self.stream.current.type == 'colon':631            self.stream.next()632            if self.stream.current.type not in ('rbracket', 'comma'):633                args.append(self.parse_expression())634            else:635                args.append(None)636        else:637            args.append(None)638639        return nodes.Slice(lineno=lineno, *args)640641    def parse_call(self, node):642        token = self.stream.expect('lparen')643        args = []644        kwargs = []645        dyn_args = dyn_kwargs = None646        require_comma = False647648        def ensure(expr):649            if not expr:650                self.fail('invalid syntax for function call expression',651                          token.lineno)652653        while self.stream.current.type != 'rparen':654            if require_comma:655                self.stream.expect('comma')656                # support for trailing comma657                if self.stream.current.type == 'rparen':658                    break659            if self.stream.current.type == 'mul':660                ensure(dyn_args is None and dyn_kwargs is None)661                self.stream.next()662                dyn_args = self.parse_expression()663            elif self.stream.current.type == 'pow':664                ensure(dyn_kwargs is None)665                self.stream.next()666                dyn_kwargs = self.parse_expression()667            else:668                ensure(dyn_args is None and dyn_kwargs is None)669                if self.stream.current.type == 'name' and \670                    self.stream.look().type == 'assign':671                    key = self.stream.current.value672                    self.stream.skip(2)673                    value = self.parse_expression()674                    kwargs.append(nodes.Keyword(key, value,675                                                lineno=value.lineno))676                else:677                    ensure(not kwargs)678                    args.append(self.parse_expression())679680            require_comma = True681        self.stream.expect('rparen')682683        if node is None:684            return args, kwargs, dyn_args, dyn_kwargs685        return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs,686                          lineno=token.lineno)687688    def parse_filter(self, node, start_inline=False):689        while self.stream.current.type == 'pipe' or start_inline:690            if not start_inline:691                self.stream.next()692            token = self.stream.expect('name')693            name = token.value694            while self.stream.current.type == 'dot':695                self.stream.next()696                name += '.' + self.stream.expect('name').value697            if self.stream.current.type == 'lparen':698                args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)699            else:700                args = []701                kwargs = []702                dyn_args = dyn_kwargs = None703            node = nodes.Filter(node, name, args, kwargs, dyn_args,704                                dyn_kwargs, lineno=token.lineno)705            start_inline = False706        return node707708    def parse_test(self, node):709        token = self.stream.next()710        if self.stream.current.test('name:not'):711            self.stream.next()712            negated = True713        else:714            negated = False715        name = self.stream.expect('name').value716        while self.stream.current.type == 'dot':717            self.stream.next()718            name += '.' + self.stream.expect('name').value719        dyn_args = dyn_kwargs = None720        kwargs = []721        if self.stream.current.type == 'lparen':722            args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)723        elif self.stream.current.type in ('name', 'string', 'integer',724                                          'float', 'lparen', 'lbracket',725                                          'lbrace') and not \726             self.stream.current.test_any('name:else', 'name:or',727                                          'name:and'):728            if self.stream.current.test('name:is'):729                self.fail('You cannot chain multiple tests with is')730            args = [self.parse_expression()]731        else:732            args = []733        node = nodes.Test(node, name, args, kwargs, dyn_args,734                          dyn_kwargs, lineno=token.lineno)735        if negated:736            node = nodes.Not(node, lineno=token.lineno)737        return node738739    def subparse(self, end_tokens=None):740        body = []741        data_buffer = []742        add_data = data_buffer.append743744        def flush_data():745            if data_buffer:746                lineno = data_buffer[0].lineno747                body.append(nodes.Output(data_buffer[:], lineno=lineno))748                del data_buffer[:]749750        while self.stream:751            token = self.stream.current752            if token.type == 'data':753                if token.value:754                    add_data(nodes.TemplateData(token.value,755                                                lineno=token.lineno))756                self.stream.next()757            elif token.type == 'variable_begin':758                self.stream.next()759                add_data(self.parse_tuple(with_condexpr=True))760                self.stream.expect('variable_end')761            elif token.type == 'block_begin':762                flush_data()763                self.stream.next()764                if end_tokens is not None and \765                   self.stream.current.test_any(*end_tokens):766                    return body767                rv = self.parse_statement()768                if isinstance(rv, list):769                    body.extend(rv)770                else:771                    body.append(rv)772                self.stream.expect('block_end')773            else:774                raise AssertionError('internal parsing error')775776        flush_data()777        return body778779    def parse(self):780        """Parse the whole template into a `Template` node."""781        result = nodes.Template(self.subparse(), lineno=1)782        result.set_environment(self.environment)783        return result