Skip to content
Myr

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

4 files+74 added−52 removed

modified:docs/api.rst+6 added-23 removed
66 unmodified lines
67 .. attribute:: filters6869 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.7475 .. attribute:: tests7677 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.8283 .. attribute:: globals8485 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`.8990 .. automethod:: overlay([options])9192
21 unmodified lines
114.. autoclass:: jinja2.environment.TemplateStream115 :members: disable_buffering, enable_buffering116117117.. _identifier-naming:118119Notes on Identifiers120~~~~~~~~~~~~~~~~~~~~121122Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to123match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters124are currently not allowed. This limitation will probably go away as soon as125unicode identifiers are fully specified for Python 3.126127Filters and tests are looked up in separate namespaces and have slightly128modified identifier syntax. Filters and tests may contain dots to group129filters and tests by topic. For example it's perfectly valid to add a130function into the filter dict and call it `to.unicode`. The regular131expression for filter and test identifiers is132``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.133134118Undefined Types119---------------120121These classes can be used as undefined types. The :class:`Environment`
234 unmodified lines
modified:jinja2/compiler.py+48 added-17 removed
6 unmodified lines
78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11import string12from time import time13from copy import copy14from random import randrange15from keyword import iskeyword16from cStringIO import StringIO16from itertools import chain17from itertools import chain, takewhile18from jinja2 import nodes19from jinja2.visitor import NodeVisitor, NodeTransformer20from jinja2.exceptions import TemplateAssertionError21from jinja2.utils import Markup, concat
16 unmodified lines
38 have_condexpr = False39else:40 have_condexpr = True4142_safe_ident_chars = set(string.letters + '0123456789')434445def 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 lines
51 if stream is None:52 return generator.stream.getvalue()535455def 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))646566def 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)777879def 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 True
413 unmodified lines
496497 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))502503 def pull_dependencies(self, nodes):504 """Pull all the dependencies."""505 visitor = DependencyFinderVisitor()
17 unmodified lines
523 # 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 aliases529530 def function_scoping(self, node, frame, children=None):531 """In Jinja a few statements require the help of anonymous
40 unmodified lines
572573 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]578579 undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))580581 if 'caller' in undeclared:
192 unmodified lines
774 self.outdent()775776 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 lines
802 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)821822 def visit_For(self, node, frame):
65 unmodified lines
888 self.outdent()889890 # 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))893894 def visit_If(self, node, frame):895 if_frame = frame.soft()896 self.writeline('if ', node)
29 unmodified lines
926 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 lines
11111112 # 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)11191120 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))11241125 def visit_MarkSafe(self, node, frame):1126 self.write('Markup(')1127 self.visit(node.expr, frame)
184 unmodified lines
modified:jinja2/debug.py+8 added-1 removed
10 unmodified lines
11 :license: BSD.12"""13import sys14from types import CodeType15from jinja2.compiler import unmask_identifier161718def translate_exception(exc_info):19 """If passed an exc_info it will automatically rewrite the exceptions
46 unmodified lines
66 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 pass7778 # 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 lines
modified:jinja2/lexer.py+12 added-11 removed
29 unmodified lines
30whitespace_re = re.compile(r'\s+(?um)')31string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"32 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')33integer_re = re.compile(r'\d+')34name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')34name_re = re.compile(r'\b[^\W\d]\w*\b(?u)')35float_re = re.compile(r'\d+\.\d+')3637# bind operators to token types38operators = {
48 unmodified lines
87 'U': 888}899091def _trystr(s):92 try:93 return str(s)94 except UnicodeError:95 return s969798def unescape_string(lineno, filename, s):99 r"""Unescape a string. Supported escapes:100 \a, \n, \r\, \f, \v, \\, \", \', \0101102 \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 lines
416 # 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