[svn] final jinja changes for today: implemented better filter lookup
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 eb1fbdf · Browse files · 6 files·+191 added−47 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+191 added−47 removed
- other:+191 added−47 removed
Provenance
- Commit
4271d77- Tree
8223ae7- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
eb1fbdf
6 files changed+191 added−47 removed
modified:jinja/translators/python.py+102 added-6 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from compiler import ast12 from jinja import nodes13+from jinja.exceptions import TemplateSyntaxError14 15 16 class PythonTranslator(object):17 """5 unmodified lines23 self.node = node24 self.indention = 025 self.last_pos = 026 27+ self.constants = {28+ 'true': 'True',29+ 'false': 'False',30+ 'none': 'None',31+ 'undefined': 'Undefined'32+ }33+34 self.handlers = {35 # jinja nodes36 nodes.Text: self.handle_template_text,37 nodes.NodeList: self.handle_node_list,14 unmodified lines52 ast.Sub: self.handle_sub,53 ast.Div: self.handle_div,54 ast.Mul: self.handle_mul,55 ast.Mod: self.handle_mod,56+ ast.UnaryAdd: self.handle_unary_add,57 ast.UnarySub: self.handle_unary_sub,58 ast.Power: self.handle_power,59 ast.Dict: self.handle_dict,60 ast.List: self.handle_list,61 ast.Tuple: self.handle_list,62 ast.And: self.handle_and,63 ast.Or: self.handle_or,55- ast.Not: self.handle_not64+ ast.Not: self.handle_not,65+ ast.Slice: self.handle_slice,66+ ast.Sliceobj: self.handle_sliceobj67 }68 69+ self.unsupported = {70+ ast.ListComp: 'list comprehensions',71+ ast.From: 'imports',72+ ast.Import: 'imports',73+ }74+ if hasattr(ast, 'GenExpr'):75+ self.unsupported.update({76+ ast.GenExpr: 'generator expressions'77+ })78+79 def indent(self, text):80 """81 Indent the current text.82 """4 unmodified lines87 Handle one node88 """89 if node.__class__ in self.handlers:90 out = self.handlers[node.__class__](node)91+ elif node.__class__ in self.unsupported:92+ raise TemplateSyntaxError('unsupported syntax element %r found.'93+ % self.unsupported[node.__class__],94+ self.last_pos)95 else:96 raise AssertionError('unhandled node %r' % node.__class__)97 return out98 75 unmodified lines174 def handle_name(self, node):175 """176 Handle name assignments and name retreivement.177 """178+ if node.name in self.constants:179+ return self.constants[node.name]180 return 'context[%r]' % node.name181 182 def handle_compare(self, node):183 """19 unmodified lines203 if len(node.subs) != 1:204 raise TemplateSyntaxError('attribute access requires one argument',205 self.last_pos)206 assert node.flags != 'OP_DELETE', 'wtf? do we support that?'207+ if node.subs[0].__class__ is ast.Sliceobj:208+ return '%s[%s]' % (209+ self.handle_node(node.expr),210+ self.handle_node(node.subs[0])211+ )180- return 'get_attribute(%s, %s)' % (212+ return 'environment.get_attribute(%s, %s)' % (213 self.handle_node(node.expr),214 self.handle_node(node.subs[0])215 )216 217 def handle_getattr(self, node):218 """219 Handle hardcoded attribute access. foo.bar220 """189- return 'get_attribute(%s, %r)' % (221+ return 'environment.get_attribute(%s, %r)' % (222 self.handle_node(node.expr),223 node.attrname224 )225 6 unmodified lines232 def handle_bitor(self, node):233 """234 We use the pipe operator for filtering.235 """236+ filters = []237+ for n in node.nodes[1:]:238+ if n.__class__ is ast.CallFunc:239+ args = []240+ for arg in n.args:241+ if arg.__class__ is ast.Keyword:242+ raise TemplateSyntaxError('keyword arguments for '243+ 'filters are not supported.',244+ self.last_pos)245+ args.append(self.handle_node(arg))246+ if n.star_args is not None or n.dstar_args is not None:247+ raise TemplateSynaxError('*args / **kwargs is not supported '248+ 'for filters', self.last_pos)249+ args = ', '.join(args)250+ if args:251+ args = ', ' + args252+ filters.append('environment.prepare_filter(%s%s)' % (253+ self.handle_node(n.node),254+ args255+ ))256+ elif n.__class__ is ast.Name:257+ filters.append('environment.prepare_filter(%s)' %258+ self.handle_node(n))259+ else:260+ raise TemplateSyntaxError('invalid filter. filter must be a '261+ 'hardcoded function name from the '262+ 'filter namespace',263+ self.last_pos)204- return 'environment.apply_filters(%s, [%s])' % (264+ return 'environment.apply_filters(%s, context, [%s])' % (265 self.handle_node(node.nodes[0]),206- ', '.join([self.handle_node(n) for n in node.nodes[1:]])266+ ', '.join(filters)267 )268 269 def handle_call_func(self, node):270 """63 unmodified lines334 self.handle_node(node.left),335 self.handle_node(node.right)336 )337 338+ def handle_unary_add(self, node):339+ """340+ One of the more or less unused nodes.341+ """342+ return '(+%s)' % self.handle_node(node.expr)343+344 def handle_unary_sub(self, node):345 """346 Make a number negative.347 """23 unmodified lines371 """372 We don't know tuples, tuples are lists for jinja.373 """374 return '[%s]' % ', '.join([309- self.handle_node(n) for n in nodes375+ self.handle_node(n) for n in node.nodes376 ])377 378 def handle_and(self, node):379 """16 unmodified lines396 handle not operator.397 """398 return 'not %s' % self.handle_node(node.expr)399 400+ def handle_slice(self, node):401+ """402+ Slice access.403+ """404+ if node.lower is None:405+ lower = ''406+ else:407+ lower = self.handle_node(node.lower)408+ if node.upper is None:409+ upper = ''410+ else:411+ upper = self.handle_node(node.upper)412+ assert node.flags != 'OP_DELETE', 'wtf? shouldn\'t happen'413+ return '%s[%s:%s]' % (414+ self.handle_node(node.expr),415+ lower,416+ upper417+ )418+419+ def handle_sliceobj(self, node):420+ """421+ Extended Slice access.422+ """423+ args = []424+ for n in node.nodes:425+ args.append(self.handle_node(n))426+ return '[%s]' % ':'.join(args)427+428 def translate(self):429 self.indention = 1430+ self.last_pos = 0431 lines = [432+ 'from jinja.datastructures import Undefined',433 'def generate(environment, context, write, write_var=None):',434 ' """This function was automatically generated by',435 ' the jinja python translator. do not edit."""',436 ' if write_var is None:',11 unmodified linesmodified:jinja/datastructure.py+38 added-5 removed
77 unmodified lines78 except:79 raise TypeError('%r requires environment as first argument. '80 'The rest of the arguments are forwarded to '81 'the default dict constructor.')82- initial.update(83- false=False,84- true=True,85- none=None86- )82 self._stack = [initial, {}]83 84 def pop(self):85 if len(self._stack) <= 2:23 unmodified lines109 tmp[key] = value110 return 'Context(%s)' % repr(tmp)111 112 113+class LoopContext(object):114+ """115+ Simple class that provides special loop variables.116+ Used by `Environment.iterate`.117+ """118+119+ def __init__(self, index, length):120+ self.index = 0121+ self.length = length122+ try:123+ self.length = len(seq)124+ except TypeError:125+ self.seq = list(seq)126+ self.length = len(self.seq)127+ else:128+ self.seq = seq129+130+ def revindex(self):131+ return self.length - self.index + 1132+ revindex = property(revindex)133+134+ def revindex0(self):135+ return self.length - self.index136+ revindex0 = property(revindex0)137+138+ def index0(self):139+ return self.index - 1140+ index0 = property(index0)141+142+ def even(self):143+ return self.index % 2 == 0144+ even = property(even)145+146+ def odd(self):147+ return self.index % 2 == 1148+ odd = property(odd)149+150+151 class TokenStream(object):152 """153 A token stream works like a normal generator just that154 it supports pushing tokens back to the stream.54 unmodified linesmodified:jinja/environment.py+45 added-11 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja.lexer import Lexer12 from jinja.parser import Parser13+from jinja.datastructure import LoopContext, Undefined13-from jinja.exceptions import TagNotFound, FilterNotFound14+from jinja.exceptions import FilterNotFound15 from jinja.defaults import DEFAULT_FILTERS16 17 18 class Environment(object):10 unmodified lines29 comment_end_string='#}',30 template_charset='utf-8',31 charset='utf-8',32 loader=None,32- tags=None,33 filters=None):34 35 # lexer / parser information36 self.block_start_string = block_start_string16 unmodified lines53 """Function that creates a new parser and parses the source."""54 parser = Parser(self, source)55 return parser.parse_page()56 57- def get_filter(self, name):58- """59- Return the filter for a given name. Raise a `FilterNotFound` exception60- if the requested filter is not registered.61- """62- if name not in self._filters:63- raise FilterNotFound(name)64- return self._filters[name]65-57 def to_unicode(self, value):58 """59 Convert a value to unicode with the rules defined on the environment.60 """3 unmodified lines64 try:65 return unicode(value)66 except UnicodeError:67 return str(value).decode(self.charset, 'ignore')68+69+ def iterate(self, seq):70+ """71+ Helper function used by the python translator runtime code to72+ iterate over a sequence.73+ """74+ try:75+ length = len(seq)76+ except TypeError:77+ seq = list(seq)78+ length = len(seq)79+ loop_data = LoopContext(0, length)80+ for item in seq:81+ loop_data.index += 182+ yield loop_data, item83+84+ def prepare_filter(self, name, *args):85+ """86+ Prepare a filter.87+ """88+ try:89+ return self.filters[name](*args)90+ except KeyError:91+ raise FilterNotFound(name)92+93+ def apply_filters(self, value, context, filters):94+ """95+ Apply a list of filters on the variable.96+ """97+ for f in filters:98+ value = f(self, context, value)99+ return value100+101+ def get_attribute(self, obj, name):102+ """103+ Get the attribute name from obj.104+ """105+ try:106+ return getattr(obj, name)107+ except AttributeError:108+ return obj[name]109+ except:110+ return Undefinedmodified:jinja/exceptions.py+5 added-17 removed
12 unmodified lines13 class TemplateError(RuntimeError):14 pass15 16 17-class TagNotFound(KeyError, TemplateError):18- """19- The parser looked for a specific tag in the tag library but was unable to find20- one.21- """22-23- def __init__(self, tagname):24- super(TagNotFound, self).__init__('The tag %r does not exist.' % tagname)25- self.tagname = tagname26-27-17 class FilterNotFound(KeyError, TemplateError):18 """30- The template engine looked for a filter but was unable to find it.19+ Raised if a filter does not exist.20 """21 33- def __init__(self, filtername):34- super(FilterNotFound, self).__init__('The filter %r does not exist.' % filtername)35- self.filtername = filtername22+ def __init__(self, message):23+ KeyError.__init__(self, message)24 25 26 class TemplateSyntaxError(SyntaxError, TemplateError):27 """28 Raised to tell the user that there is a problem with the template.29 """30 31 def __init__(self, message, pos):44- super(TemplateSyntaxError, self).__init__(message)32+ SyntaxError.__init__(self, message)33 self.pos = pos34 35 36 class TemplateRuntimeError(TemplateError):2 unmodified lines39 rendering.40 """41 42 def __init__(self, message, pos):55- super(TemplateRuntimeError, self).__init__(message)43+ RuntimeError.__init__(self, message)44 self.pos = posmodified:jinja/filters.py-7 removed
34 unmodified lines35 """36 if count is None:37 return s.replace(old, new)38 return s.replace(old, new, count)39-do_replace = stringfilter(do_replace)39 40 41 def do_upper(s):42 """1 unmodified line44 45 Return a copy of s converted to uppercase.46 """47 return s.upper()49-do_upper = stringfilter(do_upper)48 49 50 def do_lower(s):51 """1 unmodified line53 54 Return a copy of s converted to lowercase.55 """56 return s.lower()59-do_lower = stringfilter(do_lower)57 58 59 def do_escape(s, attribute=False):60 """5 unmodified lines66 s = s.replace("&", "&").replace("<", "<").replace(">", ">")67 if attribute:68 s = s.replace('"', """)69 return s73-do_escape = stringfilter(do_escape)70 71 72 def do_addslashes(s):73 """1 unmodified line75 76 Adds slashes to s.77 """78 return s.encode('utf-8').encode('string-escape').decode('utf-8')83-do_addslashes = stringfilter(do_addslashes)79 80 81 def do_capitalize(s):82 """2 unmodified lines85 Return a copy of the string s with only its first character86 capitalized.87 """88 return s.capitalize()94-do_capitalize = stringfilter(do_capitalize)89 90 91 def do_title(s):92 """2 unmodified lines95 Return a titlecased version of s, i.e. words start with uppercase96 characters, all remaining cased characters have lowercase.97 """98 return s.title()105-do_title = stringfilter(do_title)99 100 101 def do_default(default_value=u''):102 """94 unmodified linesmodified:jinja/lexer.py+1 added-1 removed
20 unmodified lines21 '+', '-', '*', '/', '%',22 # braces and parenthesis23 '[', ']', '(', ')', '{', '}',24 # attribute access and comparison / logical operators25- '.', ',', '|', '==', '<', '>', '<=', '>=', '!=',25+ '.', ':', ',', '|', '==', '<', '>', '<=', '>=', '!=', '=',26 ur'or\b', ur'and\b', ur'not\b'27 ]))28 29 162 unmodified lines