Skip to content
Myr

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

10 files+338 added−76 removed

modified:jinja2/compiler.py+9 added-7 removed
6 unmodified lines
78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10"""11from copy import copy12from keyword import iskeyword11from cStringIO import StringIO12from itertools import chain13from jinja2 import nodes14from jinja2.visitor import NodeVisitor, NodeTransformer15from jinja2.exceptions import TemplateAssertionError18from jinja2.utils import Markup, concat, escape16from jinja2.utils import Markup, concat, escape, is_python_keyword171819operators = {20 'eq': '==',
140 unmodified lines
161 self.buffer = parent.buffer162163 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 rv170171 def inspect(self, nodes, hard_scope=False):172 """Walk the node and check for identifiers. If the scope is hard (eg:
12 unmodified lines
185 """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 rv192193 __copy__ = copy194195196class VisitorExit(RuntimeError):197 """Exception used by the `UndeclaredNameVisitor` to signal a stop."""198199
250 unmodified lines
450 # 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 break457458 for arg in node.args:
957 unmodified lines
modified:jinja2/constants.py+258 added
28 unmodified lines
29sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor30tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices31ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus32viverra volutpat vulputate'''333435#: a dict of all html entities + apos36HTML_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 lines
10 :copyright: Copyright 2008 by Armin Ronacher.11 :license: BSD.12"""13import sys14from types import CodeType14from jinja2.utils import CodeType151617def translate_exception(exc_info):18 """If passed an exc_info it will automatically rewrite the exceptions
173 unmodified lines
modified:jinja2/environment.py+2 added-5 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import sys12from jinja2.defaults import *13from jinja2.lexer import Lexer, TokenStream13from jinja2.lexer import get_lexer, TokenStream14from jinja2.parser import Parser15from jinja2.optimizer import optimize16from jinja2.compiler import generate17from jinja2.runtime import Undefined, Context
262 unmodified lines
280 rv.extensions.update(load_extensions(extensions))281282 return _environment_sanity_check(rv)283284 @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.")285286 def getitem(self, obj, argument):287 """Get an item or attribute of an object but prefer the item."""288 try:
461 unmodified lines
modified:jinja2/filters.py+1 added-1 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import re12import math13import textwrap13from random import choice14from operator import itemgetter15from itertools import imap, groupby16from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode
346 unmodified lines
363 ``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 lines
modified:jinja2/lexer.py+18 added-25 removed
13 unmodified lines
14 :copyright: 2007-2008 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16"""17import re18import unicodedata18from operator import itemgetter19from collections import deque20from jinja2.exceptions import TemplateSyntaxError21from jinja2.utils import LRUCache
3 unmodified lines
25# environments with the same lexer26_lexer_cache = LRUCache(50)2728# static regular expressions30whitespace_re = re.compile(r'\s+(?um)')29whitespace_re = re.compile(r'\s+', re.U)30string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"32 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')31 r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)32integer_re = re.compile(r'\d+')33name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')34float_re = re.compile(r'\d+\.\d+')35newline_re = re.compile(r'(\r\n|\r|\n)')
208 unmodified lines
244 finally:245 self.next()246247249class LexerMeta(type):250 """Metaclass for the lexer that caches instances for251 the same configuration in a weak value dictionary.252 """248def 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 lexer264254 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 lexer265270266class 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.269270 Note that the lexer is not automatically bound to an environment.271 Multiple environments can share the same lexer.272 """273279 __metaclass__ = LexerMeta280274 def __init__(self, environment):275 # shortcuts276 c = lambda x: re.compile(x, re.M | re.S)277 e = re.escape
279 unmodified lines
modified:jinja2/nodes.py-25 removed
11 unmodified lines
12 :copyright: 2008 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14"""15import operator16from copy import copy16from itertools import chain, izip17from collections import deque18from jinja2.utils import Markup19
132 unmodified lines
152 yield child153 for result in child.find_all(node_type):154 yield result155157 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 result180156 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 assignment
627 unmodified lines
modified:jinja2/runtime.py+7 added-2 removed
7 unmodified lines
8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10"""11import sys12from types import FunctionType, MethodType12from itertools import chain, imap13from jinja2.utils import Markup, partial, soft_unicode, escape, missing, concat14from jinja2.exceptions import UndefinedError, TemplateRuntimeError15
2 unmodified lines
18__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',19 'TemplateRuntimeError', 'missing', 'concat', 'escape',20 'markup_join', 'unicode_join']2123_context_function_types = (FunctionType, MethodType)2223#: get the types we support for context functions. We do not use types because24#: IronPython doesn't provide that module out of the box.25class _C(object):26 meth = lambda: None27_context_function_types = (type(lambda: None), type(_C.meth))28del _C293031def markup_join(seq):32 """Concatenation that escapes if necessary and converts to unicode."""33 buf = []34 iterator = imap(soft_unicode, seq)
430 unmodified lines
modified:jinja2/sandbox.py+2 added-2 removed
11 unmodified lines
12 :copyright: Copyright 2008 by Armin Ronacher.13 :license: BSD.14"""15import operator16from types import FunctionType, MethodType, TracebackType, CodeType, \17 FrameType, GeneratorType16from jinja2.runtime import Undefined17from jinja2.environment import Environment18from jinja2.exceptions import SecurityError19from jinja2.utils import FunctionType, MethodType, TracebackType, CodeType, \20 FrameType, GeneratorType212223#: maximum number of items a range may produce24MAX_RANGE = 100000
226 unmodified lines
modified:jinja2/utils.py+40 added-8 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import re12import sys13import string13try:14 from thread import allocate_lock15except ImportError:16 from dummy_thread import allocate_lock18from htmlentitydefs import name2codepoint17from collections import deque20from copy import deepcopy18from itertools import imap192021_word_split_re = re.compile(r'(\s+)')
5 unmodified lines
27)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'3334# special singleton representing missing values for the runtime35missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()36
21 unmodified lines
58 concat = _concat59 del _test_gen_bug, _error606162# ironpython without stdlib doesn't have keyword63try:64 from keyword import iskeyword as is_python_keyword65except 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 True757677# common types. These do exist in the special types module too which however78# does not exist in IronPython out of the box.79class _C(object):80 def method(self): pass81def _func():82 yield None83FunctionType = type(_func)84GeneratorType = type(_func())85MethodType = type(_C.method)86CodeType = type(_C.method.func_code)87try:88 raise TypeError()89except TypeError:90 _tb = sys.exc_info()[2]91 TracebackType = type(_tb)92 FrameType = type(_tb.tb_frame)93del _C, _tb, _func949596def 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 access
109 unmodified lines
209 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 lines
385386 >>> Markup("Main &raquo; <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