added support for token stream filtering and preprocessing.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent e3290ea · Browse files · 7 files·+109 added−59 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+109 added−59 removed
- other:+109 added−59 removed
Provenance
- Commit
9ad96e7- Tree
9218904- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e3290ea
7 files changed+109 added−59 removed
modified:docs/api.rst+2 added
588 unmodified lines589 .. automethod:: Environment.lex590 591 .. automethod:: Environment.parse592 593+.. automethod:: Environment.preprocess594+595 .. automethod:: Template.new_context596 597 .. method:: Template.root_render_func(context)598 27 unmodified linesmodified:docs/extensions.rst+1 added-1 removed
166 unmodified lines167 168 Extensions always have to extend the :class:`jinja2.ext.Extension` class:169 170 .. autoclass:: Extension171- :members: parse, attr, call_method171+ :members: preprocess, filter_stream, parse, attr, call_method172 173 .. attribute:: identifier174 175 The identifier of the extension. This is always the true import name74 unmodified linesmodified:jinja2/environment.py+29 added-2 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import sys12 from jinja2.defaults import *13-from jinja2.lexer import Lexer13+from jinja2.lexer import Lexer, TokenStream14 from jinja2.parser import Parser15 from jinja2.optimizer import optimize16 from jinja2.compiler import generate17 from jinja2.runtime import Undefined, Context320 unmodified lines338 """Lex the given sourcecode and return a generator that yields339 tokens as tuples in the form ``(lineno, token_type, value)``.340 This can be useful for :ref:`extension development <writing-extensions>`341 and debugging templates.342+343+ This does not perform preprocessing. If you want the preprocessing344+ of the extensions to be applied you have to filter source through345+ the :meth:`preprocess` method.346 """343- return self.lexer.tokeniter(source, name, filename)347+ return self.lexer.tokeniter(unicode(source), name, filename)348 349+ def preprocess(self, source, name=None, filename=None):350+ """Preprocesses the source with all extensions. This is automatically351+ called for all parsing and compiling methods but *not* for :meth:`lex`352+ because there you usually only want the actual source tokenized.353+ """354+ return reduce(lambda s, e: e.preprocess(s, name, filename),355+ self.extensions.itervalues(), unicode(source))356+357+ def _tokenize(self, source, name, filename=None):358+ """Called by the parser to do the preprocessing and filtering359+ for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.360+ """361+ def _stream(iterable):362+ if not isinstance(iterable, TokenStream):363+ iterable = TokenStream(iterable, name, filename)364+ return iterable365+ source = self.preprocess(source, name, filename)366+ tokeniter = self.lexer.tokeniter(source, name, filename)367+ stream = _stream(self.lexer.wrap(tokeniter, name, filename))368+ for ext in self.extensions.itervalues():369+ stream = _stream(ext.filter_stream(stream))370+ return stream371+372 def compile(self, source, name=None, filename=None, raw=False):373 """Compile a node or template source code. The `name` parameter is374 the load name of the template after it was joined using375 :meth:`join_path` if necessary, not the filename on the file system.353 unmodified linesmodified:jinja2/ext.py+16 added
14 unmodified lines15 from jinja2.defaults import *16 from jinja2.environment import get_spontaneous_environment17 from jinja2.runtime import Undefined, concat18 from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError19+from jinja2.lexer import Token20 from jinja2.utils import contextfunction, import_string, Markup21 22 23 # the only real useful gettext functions for a Jinja template. Note43 unmodified lines67 rv.__dict__.update(self.__dict__)68 rv.environment = environment69 return rv70 71+ def preprocess(self, source, name, filename=None):72+ """This method is called before the actual lexing and can be used to73+ preprocess the source. The `filename` is optional. The return value74+ must be the preprocessed source.75+ """76+ return source77+78+ def filter_stream(self, stream):79+ """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used80+ to filter tokens returned. This method has to return an iterable of81+ :class:`~jinja2.lexer.Token`\s, but it doesn't have to return a82+ :class:`~jinja2.lexer.TokenStream`.83+ """84+ return stream85+86 def parse(self, parser):87 """If any of the :attr:`tags` matched this method is called with the88 parser as first argument. The token the parser stream is pointing at89 is the name token that matched. This method has to return one or a310 unmodified linesmodified:jinja2/lexer.py+56 added-54 removed
131 unmodified lines132 until the eof token is reached.133 """134 135 def __init__(self, stream):136- self._stream = stream136+ self.stream = stream137 138 def __iter__(self):139 return self140 141 def next(self):142- token = self._stream.current142+ token = self.stream.current143 if token.type == 'eof':144- self._stream.close()144+ self.stream.close()145 raise StopIteration()146- self._stream.next(False)146+ self.stream.next()147 return token148 149 150 class TokenStream(object):2 unmodified lines153 one token ahead. The current active token is stored as :attr:`current`.154 """155 156 def __init__(self, generator, name, filename):157- self._next = generator.next157+ self._next = iter(generator).next158 self._pushed = deque()159- self.current = Token(1, 'initial', '')159 self.name = name160 self.filename = filename161+ self.closed = False162+ self.current = Token(1, 'initial', '')163 self.next()164 165 def __iter__(self):166 return TokenStreamIterator(self)47 unmodified lines214 def close(self):215 """Close the stream."""216 self.current = Token(self.current.lineno, 'eof', '')217 self._next = None218+ self.closed = True219 220 def expect(self, expr):221 """Expect a given token type and return it. This accepts the same222 argument as :meth:`jinja2.lexer.Token.test`.152 unmodified lines375 """Called for strings and template data to normlize it to unicode."""376 return newline_re.sub(self.newline_sequence, value)377 378 def tokenize(self, source, name=None, filename=None):377- """Works like `tokeniter` but returns a tokenstream of tokens and not378- a generator or token tuples. Additionally all token values are already379- converted into types and postprocessed. For example comments are removed,380- integers and floats converted, strings unescaped etc.379+ """Calls tokeniter + tokenize and wraps it in a token stream.380+ This is currently only used for unittests.381 """382+ stream = self.tokeniter(source, name, filename)383+ return TokenStream(self.wrap(stream, name, filename), name, filename)384+385+ def wrap(self, stream, name=None, filename=None):386+ """This is called with the stream as returned by `tokenize` and wraps387+ every token in a :class:`Token` and converts the value.382- def generate():383- for lineno, token, value in self.tokeniter(source, name, filename):384- if token in ('comment_begin', 'comment', 'comment_end',385- 'whitespace'):386- continue387- elif token == 'linestatement_begin':388- token = 'block_begin'389- elif token == 'linestatement_end':390- token = 'block_end'391- # we are not interested in those tokens in the parser392- elif token in ('raw_begin', 'raw_end'):393- continue394- elif token == 'data':395- value = self._normalize_newlines(value)396- elif token == 'keyword':397- token = value398- elif token == 'name':388+ """389+ for lineno, token, value in stream:390+ if token in ('comment_begin', 'comment', 'comment_end',391+ 'whitespace'):392+ continue393+ elif token == 'linestatement_begin':394+ token = 'block_begin'395+ elif token == 'linestatement_end':396+ token = 'block_end'397+ # we are not interested in those tokens in the parser398+ elif token in ('raw_begin', 'raw_end'):399+ continue400+ elif token == 'data':401+ value = self._normalize_newlines(value)402+ elif token == 'keyword':403+ token = value404+ elif token == 'name':405+ value = str(value)406+ elif token == 'string':407+ # try to unescape string408+ try:409+ value = self._normalize_newlines(value[1:-1]) \410+ .encode('ascii', 'backslashreplace') \411+ .decode('unicode-escape')412+ except Exception, e:413+ msg = str(e).split(':')[-1].strip()414+ raise TemplateSyntaxError(msg, lineno, name, filename)415+ # if we can express it as bytestring (ascii only)416+ # we do that for support of semi broken APIs417+ # as datetime.datetime.strftime418+ try:419 value = str(value)400- elif token == 'string':401- # try to unescape string402- try:403- value = self._normalize_newlines(value[1:-1]) \404- .encode('ascii', 'backslashreplace') \405- .decode('unicode-escape')406- except Exception, e:407- msg = str(e).split(':')[-1].strip()408- raise TemplateSyntaxError(msg, lineno, name, filename)409- # if we can express it as bytestring (ascii only)410- # we do that for support of semi broken APIs411- # as datetime.datetime.strftime412- try:413- value = str(value)414- except UnicodeError:415- pass416- elif token == 'integer':417- value = int(value)418- elif token == 'float':419- value = float(value)420- elif token == 'operator':421- token = operators[value]422- yield Token(lineno, token, value)420+ except UnicodeError:421+ pass422+ elif token == 'integer':423+ value = int(value)424+ elif token == 'float':425+ value = float(value)426+ elif token == 'operator':427+ token = operators[value]428+ yield Token(lineno, token, value)423- return TokenStream(generate(), name, filename)429 430 def tokeniter(self, source, name, filename=None):431 """This method tokenizes the text and returns the tokens in a432 generator. Use this method if you just want to tokenize a template.428- The output you get is not compatible with the input the jinja parser429- wants. The parser uses the `tokenize` function with returns a430- `TokenStream` and postprocessed tokens.433 """434 source = '\n'.join(unicode(source).splitlines())435 pos = 0436 lineno = 1121 unmodified linesmodified:jinja2/parser.py+1 added-2 removed
23 unmodified lines24 """25 26 def __init__(self, environment, source, name=None, filename=None):27 self.environment = environment28- self.source = unicode(source)28+ self.stream = environment._tokenize(source, name, filename)29 self.name = name30 self.filename = filename31 self.closed = False32- self.stream = environment.lexer.tokenize(self.source, name, filename)32 self.extensions = {}33 for extension in environment.extensions.itervalues():34 for tag in extension.tags:35 self.extensions[tag] = extension.parse728 unmodified linesmodified:CHANGES+4 added
11 unmodified lines12 :class:`~jinja2.nodes.Getitem` and :class:`~jinja2.nodes.Getattr`.13 14 For more information see :ref:`the implementation details <notes-on-subscribing>`.15 16+- added support for preprocessing and token stream filtering for extensions.17+ This would allow extensions to allow simplified gettext calls in template18+ data and something similar.19+20 Version 2.0rc121 --------------22 (no codename, released on July 9th 2008)23 1 unmodified line