Skip to content
Myr

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

4 files+52 added−74 removed

modified:docs/api.rst+23 added-6 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`. 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`.7374 .. attribute:: tests7576 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`.8081 .. attribute:: globals8283 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`.8889 .. automethod:: overlay([options])9091
21 unmodified lines
113.. autoclass:: jinja2.environment.TemplateStream114 :members: disable_buffering, enable_buffering115116117.. _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_]*)*```.133134135Undefined Types136---------------137138These classes can be used as undefined types. The :class:`Environment`
234 unmodified lines
modified:jinja2/compiler.py+17 added-48 removed
6 unmodified lines
78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11import string11from time import time12from copy import copy13from random import randrange14from keyword import iskeyword15from cStringIO import StringIO17from itertools import chain, takewhile16from itertools import chain17from jinja2 import nodes18from jinja2.visitor import NodeVisitor, NodeTransformer19from jinja2.exceptions import TemplateAssertionError20from jinja2.utils import Markup, concat
16 unmodified lines
37 have_condexpr = False38else:39 have_condexpr = True4042_safe_ident_chars = set(string.letters + '0123456789')414442def 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 lines
48 if stream is None:49 return generator.stream.getvalue()505155def 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)777852def 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 True
413 unmodified lines
469470 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))474475 def pull_dependencies(self, nodes):476 """Pull all the dependencies."""477 visitor = DependencyFinderVisitor()
17 unmodified lines
495 # 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 aliases501502 def function_scoping(self, node, frame, children=None):503 """In Jinja a few statements require the help of anonymous
40 unmodified lines
544545 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]549550 undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))551552 if 'caller' in undeclared:
192 unmodified lines
745 self.outdent()746747 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 lines
773 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)791792 def visit_For(self, node, frame):
65 unmodified lines
858 self.outdent()859860 # 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))863864 def visit_If(self, node, frame):865 if_frame = frame.soft()866 self.writeline('if ', node)
29 unmodified lines
896 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 lines
10811082 # 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)10881089 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)10931094 def visit_MarkSafe(self, node, frame):1095 self.write('Markup(')1096 self.visit(node.expr, frame)
184 unmodified lines
modified:jinja2/debug.py+1 added-8 removed
10 unmodified lines
11 :license: BSD.12"""13import sys14from types import CodeType15from jinja2.compiler import unmask_identifier151617def translate_exception(exc_info):18 """If passed an exc_info it will automatically rewrite the exceptions
46 unmodified lines
65 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:]] = value7071 # 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 lines
modified:jinja2/lexer.py+11 added-12 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[^\W\d]\w*\b(?u)')34name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')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 s969791def unescape_string(lineno, filename, s):92 r"""Unescape a string. Supported escapes:93 \a, \n, \r\, \f, \v, \\, \", \', \09495 \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 lines
408 # 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