Backed out changeset 6afb554797b6, which added unicode identifier support. This doesn't work in reality under Python 2.6 properly.
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 b536548 · Browse files · 4 files·+52 added−74 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+52 added−74 removed
- other:+52 added−74 removed
Provenance
- Commit
d1ff858- Tree
d5d79bd- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
b536548
4 files changed+52 added−74 removed
modified:docs/api.rst+23 added-6 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`. 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.71+ see :ref:`writing-filters`. For valid filter names have a look at72+ :ref:`identifier-naming`.73 74 .. attribute:: tests75 76 A dict of test functions for this environment. As long as no77 template was loaded it's safe to modify this dict. For custom tests79- 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.78+ see :ref:`writing-tests`. For valid test names have a look at79+ :ref:`identifier-naming`.80 81 .. attribute:: globals82 83 A dict of global variables. These variables are always available84 in a template and (if the optimizer is enabled) may not be85 overridden by templates. As long as no template was loaded it's safe86 to modify this dict. For more details see :ref:`global-namespace`.87+ For valid object names have a look at :ref:`identifier-naming`.88 89 .. automethod:: overlay([options])90 91 21 unmodified lines113 .. autoclass:: jinja2.environment.TemplateStream114 :members: disable_buffering, enable_buffering115 116 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+135 Undefined Types136 ---------------137 138 These classes can be used as undefined types. The :class:`Environment`234 unmodified linesmodified:jinja2/compiler.py+17 added-48 removed
6 unmodified lines7 8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10 """11-import string11 from time import time12 from copy import copy13 from random import randrange14 from keyword import iskeyword15 from cStringIO import StringIO17-from itertools import chain, takewhile16+from itertools import chain17 from jinja2 import nodes18 from jinja2.visitor import NodeVisitor, NodeTransformer19 from jinja2.exceptions import TemplateAssertionError20 from jinja2.utils import Markup, concat16 unmodified lines37 have_condexpr = False38 else:39 have_condexpr = True40 42-_safe_ident_chars = set(string.letters + '0123456789')41 44-42 def generate(node, environment, name, filename, stream=None):43 """Generate the python source for a node tree."""44 if not isinstance(node, nodes.Template):45 raise TypeError('Can\'t compile non template nodes')2 unmodified lines48 if stream is None:49 return generator.stream.getvalue()50 51 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-52 def has_safe_repr(value):53 """Does the node have a safe representation?"""54 if value is None or value is NotImplemented or value is Ellipsis:55 return True413 unmodified lines469 470 def pull_locals(self, frame):471 """Pull all the references identifiers into the local scope."""472 for name in frame.identifiers.undeclared:500- self.writeline('%s = context.resolve(%r)' % (mask_identifier(name),501- name))473+ self.writeline('l_%s = context.resolve(%r)' % (name, name))474 475 def pull_dependencies(self, nodes):476 """Pull all the dependencies."""477 visitor = DependencyFinderVisitor()17 unmodified lines495 # identifier is in use afterwards.496 aliases = {}497 for name in frame.identifiers.find_shadowed():498 aliases[name] = ident = self.temporary_identifier()527- self.writeline('%s = %s' % (ident, mask_identifier(name)))499+ self.writeline('%s = l_%s' % (ident, name))500 return aliases501 502 def function_scoping(self, node, frame, children=None):503 """In Jinja a few statements require the help of anonymous40 unmodified lines544 545 func_frame.accesses_kwargs = False546 func_frame.accesses_varargs = False547 func_frame.accesses_caller = False576- func_frame.arguments = args = [mask_identifier(x.name)577- for x in node.args]548+ func_frame.arguments = args = ['l_' + x.name for x in node.args]549 550 undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))551 552 if 'caller' in undeclared:192 unmodified lines745 self.outdent()746 747 def visit_Import(self, node, frame):748 """Visit regular imports."""778- self.writeline(mask_identifier(node.target) + ' = ', node)749+ self.writeline('l_%s = ' % node.target, node)750 if frame.toplevel:751 self.write('context.vars[%r] = ' % node.target)752 self.write('environment.get_template(')753 self.visit(node.template, frame)19 unmodified lines773 if isinstance(name, tuple):774 name, alias = name775 else:776 alias = name806- self.writeline('%s = getattr(included_template, '807- '%r, missing)' % (mask_identifier(alias), name))808- self.writeline('if %s is missing:' % mask_identifier(alias))777+ self.writeline('l_%s = getattr(included_template, '778+ '%r, missing)' % (alias, name))779+ self.writeline('if l_%s is missing:' % alias)780 self.indent()810- self.writeline('%s = environment.undefined(%r %% '781+ self.writeline('l_%s = environment.undefined(%r %% '782 'included_template.name, '783 'name=included_template.name)' %813- (mask_identifier(alias), 'the template %r does '814- 'not export the requested name ' + repr(name)))784+ (alias, 'the template %r does not export '785+ 'the requested name ' + repr(name)))786 self.outdent()787 if frame.toplevel:817- self.writeline('context.vars[%r] = %s' %818- (alias, mask_identifier(alias)))788+ self.writeline('context.vars[%r] = l_%s' % (alias, alias))789 if not alias.startswith('__'):790 self.writeline('context.exported_vars.discard(%r)' % alias)791 792 def visit_For(self, node, frame):65 unmodified lines858 self.outdent()859 860 # reset the aliases if there are any.861 for name, alias in aliases.iteritems():892- self.writeline('%s = %s' % (mask_identifier(name), alias))862+ self.writeline('l_%s = %s' % (name, alias))863 864 def visit_If(self, node, frame):865 if_frame = frame.soft()866 self.writeline('if ', node)29 unmodified lines896 self.writeline('context.vars[%r] = ' % node.name)897 arg_tuple = ', '.join(repr(x.name) for x in node.args)898 if len(node.args) == 1:899 arg_tuple += ','930- self.write('%s = Macro(environment, macro, %r, (%s), (' %931- (mask_identifier(node.name), node.name, arg_tuple))900+ self.write('l_%s = Macro(environment, macro, %r, (%s), (' %901+ (node.name, node.name, arg_tuple))902 for arg in node.defaults:903 self.visit(arg, macro_frame)904 self.write(', ')905 self.write('), %s, %s, %s)' % (175 unmodified lines1081 1082 # make sure toplevel assignments are added to the context.1083 if frame.toplevel:1084 for name in assignment_frame.assigned_names:1115- self.writeline('context.vars[%r] = %s' %1116- (name, mask_identifier(name)))1085+ self.writeline('context.vars[%r] = l_%s' % (name, name))1086 if not name.startswith('__'):1087 self.writeline('context.exported_vars.add(%r)' % name)1088 1089 def visit_Name(self, node, frame):1090 if node.ctx == 'store' and frame.toplevel:1091 frame.assigned_names.add(node.name)1123- self.write(mask_identifier(node.name))1092+ self.write('l_' + node.name)1093 1094 def visit_MarkSafe(self, node, frame):1095 self.write('Markup(')1096 self.visit(node.expr, frame)184 unmodified linesmodified:jinja2/debug.py+1 added-8 removed
10 unmodified lines11 :license: BSD.12 """13 import sys14 from types import CodeType15-from jinja2.compiler import unmask_identifier15 16 17 def translate_exception(exc_info):18 """If passed an exc_info it will automatically rewrite the exceptions46 unmodified lines65 else:66 locals = {}67 for name, value in real_locals.iteritems():68 if name.startswith('l_'):70- 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- pass69+ locals[name[2:]] = value70 71 # if there is a local called __jinja_exception__, we get72 # rid of it to not break the debug functionality.73 locals.pop('__jinja_exception__', None)118 unmodified linesmodified:jinja2/lexer.py+11 added-12 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[^\W\d]\w*\b(?u)')34+name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')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-91 def unescape_string(lineno, filename, s):92 r"""Unescape a string. Supported escapes:93 \a, \n, \r\, \f, \v, \\, \", \', \094 95 \x00, \u0000, \U00000000, \N{...}96 """97 try:105- return _trystr(s.encode('ascii', 'backslashreplace')106- .decode('unicode-escape'))98+ return s.encode('ascii', 'backslashreplace').decode('unicode-escape')99 except UnicodeError, e:100 msg = str(e).split(':')[-1].strip()101 raise TemplateSyntaxError(msg, lineno, filename)102 305 unmodified lines408 # we are not interested in those tokens in the parser409 elif token in ('raw_begin', 'raw_end'):410 continue411 elif token == 'data':412+ try:420- value = _trystr(value)413+ value = str(value)414+ except UnicodeError:415+ pass416 elif token == 'keyword':417 token = value418 elif token == 'name':424- value = _trystr(value)419+ value = str(value)420 elif token == 'string':421 value = unescape_string(lineno, filename, value[1:-1])422+ try:423+ value = str(value)424+ except UnicodeError:425+ pass426 elif token == 'integer':427 value = int(value)428 elif token == 'float':429 value = float(value)142 unmodified lines