Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.
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 a9d5922 · Browse files · 10 files·+338 added−76 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+338 added−76 removed
- other:+338 added−76 removed
Provenance
- Commit
9a0078d- Tree
369b35d- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
a9d5922
10 files changed+338 added−76 removed
modified:jinja2/compiler.py+9 added-7 removed
6 unmodified lines7 8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10 """11-from copy import copy12-from keyword import iskeyword11 from cStringIO import StringIO12 from itertools import chain13 from jinja2 import nodes14 from jinja2.visitor import NodeVisitor, NodeTransformer15 from jinja2.exceptions import TemplateAssertionError18-from jinja2.utils import Markup, concat, escape16+from jinja2.utils import Markup, concat, escape, is_python_keyword17 18 19 operators = {20 'eq': '==',140 unmodified lines161 self.buffer = parent.buffer162 163 def copy(self):164 """Create a copy of the current one."""167- rv = copy(self)168- rv.identifiers = copy(self.identifiers)165+ rv = object.__new__(self.__class__)166+ rv.__dict__.update(self.__dict__)167+ rv.identifiers = object.__new__(self.identifiers.__class__)168+ rv.identifiers.__dict__.update(self.identifiers.__dict__)169 return rv170 171 def inspect(self, nodes, hard_scope=False):172 """Walk the node and check for identifiers. If the scope is hard (eg:12 unmodified lines185 """Return a soft frame. A soft frame may not be modified as186 standalone thing as it shares the resources with the frame it187 was created of, but it's not a rootlevel frame any longer.188 """189- rv = copy(self)189+ rv = self.copy()190 rv.rootlevel = False191 return rv192 193+ __copy__ = copy194 195+196 class VisitorExit(RuntimeError):197 """Exception used by the `UndeclaredNameVisitor` to signal a stop."""198 199 250 unmodified lines450 # if any of the given keyword arguments is a python keyword451 # we have to make sure that no invalid call is created.452 kwarg_workaround = False453 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):452- if iskeyword(kwarg):454+ if is_python_keyword(kwarg):455 kwarg_workaround = True456 break457 458 for arg in node.args:957 unmodified linesmodified:jinja2/constants.py+258 added
28 unmodified lines29 sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor30 tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices31 ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus32 viverra volutpat vulputate'''33+34+35+#: a dict of all html entities + apos36+HTML_ENTITIES = {37+ 'AElig': 198,38+ 'Aacute': 193,39+ 'Acirc': 194,40+ 'Agrave': 192,41+ 'Alpha': 913,42+ 'Aring': 197,43+ 'Atilde': 195,44+ 'Auml': 196,45+ 'Beta': 914,46+ 'Ccedil': 199,47+ 'Chi': 935,48+ 'Dagger': 8225,49+ 'Delta': 916,50+ 'ETH': 208,51+ 'Eacute': 201,52+ 'Ecirc': 202,53+ 'Egrave': 200,54+ 'Epsilon': 917,55+ 'Eta': 919,56+ 'Euml': 203,57+ 'Gamma': 915,58+ 'Iacute': 205,59+ 'Icirc': 206,60+ 'Igrave': 204,61+ 'Iota': 921,62+ 'Iuml': 207,63+ 'Kappa': 922,64+ 'Lambda': 923,65+ 'Mu': 924,66+ 'Ntilde': 209,67+ 'Nu': 925,68+ 'OElig': 338,69+ 'Oacute': 211,70+ 'Ocirc': 212,71+ 'Ograve': 210,72+ 'Omega': 937,73+ 'Omicron': 927,74+ 'Oslash': 216,75+ 'Otilde': 213,76+ 'Ouml': 214,77+ 'Phi': 934,78+ 'Pi': 928,79+ 'Prime': 8243,80+ 'Psi': 936,81+ 'Rho': 929,82+ 'Scaron': 352,83+ 'Sigma': 931,84+ 'THORN': 222,85+ 'Tau': 932,86+ 'Theta': 920,87+ 'Uacute': 218,88+ 'Ucirc': 219,89+ 'Ugrave': 217,90+ 'Upsilon': 933,91+ 'Uuml': 220,92+ 'Xi': 926,93+ 'Yacute': 221,94+ 'Yuml': 376,95+ 'Zeta': 918,96+ 'aacute': 225,97+ 'acirc': 226,98+ 'acute': 180,99+ 'aelig': 230,100+ 'agrave': 224,101+ 'alefsym': 8501,102+ 'alpha': 945,103+ 'amp': 38,104+ 'and': 8743,105+ 'ang': 8736,106+ 'apos': 39,107+ 'aring': 229,108+ 'asymp': 8776,109+ 'atilde': 227,110+ 'auml': 228,111+ 'bdquo': 8222,112+ 'beta': 946,113+ 'brvbar': 166,114+ 'bull': 8226,115+ 'cap': 8745,116+ 'ccedil': 231,117+ 'cedil': 184,118+ 'cent': 162,119+ 'chi': 967,120+ 'circ': 710,121+ 'clubs': 9827,122+ 'cong': 8773,123+ 'copy': 169,124+ 'crarr': 8629,125+ 'cup': 8746,126+ 'curren': 164,127+ 'dArr': 8659,128+ 'dagger': 8224,129+ 'darr': 8595,130+ 'deg': 176,131+ 'delta': 948,132+ 'diams': 9830,133+ 'divide': 247,134+ 'eacute': 233,135+ 'ecirc': 234,136+ 'egrave': 232,137+ 'empty': 8709,138+ 'emsp': 8195,139+ 'ensp': 8194,140+ 'epsilon': 949,141+ 'equiv': 8801,142+ 'eta': 951,143+ 'eth': 240,144+ 'euml': 235,145+ 'euro': 8364,146+ 'exist': 8707,147+ 'fnof': 402,148+ 'forall': 8704,149+ 'frac12': 189,150+ 'frac14': 188,151+ 'frac34': 190,152+ 'frasl': 8260,153+ 'gamma': 947,154+ 'ge': 8805,155+ 'gt': 62,156+ 'hArr': 8660,157+ 'harr': 8596,158+ 'hearts': 9829,159+ 'hellip': 8230,160+ 'iacute': 237,161+ 'icirc': 238,162+ 'iexcl': 161,163+ 'igrave': 236,164+ 'image': 8465,165+ 'infin': 8734,166+ 'int': 8747,167+ 'iota': 953,168+ 'iquest': 191,169+ 'isin': 8712,170+ 'iuml': 239,171+ 'kappa': 954,172+ 'lArr': 8656,173+ 'lambda': 955,174+ 'lang': 9001,175+ 'laquo': 171,176+ 'larr': 8592,177+ 'lceil': 8968,178+ 'ldquo': 8220,179+ 'le': 8804,180+ 'lfloor': 8970,181+ 'lowast': 8727,182+ 'loz': 9674,183+ 'lrm': 8206,184+ 'lsaquo': 8249,185+ 'lsquo': 8216,186+ 'lt': 60,187+ 'macr': 175,188+ 'mdash': 8212,189+ 'micro': 181,190+ 'middot': 183,191+ 'minus': 8722,192+ 'mu': 956,193+ 'nabla': 8711,194+ 'nbsp': 160,195+ 'ndash': 8211,196+ 'ne': 8800,197+ 'ni': 8715,198+ 'not': 172,199+ 'notin': 8713,200+ 'nsub': 8836,201+ 'ntilde': 241,202+ 'nu': 957,203+ 'oacute': 243,204+ 'ocirc': 244,205+ 'oelig': 339,206+ 'ograve': 242,207+ 'oline': 8254,208+ 'omega': 969,209+ 'omicron': 959,210+ 'oplus': 8853,211+ 'or': 8744,212+ 'ordf': 170,213+ 'ordm': 186,214+ 'oslash': 248,215+ 'otilde': 245,216+ 'otimes': 8855,217+ 'ouml': 246,218+ 'para': 182,219+ 'part': 8706,220+ 'permil': 8240,221+ 'perp': 8869,222+ 'phi': 966,223+ 'pi': 960,224+ 'piv': 982,225+ 'plusmn': 177,226+ 'pound': 163,227+ 'prime': 8242,228+ 'prod': 8719,229+ 'prop': 8733,230+ 'psi': 968,231+ 'quot': 34,232+ 'rArr': 8658,233+ 'radic': 8730,234+ 'rang': 9002,235+ 'raquo': 187,236+ 'rarr': 8594,237+ 'rceil': 8969,238+ 'rdquo': 8221,239+ 'real': 8476,240+ 'reg': 174,241+ 'rfloor': 8971,242+ 'rho': 961,243+ 'rlm': 8207,244+ 'rsaquo': 8250,245+ 'rsquo': 8217,246+ 'sbquo': 8218,247+ 'scaron': 353,248+ 'sdot': 8901,249+ 'sect': 167,250+ 'shy': 173,251+ 'sigma': 963,252+ 'sigmaf': 962,253+ 'sim': 8764,254+ 'spades': 9824,255+ 'sub': 8834,256+ 'sube': 8838,257+ 'sum': 8721,258+ 'sup': 8835,259+ 'sup1': 185,260+ 'sup2': 178,261+ 'sup3': 179,262+ 'supe': 8839,263+ 'szlig': 223,264+ 'tau': 964,265+ 'there4': 8756,266+ 'theta': 952,267+ 'thetasym': 977,268+ 'thinsp': 8201,269+ 'thorn': 254,270+ 'tilde': 732,271+ 'times': 215,272+ 'trade': 8482,273+ 'uArr': 8657,274+ 'uacute': 250,275+ 'uarr': 8593,276+ 'ucirc': 251,277+ 'ugrave': 249,278+ 'uml': 168,279+ 'upsih': 978,280+ 'upsilon': 965,281+ 'uuml': 252,282+ 'weierp': 8472,283+ 'xi': 958,284+ 'yacute': 253,285+ 'yen': 165,286+ 'yuml': 255,287+ 'zeta': 950,288+ 'zwj': 8205,289+ 'zwnj': 8204290+}modified:jinja2/debug.py+1 added-1 removed
9 unmodified lines10 :copyright: Copyright 2008 by Armin Ronacher.11 :license: BSD.12 """13 import sys14-from types import CodeType14+from jinja2.utils import CodeType15 16 17 def translate_exception(exc_info):18 """If passed an exc_info it will automatically rewrite the exceptions173 unmodified linesmodified:jinja2/environment.py+2 added-5 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import sys12 from jinja2.defaults import *13-from jinja2.lexer import Lexer, TokenStream13+from jinja2.lexer import get_lexer, TokenStream14 from jinja2.parser import Parser15 from jinja2.optimizer import optimize16 from jinja2.compiler import generate17 from jinja2.runtime import Undefined, Context262 unmodified lines280 rv.extensions.update(load_extensions(extensions))281 282 return _environment_sanity_check(rv)283 284- @property285- def lexer(self):286- """Return a fresh lexer for the environment."""287- return Lexer(self)284+ lexer = property(get_lexer, doc="The lexer for this environment.")285 286 def getitem(self, obj, argument):287 """Get an item or attribute of an object but prefer the item."""288 try:461 unmodified linesmodified:jinja2/filters.py+1 added-1 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 import math13-import textwrap13 from random import choice14 from operator import itemgetter15 from itertools import imap, groupby16 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode346 unmodified lines363 ``79`` characters. You can override this default using the first364 parameter. If you set the second parameter to `false` Jinja will not365 split words apart if they are longer than `width`.366 """367+ import textwrap368 return u'\n'.join(textwrap.wrap(s, width=width, expand_tabs=False,369 replace_whitespace=False,370 break_long_words=break_long_words))371 316 unmodified linesmodified:jinja2/lexer.py+18 added-25 removed
13 unmodified lines14 :copyright: 2007-2008 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16 """17 import re18-import unicodedata18 from operator import itemgetter19 from collections import deque20 from jinja2.exceptions import TemplateSyntaxError21 from jinja2.utils import LRUCache3 unmodified lines25 # environments with the same lexer26 _lexer_cache = LRUCache(50)27 28 # static regular expressions30-whitespace_re = re.compile(r'\s+(?um)')29+whitespace_re = re.compile(r'\s+', re.U)30 string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"32- r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')31+ r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)32 integer_re = re.compile(r'\d+')33 name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')34 float_re = re.compile(r'\d+\.\d+')35 newline_re = re.compile(r'(\r\n|\r|\n)')208 unmodified lines244 finally:245 self.next()246 247 249-class LexerMeta(type):250- """Metaclass for the lexer that caches instances for251- the same configuration in a weak value dictionary.252- """248+def get_lexer(environment):249+ """Return a lexer which is probably cached."""250+ key = (environment.block_start_string,251+ environment.block_end_string,252+ environment.variable_start_string,253+ environment.variable_end_string,254+ environment.comment_start_string,255+ environment.comment_end_string,256+ environment.line_statement_prefix,257+ environment.trim_blocks,258+ environment.newline_sequence)259+ lexer = _lexer_cache.get(key)260+ if lexer is None:261+ lexer = Lexer(environment)262+ _lexer_cache[key] = lexer263+ return lexer264 254- def __call__(cls, environment):255- key = (environment.block_start_string,256- environment.block_end_string,257- environment.variable_start_string,258- environment.variable_end_string,259- environment.comment_start_string,260- environment.comment_end_string,261- environment.line_statement_prefix,262- environment.trim_blocks,263- environment.newline_sequence)264- lexer = _lexer_cache.get(key)265- if lexer is None:266- lexer = type.__call__(cls, environment)267- _lexer_cache[key] = lexer268- return lexer265 270-266 class Lexer(object):267 """Class that implements a lexer for a given environment. Automatically268 created by the environment class, usually you don't have to do that.269 270 Note that the lexer is not automatically bound to an environment.271 Multiple environments can share the same lexer.272 """273 279- __metaclass__ = LexerMeta280-274 def __init__(self, environment):275 # shortcuts276 c = lambda x: re.compile(x, re.M | re.S)277 e = re.escape279 unmodified linesmodified:jinja2/nodes.py-25 removed
11 unmodified lines12 :copyright: 2008 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14 """15 import operator16-from copy import copy16 from itertools import chain, izip17 from collections import deque18 from jinja2.utils import Markup19 132 unmodified lines152 yield child153 for result in child.find_all(node_type):154 yield result155 157- def copy(self):158- """Return a deep copy of the node."""159- result = object.__new__(self.__class__)160- for field, value in self.iter_fields():161- if isinstance(value, Node):162- new_value = value.copy()163- elif isinstance(value, list):164- new_value = []165- for item in value:166- if isinstance(item, Node):167- item = item.copy()168- else:169- item = copy(item)170- new_value.append(item)171- else:172- new_value = copy(value)173- setattr(result, field, new_value)174- for attr in self.attributes:175- try:176- setattr(result, attr, getattr(self, attr))177- except AttributeError:178- pass179- return result180-156 def set_ctx(self, ctx):157 """Reset the context of a node and all child nodes. Per default the158 parser will all generate nodes that have a 'load' context as it's the159 most common one. This method is used in the parser to set assignment627 unmodified linesmodified:jinja2/runtime.py+7 added-2 removed
7 unmodified lines8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10 """11 import sys12-from types import FunctionType, MethodType12 from itertools import chain, imap13 from jinja2.utils import Markup, partial, soft_unicode, escape, missing, concat14 from jinja2.exceptions import UndefinedError, TemplateRuntimeError15 2 unmodified lines18 __all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',19 'TemplateRuntimeError', 'missing', 'concat', 'escape',20 'markup_join', 'unicode_join']21 23-_context_function_types = (FunctionType, MethodType)22 23+#: get the types we support for context functions. We do not use types because24+#: IronPython doesn't provide that module out of the box.25+class _C(object):26+ meth = lambda: None27+_context_function_types = (type(lambda: None), type(_C.meth))28+del _C29 30+31 def markup_join(seq):32 """Concatenation that escapes if necessary and converts to unicode."""33 buf = []34 iterator = imap(soft_unicode, seq)430 unmodified linesmodified:jinja2/sandbox.py+2 added-2 removed
11 unmodified lines12 :copyright: Copyright 2008 by Armin Ronacher.13 :license: BSD.14 """15 import operator16-from types import FunctionType, MethodType, TracebackType, CodeType, \17- FrameType, GeneratorType16 from jinja2.runtime import Undefined17 from jinja2.environment import Environment18 from jinja2.exceptions import SecurityError19+from jinja2.utils import FunctionType, MethodType, TracebackType, CodeType, \20+ FrameType, GeneratorType21 22 23 #: maximum number of items a range may produce24 MAX_RANGE = 100000226 unmodified linesmodified:jinja2/utils.py+40 added-8 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 import sys13-import string13 try:14 from thread import allocate_lock15 except ImportError:16 from dummy_thread import allocate_lock18-from htmlentitydefs import name2codepoint17 from collections import deque20-from copy import deepcopy18 from itertools import imap19 20 21 _word_split_re = re.compile(r'(\s+)')5 unmodified lines27 )28 _simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')29 _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')30 _entity_re = re.compile(r'&([^;]+);')34-_entities = name2codepoint.copy()35-_entities['apos'] = 3931+_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'32+_digits = '0123456789'33 34 # special singleton representing missing values for the runtime35 missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()36 21 unmodified lines58 concat = _concat59 del _test_gen_bug, _error60 61 62+# ironpython without stdlib doesn't have keyword63+try:64+ from keyword import iskeyword as is_python_keyword65+except ImportError:66+ _py_identifier_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9]*$')67+ def is_python_keyword(name):68+ if _py_identifier_re.search(name) is None:69+ return False70+ try:71+ exec name + " = 42"72+ except SyntaxError:73+ return False74+ return True75+76+77+# common types. These do exist in the special types module too which however78+# does not exist in IronPython out of the box.79+class _C(object):80+ def method(self): pass81+def _func():82+ yield None83+FunctionType = type(_func)84+GeneratorType = type(_func())85+MethodType = type(_C.method)86+CodeType = type(_C.method.func_code)87+try:88+ raise TypeError()89+except TypeError:90+ _tb = sys.exc_info()[2]91+ TracebackType = type(_tb)92+ FrameType = type(_tb.tb_frame)93+del _C, _tb, _func94+95+96 def contextfunction(f):97 """This decorator can be used to mark a function or method context callable.98 A context callable is passed the active :class:`Context` as first argument when99 called from the template. This is useful if a function wants to get access109 unmodified lines209 if middle.startswith('www.') or (210 '@' not in middle and211 not middle.startswith('http://') and212 len(middle) > 0 and182- middle[0] in string.letters + string.digits and (213+ middle[0] in _letters + _digits and (214 middle.endswith('.org') or215 middle.endswith('.net') or216 middle.endswith('.com')217 )):167 unmodified lines385 386 >>> Markup("Main » <em>About</em>").unescape()387 u'Main \xbb <em>About</em>'388 """389+ from jinja2.constants import HTML_ENTITIES390 def handle_match(m):391 name = m.group(1)360- if name in _entities:361- return unichr(_entities[name])392+ if name in HTML_ENTITIES:393+ return unichr(HTML_ENTITIES[name])394 try:395 if name[:2] in ('#x', '#X'):396 return unichr(int(name[2:], 16))397 elif name.startswith('#'):294 unmodified lines