added support for unicode identifiers
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 b9e7875 · Browse files · 4 files·+74 added−52 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+74 added−52 removed
- other:+74 added−52 removed
Provenance
- Commit
b536548- Tree
72f5c01- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
b9e7875
4 files changed+74 added−52 removed
modified:docs/api.rst+6 added-23 removed
66 unmodified lines67 .. attribute:: filters68 69 A dict of filters for this environment. As long as no template was70 loaded it's safe to add new filters or remove old. For custom filters71- see :ref:`writing-filters`. For valid filter names have a look at72- :ref:`identifier-naming`.71+ see :ref:`writing-filters`. Unlike regular identifiers filters and72+ tests may contain dots to group functions with similar functionality.73+ For example `to.unicode` is a valid name for a filter.74 75 .. attribute:: tests76 77 A dict of test functions for this environment. As long as no78 template was loaded it's safe to modify this dict. For custom tests78- see :ref:`writing-tests`. For valid test names have a look at79- :ref:`identifier-naming`.79+ see :ref:`writing-tests`. Unlike regular identifiers filters and80+ tests may contain dots to group functions with similar functionality.81+ For example `check.positive` is a valid name for a test.82 83 .. attribute:: globals84 85 A dict of global variables. These variables are always available86 in a template and (if the optimizer is enabled) may not be87 overridden by templates. As long as no template was loaded it's safe88 to modify this dict. For more details see :ref:`global-namespace`.87- For valid object names have a look at :ref:`identifier-naming`.89 90 .. automethod:: overlay([options])91 92 21 unmodified lines114 .. autoclass:: jinja2.environment.TemplateStream115 :members: disable_buffering, enable_buffering116 117 117-.. _identifier-naming:118-119-Notes on Identifiers120-~~~~~~~~~~~~~~~~~~~~121-122-Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to123-match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters124-are currently not allowed. This limitation will probably go away as soon as125-unicode identifiers are fully specified for Python 3.126-127-Filters and tests are looked up in separate namespaces and have slightly128-modified identifier syntax. Filters and tests may contain dots to group129-filters and tests by topic. For example it's perfectly valid to add a130-function into the filter dict and call it `to.unicode`. The regular131-expression for filter and test identifiers is132-``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.133-134-118 Undefined Types119 ---------------120 121 These classes can be used as undefined types. The :class:`Environment`234 unmodified linesmodified:jinja2/compiler.py+48 added-17 removed
6 unmodified lines7 8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10 """11+import string12 from time import time13 from copy import copy14 from random import randrange15 from keyword import iskeyword16 from cStringIO import StringIO16-from itertools import chain17+from itertools import chain, takewhile18 from jinja2 import nodes19 from jinja2.visitor import NodeVisitor, NodeTransformer20 from jinja2.exceptions import TemplateAssertionError21 from jinja2.utils import Markup, concat16 unmodified lines38 have_condexpr = False39 else:40 have_condexpr = True41 42+_safe_ident_chars = set(string.letters + '0123456789')43 44+45 def generate(node, environment, name, filename, stream=None):46 """Generate the python source for a node tree."""47 if not isinstance(node, nodes.Template):48 raise TypeError('Can\'t compile non template nodes')2 unmodified lines51 if stream is None:52 return generator.stream.getvalue()53 54 55+def mask_identifier(ident):56+ """Mask an identifier properly for python source code."""57+ rv = ['l_']58+ for char in ident:59+ if char in _safe_ident_chars:60+ rv.append(char)61+ else:62+ rv.append('_%x_' % ord(char))63+ return str(''.join(rv))64+65+66+def unmask_identifier(ident):67+ """Unmask an identifier."""68+ if not ident.startswith('l_'):69+ return ident70+ rv = []71+ i = iter(ident[2:])72+ for c in i:73+ if c == '_':74+ c = unichr(int(concat(takewhile(lambda c: c != '_', i)), 16))75+ rv.append(c)76+ return ''.join(rv)77+78+79 def has_safe_repr(value):80 """Does the node have a safe representation?"""81 if value is None or value is NotImplemented or value is Ellipsis:82 return True413 unmodified lines496 497 def pull_locals(self, frame):498 """Pull all the references identifiers into the local scope."""499 for name in frame.identifiers.undeclared:473- self.writeline('l_%s = context.resolve(%r)' % (name, name))500+ self.writeline('%s = context.resolve(%r)' % (mask_identifier(name),501+ name))502 503 def pull_dependencies(self, nodes):504 """Pull all the dependencies."""505 visitor = DependencyFinderVisitor()17 unmodified lines523 # identifier is in use afterwards.524 aliases = {}525 for name in frame.identifiers.find_shadowed():526 aliases[name] = ident = self.temporary_identifier()499- self.writeline('%s = l_%s' % (ident, name))527+ self.writeline('%s = %s' % (ident, mask_identifier(name)))528 return aliases529 530 def function_scoping(self, node, frame, children=None):531 """In Jinja a few statements require the help of anonymous40 unmodified lines572 573 func_frame.accesses_kwargs = False574 func_frame.accesses_varargs = False575 func_frame.accesses_caller = False548- func_frame.arguments = args = ['l_' + x.name for x in node.args]576+ func_frame.arguments = args = [mask_identifier(x.name)577+ for x in node.args]578 579 undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))580 581 if 'caller' in undeclared:192 unmodified lines774 self.outdent()775 776 def visit_Import(self, node, frame):777 """Visit regular imports."""749- self.writeline('l_%s = ' % node.target, node)778+ self.writeline(mask_identifier(node.target) + ' = ', node)779 if frame.toplevel:780 self.write('context.vars[%r] = ' % node.target)781 self.write('environment.get_template(')782 self.visit(node.template, frame)19 unmodified lines802 if isinstance(name, tuple):803 name, alias = name804 else:805 alias = name777- self.writeline('l_%s = getattr(included_template, '778- '%r, missing)' % (alias, name))779- self.writeline('if l_%s is missing:' % alias)806+ self.writeline('%s = getattr(included_template, '807+ '%r, missing)' % (mask_identifier(alias), name))808+ self.writeline('if %s is missing:' % mask_identifier(alias))809 self.indent()781- self.writeline('l_%s = environment.undefined(%r %% '810+ self.writeline('%s = environment.undefined(%r %% '811 'included_template.name, '812 'name=included_template.name)' %784- (alias, 'the template %r does not export '785- 'the requested name ' + repr(name)))813+ (mask_identifier(alias), 'the template %r does '814+ 'not export the requested name ' + repr(name)))815 self.outdent()816 if frame.toplevel:788- self.writeline('context.vars[%r] = l_%s' % (alias, alias))817+ self.writeline('context.vars[%r] = %s' %818+ (alias, mask_identifier(alias)))819 if not alias.startswith('__'):820 self.writeline('context.exported_vars.discard(%r)' % alias)821 822 def visit_For(self, node, frame):65 unmodified lines888 self.outdent()889 890 # reset the aliases if there are any.891 for name, alias in aliases.iteritems():862- self.writeline('l_%s = %s' % (name, alias))892+ self.writeline('%s = %s' % (mask_identifier(name), alias))893 894 def visit_If(self, node, frame):895 if_frame = frame.soft()896 self.writeline('if ', node)29 unmodified lines926 self.writeline('context.vars[%r] = ' % node.name)927 arg_tuple = ', '.join(repr(x.name) for x in node.args)928 if len(node.args) == 1:929 arg_tuple += ','900- self.write('l_%s = Macro(environment, macro, %r, (%s), (' %901- (node.name, node.name, arg_tuple))930+ self.write('%s = Macro(environment, macro, %r, (%s), (' %931+ (mask_identifier(node.name), node.name, arg_tuple))932 for arg in node.defaults:933 self.visit(arg, macro_frame)934 self.write(', ')935 self.write('), %s, %s, %s)' % (175 unmodified lines1111 1112 # make sure toplevel assignments are added to the context.1113 if frame.toplevel:1114 for name in assignment_frame.assigned_names:1085- self.writeline('context.vars[%r] = l_%s' % (name, name))1115+ self.writeline('context.vars[%r] = %s' %1116+ (name, mask_identifier(name)))1117 if not name.startswith('__'):1118 self.writeline('context.exported_vars.add(%r)' % name)1119 1120 def visit_Name(self, node, frame):1121 if node.ctx == 'store' and frame.toplevel:1122 frame.assigned_names.add(node.name)1092- self.write('l_' + node.name)1123+ self.write(mask_identifier(node.name))1124 1125 def visit_MarkSafe(self, node, frame):1126 self.write('Markup(')1127 self.visit(node.expr, frame)184 unmodified linesmodified:jinja2/debug.py+8 added-1 removed
10 unmodified lines11 :license: BSD.12 """13 import sys14 from types import CodeType15+from jinja2.compiler import unmask_identifier16 17 18 def translate_exception(exc_info):19 """If passed an exc_info it will automatically rewrite the exceptions46 unmodified lines66 else:67 locals = {}68 for name, value in real_locals.iteritems():69 if name.startswith('l_'):69- locals[name[2:]] = value70+ try:71+ locals[str(unmask_identifier(name))] = value72+ except UnicodeError:73+ # bummer. someone actually used an unicode identifier.74+ # there is no way this can be added back into the python75+ # layer with python < 3. we have to ignore it...76+ pass77 78 # if there is a local called __jinja_exception__, we get79 # rid of it to not break the debug functionality.80 locals.pop('__jinja_exception__', None)118 unmodified linesmodified:jinja2/lexer.py+12 added-11 removed
29 unmodified lines30 whitespace_re = re.compile(r'\s+(?um)')31 string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"32 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')33 integer_re = re.compile(r'\d+')34-name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')34+name_re = re.compile(r'\b[^\W\d]\w*\b(?u)')35 float_re = re.compile(r'\d+\.\d+')36 37 # bind operators to token types38 operators = {48 unmodified lines87 'U': 888 }89 90 91+def _trystr(s):92+ try:93+ return str(s)94+ except UnicodeError:95+ return s96+97+98 def unescape_string(lineno, filename, s):99 r"""Unescape a string. Supported escapes:100 \a, \n, \r\, \f, \v, \\, \", \', \0101 102 \x00, \u0000, \U00000000, \N{...}103 """104 try:98- return s.encode('ascii', 'backslashreplace').decode('unicode-escape')105+ return _trystr(s.encode('ascii', 'backslashreplace')106+ .decode('unicode-escape'))107 except UnicodeError, e:108 msg = str(e).split(':')[-1].strip()109 raise TemplateSyntaxError(msg, lineno, filename)110 305 unmodified lines416 # we are not interested in those tokens in the parser417 elif token in ('raw_begin', 'raw_end'):418 continue419 elif token == 'data':412- try:413- value = str(value)420+ value = _trystr(value)414- except UnicodeError:415- pass421 elif token == 'keyword':422 token = value423 elif token == 'name':419- value = str(value)424+ value = _trystr(value)425 elif token == 'string':426 value = unescape_string(lineno, filename, value[1:-1])422- try:423- value = str(value)424- except UnicodeError:425- pass427 elif token == 'integer':428 value = int(value)429 elif token == 'float':430 value = float(value)142 unmodified lines