rename directory to jinja
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 42d4a4e · Browse files · 54 files·+13286 added−13286 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
54 files+13286 added−13286 removed
- other:+13286 added−13286 removed
Provenance
- Commit
eac9acb- Tree
fbf137f- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
42d4a4e
54 files changed+13286 added−13286 removed
added:src/jinja/__init__.py+43 added
1+# -*- coding: utf-8 -*-2+"""Jinja is a template engine written in pure Python. It provides a3+non-XML syntax that supports inline expressions and an optional4+sandboxed environment.5+"""6+from .bccache import BytecodeCache7+from .bccache import FileSystemBytecodeCache8+from .bccache import MemcachedBytecodeCache9+from .environment import Environment10+from .environment import Template11+from .exceptions import TemplateAssertionError12+from .exceptions import TemplateError13+from .exceptions import TemplateNotFound14+from .exceptions import TemplateRuntimeError15+from .exceptions import TemplatesNotFound16+from .exceptions import TemplateSyntaxError17+from .exceptions import UndefinedError18+from .filters import contextfilter19+from .filters import environmentfilter20+from .filters import evalcontextfilter21+from .loaders import BaseLoader22+from .loaders import ChoiceLoader23+from .loaders import DictLoader24+from .loaders import FileSystemLoader25+from .loaders import FunctionLoader26+from .loaders import ModuleLoader27+from .loaders import PackageLoader28+from .loaders import PrefixLoader29+from .runtime import ChainableUndefined30+from .runtime import DebugUndefined31+from .runtime import make_logging_undefined32+from .runtime import StrictUndefined33+from .runtime import Undefined34+from .utils import clear_caches35+from .utils import contextfunction36+from .utils import environmentfunction37+from .utils import escape38+from .utils import evalcontextfunction39+from .utils import is_undefined40+from .utils import Markup41+from .utils import select_autoescape42+43+__version__ = "2.11.0.dev0"added:src/jinja/_compat.py+132 added
1+# -*- coding: utf-8 -*-2+# flake8: noqa3+import marshal4+import sys5+6+PY2 = sys.version_info[0] == 27+PYPY = hasattr(sys, "pypy_translation_info")8+_identity = lambda x: x9+10+if not PY2:11+ unichr = chr12+ range_type = range13+ text_type = str14+ string_types = (str,)15+ integer_types = (int,)16+17+ iterkeys = lambda d: iter(d.keys())18+ itervalues = lambda d: iter(d.values())19+ iteritems = lambda d: iter(d.items())20+21+ import pickle22+ from io import BytesIO, StringIO23+24+ NativeStringIO = StringIO25+26+ def reraise(tp, value, tb=None):27+ if value.__traceback__ is not tb:28+ raise value.with_traceback(tb)29+ raise value30+31+ ifilter = filter32+ imap = map33+ izip = zip34+ intern = sys.intern35+36+ implements_iterator = _identity37+ implements_to_string = _identity38+ encode_filename = _identity39+40+ marshal_dump = marshal.dump41+ marshal_load = marshal.load42+43+else:44+ unichr = unichr45+ text_type = unicode46+ range_type = xrange47+ string_types = (str, unicode)48+ integer_types = (int, long)49+50+ iterkeys = lambda d: d.iterkeys()51+ itervalues = lambda d: d.itervalues()52+ iteritems = lambda d: d.iteritems()53+54+ import cPickle as pickle55+ from cStringIO import StringIO as BytesIO, StringIO56+57+ NativeStringIO = BytesIO58+59+ exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")60+61+ from itertools import imap, izip, ifilter62+63+ intern = intern64+65+ def implements_iterator(cls):66+ cls.next = cls.__next__67+ del cls.__next__68+ return cls69+70+ def implements_to_string(cls):71+ cls.__unicode__ = cls.__str__72+ cls.__str__ = lambda x: x.__unicode__().encode("utf-8")73+ return cls74+75+ def encode_filename(filename):76+ if isinstance(filename, unicode):77+ return filename.encode("utf-8")78+ return filename79+80+ def marshal_dump(code, f):81+ if isinstance(f, file):82+ marshal.dump(code, f)83+ else:84+ f.write(marshal.dumps(code))85+86+ def marshal_load(f):87+ if isinstance(f, file):88+ return marshal.load(f)89+ return marshal.loads(f.read())90+91+92+def with_metaclass(meta, *bases):93+ """Create a base class with a metaclass."""94+ # This requires a bit of explanation: the basic idea is to make a95+ # dummy metaclass for one level of class instantiation that replaces96+ # itself with the actual metaclass.97+ class metaclass(type):98+ def __new__(cls, name, this_bases, d):99+ return meta(name, bases, d)100+101+ return type.__new__(metaclass, "temporary_class", (), {})102+103+104+try:105+ from urllib.parse import quote_from_bytes as url_quote106+except ImportError:107+ from urllib import quote as url_quote108+109+110+try:111+ from collections import abc112+except ImportError:113+ import collections as abc114+115+116+try:117+ from os import fspath118+except ImportError:119+ try:120+ from pathlib import PurePath121+ except ImportError:122+ PurePath = None123+124+ def fspath(path):125+ if hasattr(path, "__fspath__"):126+ return path.__fspath__()127+128+ # Python 3.5 doesn't have __fspath__ yet, use str.129+ if PurePath is not None and isinstance(path, PurePath):130+ return str(path)131+132+ return pathadded:src/jinja/_identifier.py+6 added
1+import re2+3+# generated by scripts/generate_identifier_pattern.py4+pattern = re.compile(5+ r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఃా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑅳𑄴𑆀-𑆂𑆳-𑇊𑇀-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B9506+)added:src/jinja/asyncfilters.py+159 added
1+from functools import wraps2+3+from . import filters4+from .asyncsupport import auto_aiter5+from .asyncsupport import auto_await6+7+8+async def auto_to_seq(value):9+ seq = []10+ if hasattr(value, "__aiter__"):11+ async for item in value:12+ seq.append(item)13+ else:14+ for item in value:15+ seq.append(item)16+ return seq17+18+19+async def async_select_or_reject(args, kwargs, modfunc, lookup_attr):20+ seq, func = filters.prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)21+ if seq:22+ async for item in auto_aiter(seq):23+ if func(item):24+ yield item25+26+27+def dualfilter(normal_filter, async_filter):28+ wrap_evalctx = False29+ if getattr(normal_filter, "environmentfilter", False):30+31+ def is_async(args):32+ return args[0].is_async33+34+ wrap_evalctx = False35+ else:36+ if not getattr(normal_filter, "evalcontextfilter", False) and not getattr(37+ normal_filter, "contextfilter", False38+ ):39+ wrap_evalctx = True40+41+ def is_async(args):42+ return args[0].environment.is_async43+44+ @wraps(normal_filter)45+ def wrapper(*args, **kwargs):46+ b = is_async(args)47+ if wrap_evalctx:48+ args = args[1:]49+ if b:50+ return async_filter(*args, **kwargs)51+ return normal_filter(*args, **kwargs)52+53+ if wrap_evalctx:54+ wrapper.evalcontextfilter = True55+56+ wrapper.asyncfiltervariant = True57+58+ return wrapper59+60+61+def asyncfiltervariant(original):62+ def decorator(f):63+ return dualfilter(original, f)64+65+ return decorator66+67+68+@asyncfiltervariant(filters.do_first)69+async def do_first(environment, seq):70+ try:71+ return await auto_aiter(seq).__anext__()72+ except StopAsyncIteration:73+ return environment.undefined("No first item, sequence was empty.")74+75+76+@asyncfiltervariant(filters.do_groupby)77+async def do_groupby(environment, value, attribute):78+ expr = filters.make_attrgetter(environment, attribute)79+ return [80+ filters._GroupTuple(key, await auto_to_seq(values))81+ for key, values in filters.groupby(82+ sorted(await auto_to_seq(value), key=expr), expr83+ )84+ ]85+86+87+@asyncfiltervariant(filters.do_join)88+async def do_join(eval_ctx, value, d=u"", attribute=None):89+ return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)90+91+92+@asyncfiltervariant(filters.do_list)93+async def do_list(value):94+ return await auto_to_seq(value)95+96+97+@asyncfiltervariant(filters.do_reject)98+async def do_reject(*args, **kwargs):99+ return async_select_or_reject(args, kwargs, lambda x: not x, False)100+101+102+@asyncfiltervariant(filters.do_rejectattr)103+async def do_rejectattr(*args, **kwargs):104+ return async_select_or_reject(args, kwargs, lambda x: not x, True)105+106+107+@asyncfiltervariant(filters.do_select)108+async def do_select(*args, **kwargs):109+ return async_select_or_reject(args, kwargs, lambda x: x, False)110+111+112+@asyncfiltervariant(filters.do_selectattr)113+async def do_selectattr(*args, **kwargs):114+ return async_select_or_reject(args, kwargs, lambda x: x, True)115+116+117+@asyncfiltervariant(filters.do_map)118+async def do_map(*args, **kwargs):119+ seq, func = filters.prepare_map(args, kwargs)120+ if seq:121+ async for item in auto_aiter(seq):122+ yield await auto_await(func(item))123+124+125+@asyncfiltervariant(filters.do_sum)126+async def do_sum(environment, iterable, attribute=None, start=0):127+ rv = start128+ if attribute is not None:129+ func = filters.make_attrgetter(environment, attribute)130+ else:131+132+ def func(x):133+ return x134+135+ async for item in auto_aiter(iterable):136+ rv += func(item)137+ return rv138+139+140+@asyncfiltervariant(filters.do_slice)141+async def do_slice(value, slices, fill_with=None):142+ return filters.do_slice(await auto_to_seq(value), slices, fill_with)143+144+145+ASYNC_FILTERS = {146+ "first": do_first,147+ "groupby": do_groupby,148+ "join": do_join,149+ "list": do_list,150+ # we intentionally do not support do_last because that would be151+ # ridiculous152+ "reject": do_reject,153+ "rejectattr": do_rejectattr,154+ "map": do_map,155+ "select": do_select,156+ "selectattr": do_selectattr,157+ "sum": do_sum,158+ "slice": do_slice,159+}added:src/jinja/asyncsupport.py+263 added
1+# -*- coding: utf-8 -*-2+"""The code for async support. Importing this patches Jinja on supported3+Python versions.4+"""5+import asyncio6+import inspect7+from functools import update_wrapper8+9+from .environment import TemplateModule10+from .runtime import LoopContext11+from .utils import concat12+from .utils import internalcode13+from .utils import Markup14+from .utils import missing15+16+17+async def concat_async(async_gen):18+ rv = []19+20+ async def collect():21+ async for event in async_gen:22+ rv.append(event)23+24+ await collect()25+ return concat(rv)26+27+28+async def generate_async(self, *args, **kwargs):29+ vars = dict(*args, **kwargs)30+ try:31+ async for event in self.root_render_func(self.new_context(vars)):32+ yield event33+ except Exception:34+ yield self.environment.handle_exception()35+36+37+def wrap_generate_func(original_generate):38+ def _convert_generator(self, loop, args, kwargs):39+ async_gen = self.generate_async(*args, **kwargs)40+ try:41+ while 1:42+ yield loop.run_until_complete(async_gen.__anext__())43+ except StopAsyncIteration:44+ pass45+46+ def generate(self, *args, **kwargs):47+ if not self.environment.is_async:48+ return original_generate(self, *args, **kwargs)49+ return _convert_generator(self, asyncio.get_event_loop(), args, kwargs)50+51+ return update_wrapper(generate, original_generate)52+53+54+async def render_async(self, *args, **kwargs):55+ if not self.environment.is_async:56+ raise RuntimeError("The environment was not created with async mode enabled.")57+58+ vars = dict(*args, **kwargs)59+ ctx = self.new_context(vars)60+61+ try:62+ return await concat_async(self.root_render_func(ctx))63+ except Exception:64+ return self.environment.handle_exception()65+66+67+def wrap_render_func(original_render):68+ def render(self, *args, **kwargs):69+ if not self.environment.is_async:70+ return original_render(self, *args, **kwargs)71+ loop = asyncio.get_event_loop()72+ return loop.run_until_complete(self.render_async(*args, **kwargs))73+74+ return update_wrapper(render, original_render)75+76+77+def wrap_block_reference_call(original_call):78+ @internalcode79+ async def async_call(self):80+ rv = await concat_async(self._stack[self._depth](self._context))81+ if self._context.eval_ctx.autoescape:82+ rv = Markup(rv)83+ return rv84+85+ @internalcode86+ def __call__(self):87+ if not self._context.environment.is_async:88+ return original_call(self)89+ return async_call(self)90+91+ return update_wrapper(__call__, original_call)92+93+94+def wrap_macro_invoke(original_invoke):95+ @internalcode96+ async def async_invoke(self, arguments, autoescape):97+ rv = await self._func(*arguments)98+ if autoescape:99+ rv = Markup(rv)100+ return rv101+102+ @internalcode103+ def _invoke(self, arguments, autoescape):104+ if not self._environment.is_async:105+ return original_invoke(self, arguments, autoescape)106+ return async_invoke(self, arguments, autoescape)107+108+ return update_wrapper(_invoke, original_invoke)109+110+111+@internalcode112+async def get_default_module_async(self):113+ if self._module is not None:114+ return self._module115+ self._module = rv = await self.make_module_async()116+ return rv117+118+119+def wrap_default_module(original_default_module):120+ @internalcode121+ def _get_default_module(self):122+ if self.environment.is_async:123+ raise RuntimeError("Template module attribute is unavailable in async mode")124+ return original_default_module(self)125+126+ return _get_default_module127+128+129+async def make_module_async(self, vars=None, shared=False, locals=None):130+ context = self.new_context(vars, shared, locals)131+ body_stream = []132+ async for item in self.root_render_func(context):133+ body_stream.append(item)134+ return TemplateModule(self, context, body_stream)135+136+137+def patch_template():138+ from . import Template139+140+ Template.generate = wrap_generate_func(Template.generate)141+ Template.generate_async = update_wrapper(generate_async, Template.generate_async)142+ Template.render_async = update_wrapper(render_async, Template.render_async)143+ Template.render = wrap_render_func(Template.render)144+ Template._get_default_module = wrap_default_module(Template._get_default_module)145+ Template._get_default_module_async = get_default_module_async146+ Template.make_module_async = update_wrapper(147+ make_module_async, Template.make_module_async148+ )149+150+151+def patch_runtime():152+ from .runtime import BlockReference, Macro153+154+ BlockReference.__call__ = wrap_block_reference_call(BlockReference.__call__)155+ Macro._invoke = wrap_macro_invoke(Macro._invoke)156+157+158+def patch_filters():159+ from .filters import FILTERS160+ from .asyncfilters import ASYNC_FILTERS161+162+ FILTERS.update(ASYNC_FILTERS)163+164+165+def patch_all():166+ patch_template()167+ patch_runtime()168+ patch_filters()169+170+171+async def auto_await(value):172+ if inspect.isawaitable(value):173+ return await value174+ return value175+176+177+async def auto_aiter(iterable):178+ if hasattr(iterable, "__aiter__"):179+ async for item in iterable:180+ yield item181+ return182+ for item in iterable:183+ yield item184+185+186+class AsyncLoopContext(LoopContext):187+ _to_iterator = staticmethod(auto_aiter)188+189+ @property190+ async def length(self):191+ if self._length is not None:192+ return self._length193+194+ try:195+ self._length = len(self._iterable)196+ except TypeError:197+ iterable = [x async for x in self._iterator]198+ self._iterator = self._to_iterator(iterable)199+ self._length = len(iterable) + self.index + (self._after is not missing)200+201+ return self._length202+203+ @property204+ async def revindex0(self):205+ return await self.length - self.index206+207+ @property208+ async def revindex(self):209+ return await self.length - self.index0210+211+ async def _peek_next(self):212+ if self._after is not missing:213+ return self._after214+215+ try:216+ self._after = await self._iterator.__anext__()217+ except StopAsyncIteration:218+ self._after = missing219+220+ return self._after221+222+ @property223+ async def last(self):224+ return await self._peek_next() is missing225+226+ @property227+ async def nextitem(self):228+ rv = await self._peek_next()229+230+ if rv is missing:231+ return self._undefined("there is no next item")232+233+ return rv234+235+ def __aiter__(self):236+ return self237+238+ async def __anext__(self):239+ if self._after is not missing:240+ rv = self._after241+ self._after = missing242+ else:243+ rv = await self._iterator.__anext__()244+245+ self.index0 += 1246+ self._before = self._current247+ self._current = rv248+ return rv, self249+250+251+async def make_async_loop_context(iterable, undefined, recurse=None, depth0=0):252+ import warnings253+254+ warnings.warn(255+ "This template must be recompiled with at least Jinja 2.11, or"256+ " it will fail in 3.0.",257+ DeprecationWarning,258+ stacklevel=2,259+ )260+ return AsyncLoopContext(iterable, undefined, recurse, depth0)261+262+263+patch_all()added:src/jinja/bccache.py+353 added
1+# -*- coding: utf-8 -*-2+"""The optional bytecode cache system. This is useful if you have very3+complex template situations and the compilation of all those templates4+slows down your application too much.5+6+Situations where this is useful are often forking web applications that7+are initialized on the first request.8+"""9+import errno10+import fnmatch11+import os12+import stat13+import sys14+import tempfile15+from hashlib import sha116+from os import listdir17+from os import path18+19+from ._compat import BytesIO20+from ._compat import marshal_dump21+from ._compat import marshal_load22+from ._compat import pickle23+from ._compat import text_type24+from .utils import open_if_exists25+26+bc_version = 327+28+# magic version used to only change with new jinja versions. With 2.629+# we change this to also take Python version changes into account. The30+# reason for this is that Python tends to segfault if fed earlier bytecode31+# versions because someone thought it would be a good idea to reuse opcodes32+# or make Python incompatible with earlier versions.33+bc_magic = (34+ "j2".encode("ascii")35+ + pickle.dumps(bc_version, 2)36+ + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1])37+)38+39+40+class Bucket(object):41+ """Buckets are used to store the bytecode for one template. It's created42+ and initialized by the bytecode cache and passed to the loading functions.43+44+ The buckets get an internal checksum from the cache assigned and use this45+ to automatically reject outdated cache material. Individual bytecode46+ cache subclasses don't have to care about cache invalidation.47+ """48+49+ def __init__(self, environment, key, checksum):50+ self.environment = environment51+ self.key = key52+ self.checksum = checksum53+ self.reset()54+55+ def reset(self):56+ """Resets the bucket (unloads the bytecode)."""57+ self.code = None58+59+ def load_bytecode(self, f):60+ """Loads bytecode from a file or file like object."""61+ # make sure the magic header is correct62+ magic = f.read(len(bc_magic))63+ if magic != bc_magic:64+ self.reset()65+ return66+ # the source code of the file changed, we need to reload67+ checksum = pickle.load(f)68+ if self.checksum != checksum:69+ self.reset()70+ return71+ # if marshal_load fails then we need to reload72+ try:73+ self.code = marshal_load(f)74+ except (EOFError, ValueError, TypeError):75+ self.reset()76+ return77+78+ def write_bytecode(self, f):79+ """Dump the bytecode into the file or file like object passed."""80+ if self.code is None:81+ raise TypeError("can't write empty bucket")82+ f.write(bc_magic)83+ pickle.dump(self.checksum, f, 2)84+ marshal_dump(self.code, f)85+86+ def bytecode_from_string(self, string):87+ """Load bytecode from a string."""88+ self.load_bytecode(BytesIO(string))89+90+ def bytecode_to_string(self):91+ """Return the bytecode as string."""92+ out = BytesIO()93+ self.write_bytecode(out)94+ return out.getvalue()95+96+97+class BytecodeCache(object):98+ """To implement your own bytecode cache you have to subclass this class99+ and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of100+ these methods are passed a :class:`~jinja2.bccache.Bucket`.101+102+ A very basic bytecode cache that saves the bytecode on the file system::103+104+ from os import path105+106+ class MyCache(BytecodeCache):107+108+ def __init__(self, directory):109+ self.directory = directory110+111+ def load_bytecode(self, bucket):112+ filename = path.join(self.directory, bucket.key)113+ if path.exists(filename):114+ with open(filename, 'rb') as f:115+ bucket.load_bytecode(f)116+117+ def dump_bytecode(self, bucket):118+ filename = path.join(self.directory, bucket.key)119+ with open(filename, 'wb') as f:120+ bucket.write_bytecode(f)121+122+ A more advanced version of a filesystem based bytecode cache is part of123+ Jinja.124+ """125+126+ def load_bytecode(self, bucket):127+ """Subclasses have to override this method to load bytecode into a128+ bucket. If they are not able to find code in the cache for the129+ bucket, it must not do anything.130+ """131+ raise NotImplementedError()132+133+ def dump_bytecode(self, bucket):134+ """Subclasses have to override this method to write the bytecode135+ from a bucket back to the cache. If it unable to do so it must not136+ fail silently but raise an exception.137+ """138+ raise NotImplementedError()139+140+ def clear(self):141+ """Clears the cache. This method is not used by Jinja but should be142+ implemented to allow applications to clear the bytecode cache used143+ by a particular environment.144+ """145+146+ def get_cache_key(self, name, filename=None):147+ """Returns the unique hash key for this template name."""148+ hash = sha1(name.encode("utf-8"))149+ if filename is not None:150+ filename = "|" + filename151+ if isinstance(filename, text_type):152+ filename = filename.encode("utf-8")153+ hash.update(filename)154+ return hash.hexdigest()155+156+ def get_source_checksum(self, source):157+ """Returns a checksum for the source."""158+ return sha1(source.encode("utf-8")).hexdigest()159+160+ def get_bucket(self, environment, name, filename, source):161+ """Return a cache bucket for the given template. All arguments are162+ mandatory but filename may be `None`.163+ """164+ key = self.get_cache_key(name, filename)165+ checksum = self.get_source_checksum(source)166+ bucket = Bucket(environment, key, checksum)167+ self.load_bytecode(bucket)168+ return bucket169+170+ def set_bucket(self, bucket):171+ """Put the bucket into the cache."""172+ self.dump_bytecode(bucket)173+174+175+class FileSystemBytecodeCache(BytecodeCache):176+ """A bytecode cache that stores bytecode on the filesystem. It accepts177+ two arguments: The directory where the cache items are stored and a178+ pattern string that is used to build the filename.179+180+ If no directory is specified a default cache directory is selected. On181+ Windows the user's temp directory is used, on UNIX systems a directory182+ is created for the user in the system temp directory.183+184+ The pattern can be used to have multiple separate caches operate on the185+ same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``186+ is replaced with the cache key.187+188+ >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')189+190+ This bytecode cache supports clearing of the cache using the clear method.191+ """192+193+ def __init__(self, directory=None, pattern="__jinja2_%s.cache"):194+ if directory is None:195+ directory = self._get_default_cache_dir()196+ self.directory = directory197+ self.pattern = pattern198+199+ def _get_default_cache_dir(self):200+ def _unsafe_dir():201+ raise RuntimeError(202+ "Cannot determine safe temp directory. You "203+ "need to explicitly provide one."204+ )205+206+ tmpdir = tempfile.gettempdir()207+208+ # On windows the temporary directory is used specific unless209+ # explicitly forced otherwise. We can just use that.210+ if os.name == "nt":211+ return tmpdir212+ if not hasattr(os, "getuid"):213+ _unsafe_dir()214+215+ dirname = "_jinja2-cache-%d" % os.getuid()216+ actual_dir = os.path.join(tmpdir, dirname)217+218+ try:219+ os.mkdir(actual_dir, stat.S_IRWXU)220+ except OSError as e:221+ if e.errno != errno.EEXIST:222+ raise223+ try:224+ os.chmod(actual_dir, stat.S_IRWXU)225+ actual_dir_stat = os.lstat(actual_dir)226+ if (227+ actual_dir_stat.st_uid != os.getuid()228+ or not stat.S_ISDIR(actual_dir_stat.st_mode)229+ or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU230+ ):231+ _unsafe_dir()232+ except OSError as e:233+ if e.errno != errno.EEXIST:234+ raise235+236+ actual_dir_stat = os.lstat(actual_dir)237+ if (238+ actual_dir_stat.st_uid != os.getuid()239+ or not stat.S_ISDIR(actual_dir_stat.st_mode)240+ or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU241+ ):242+ _unsafe_dir()243+244+ return actual_dir245+246+ def _get_cache_filename(self, bucket):247+ return path.join(self.directory, self.pattern % bucket.key)248+249+ def load_bytecode(self, bucket):250+ f = open_if_exists(self._get_cache_filename(bucket), "rb")251+ if f is not None:252+ try:253+ bucket.load_bytecode(f)254+ finally:255+ f.close()256+257+ def dump_bytecode(self, bucket):258+ f = open(self._get_cache_filename(bucket), "wb")259+ try:260+ bucket.write_bytecode(f)261+ finally:262+ f.close()263+264+ def clear(self):265+ # imported lazily here because google app-engine doesn't support266+ # write access on the file system and the function does not exist267+ # normally.268+ from os import remove269+270+ files = fnmatch.filter(listdir(self.directory), self.pattern % "*")271+ for filename in files:272+ try:273+ remove(path.join(self.directory, filename))274+ except OSError:275+ pass276+277+278+class MemcachedBytecodeCache(BytecodeCache):279+ """This class implements a bytecode cache that uses a memcache cache for280+ storing the information. It does not enforce a specific memcache library281+ (tummy's memcache or cmemcache) but will accept any class that provides282+ the minimal interface required.283+284+ Libraries compatible with this class:285+286+ - `cachelib <https://github.com/pallets/cachelib>`_287+ - `python-memcached <https://pypi.org/project/python-memcached/>`_288+289+ (Unfortunately the django cache interface is not compatible because it290+ does not support storing binary data, only unicode. You can however pass291+ the underlying cache client to the bytecode cache which is available292+ as `django.core.cache.cache._client`.)293+294+ The minimal interface for the client passed to the constructor is this:295+296+ .. class:: MinimalClientInterface297+298+ .. method:: set(key, value[, timeout])299+300+ Stores the bytecode in the cache. `value` is a string and301+ `timeout` the timeout of the key. If timeout is not provided302+ a default timeout or no timeout should be assumed, if it's303+ provided it's an integer with the number of seconds the cache304+ item should exist.305+306+ .. method:: get(key)307+308+ Returns the value for the cache key. If the item does not309+ exist in the cache the return value must be `None`.310+311+ The other arguments to the constructor are the prefix for all keys that312+ is added before the actual cache key and the timeout for the bytecode in313+ the cache system. We recommend a high (or no) timeout.314+315+ This bytecode cache does not support clearing of used items in the cache.316+ The clear method is a no-operation function.317+318+ .. versionadded:: 2.7319+ Added support for ignoring memcache errors through the320+ `ignore_memcache_errors` parameter.321+ """322+323+ def __init__(324+ self,325+ client,326+ prefix="jinja2/bytecode/",327+ timeout=None,328+ ignore_memcache_errors=True,329+ ):330+ self.client = client331+ self.prefix = prefix332+ self.timeout = timeout333+ self.ignore_memcache_errors = ignore_memcache_errors334+335+ def load_bytecode(self, bucket):336+ try:337+ code = self.client.get(self.prefix + bucket.key)338+ except Exception:339+ if not self.ignore_memcache_errors:340+ raise341+ code = None342+ if code is not None:343+ bucket.bytecode_from_string(code)344+345+ def dump_bytecode(self, bucket):346+ args = (self.prefix + bucket.key, bucket.bytecode_to_string())347+ if self.timeout is not None:348+ args += (self.timeout,)349+ try:350+ self.client.set(*args)351+ except Exception:352+ if not self.ignore_memcache_errors:353+ raiseadded:src/jinja/compiler.py+1842 added
1+# -*- coding: utf-8 -*-2+"""Compiles nodes from the parser into Python code."""3+from collections import namedtuple4+from functools import update_wrapper5+from itertools import chain6+from keyword import iskeyword as is_python_keyword7+8+from . import nodes9+from ._compat import imap10+from ._compat import iteritems11+from ._compat import izip12+from ._compat import NativeStringIO13+from ._compat import range_type14+from ._compat import string_types15+from ._compat import text_type16+from .exceptions import TemplateAssertionError17+from .idtracking import Symbols18+from .idtracking import VAR_LOAD_ALIAS19+from .idtracking import VAR_LOAD_PARAMETER20+from .idtracking import VAR_LOAD_RESOLVE21+from .idtracking import VAR_LOAD_UNDEFINED22+from .nodes import EvalContext23+from .optimizer import Optimizer24+from .utils import concat25+from .utils import escape26+from .utils import Markup27+from .visitor import NodeVisitor28+29+operators = {30+ "eq": "==",31+ "ne": "!=",32+ "gt": ">",33+ "gteq": ">=",34+ "lt": "<",35+ "lteq": "<=",36+ "in": "in",37+ "notin": "not in",38+}39+40+# what method to iterate over items do we want to use for dict iteration41+# in generated code? on 2.x let's go with iteritems, on 3.x with items42+if hasattr(dict, "iteritems"):43+ dict_item_iter = "iteritems"44+else:45+ dict_item_iter = "items"46+47+code_features = ["division"]48+49+# does this python version support generator stops? (PEP 0479)50+try:51+ exec("from __future__ import generator_stop")52+ code_features.append("generator_stop")53+except SyntaxError:54+ pass55+56+# does this python version support yield from?57+try:58+ exec("def f(): yield from x()")59+except SyntaxError:60+ supports_yield_from = False61+else:62+ supports_yield_from = True63+64+65+def optimizeconst(f):66+ def new_func(self, node, frame, **kwargs):67+ # Only optimize if the frame is not volatile68+ if self.optimized and not frame.eval_ctx.volatile:69+ new_node = self.optimizer.visit(node, frame.eval_ctx)70+ if new_node != node:71+ return self.visit(new_node, frame)72+ return f(self, node, frame, **kwargs)73+74+ return update_wrapper(new_func, f)75+76+77+def generate(78+ node, environment, name, filename, stream=None, defer_init=False, optimized=True79+):80+ """Generate the python source for a node tree."""81+ if not isinstance(node, nodes.Template):82+ raise TypeError("Can't compile non template nodes")83+ generator = environment.code_generator_class(84+ environment, name, filename, stream, defer_init, optimized85+ )86+ generator.visit(node)87+ if stream is None:88+ return generator.stream.getvalue()89+90+91+def has_safe_repr(value):92+ """Does the node have a safe representation?"""93+ if value is None or value is NotImplemented or value is Ellipsis:94+ return True95+ if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:96+ return True97+ if type(value) in (tuple, list, set, frozenset):98+ for item in value:99+ if not has_safe_repr(item):100+ return False101+ return True102+ elif type(value) is dict:103+ for key, value in iteritems(value):104+ if not has_safe_repr(key):105+ return False106+ if not has_safe_repr(value):107+ return False108+ return True109+ return False110+111+112+def find_undeclared(nodes, names):113+ """Check if the names passed are accessed undeclared. The return value114+ is a set of all the undeclared names from the sequence of names found.115+ """116+ visitor = UndeclaredNameVisitor(names)117+ try:118+ for node in nodes:119+ visitor.visit(node)120+ except VisitorExit:121+ pass122+ return visitor.undeclared123+124+125+class MacroRef(object):126+ def __init__(self, node):127+ self.node = node128+ self.accesses_caller = False129+ self.accesses_kwargs = False130+ self.accesses_varargs = False131+132+133+class Frame(object):134+ """Holds compile time information for us."""135+136+ def __init__(self, eval_ctx, parent=None, level=None):137+ self.eval_ctx = eval_ctx138+ self.symbols = Symbols(parent and parent.symbols or None, level=level)139+140+ # a toplevel frame is the root + soft frames such as if conditions.141+ self.toplevel = False142+143+ # the root frame is basically just the outermost frame, so no if144+ # conditions. This information is used to optimize inheritance145+ # situations.146+ self.rootlevel = False147+148+ # in some dynamic inheritance situations the compiler needs to add149+ # write tests around output statements.150+ self.require_output_check = parent and parent.require_output_check151+152+ # inside some tags we are using a buffer rather than yield statements.153+ # this for example affects {% filter %} or {% macro %}. If a frame154+ # is buffered this variable points to the name of the list used as155+ # buffer.156+ self.buffer = None157+158+ # the name of the block we're in, otherwise None.159+ self.block = parent and parent.block or None160+161+ # the parent of this frame162+ self.parent = parent163+164+ if parent is not None:165+ self.buffer = parent.buffer166+167+ def copy(self):168+ """Create a copy of the current one."""169+ rv = object.__new__(self.__class__)170+ rv.__dict__.update(self.__dict__)171+ rv.symbols = self.symbols.copy()172+ return rv173+174+ def inner(self, isolated=False):175+ """Return an inner frame."""176+ if isolated:177+ return Frame(self.eval_ctx, level=self.symbols.level + 1)178+ return Frame(self.eval_ctx, self)179+180+ def soft(self):181+ """Return a soft frame. A soft frame may not be modified as182+ standalone thing as it shares the resources with the frame it183+ was created of, but it's not a rootlevel frame any longer.184+185+ This is only used to implement if-statements.186+ """187+ rv = self.copy()188+ rv.rootlevel = False189+ return rv190+191+ __copy__ = copy192+193+194+class VisitorExit(RuntimeError):195+ """Exception used by the `UndeclaredNameVisitor` to signal a stop."""196+197+198+class DependencyFinderVisitor(NodeVisitor):199+ """A visitor that collects filter and test calls."""200+201+ def __init__(self):202+ self.filters = set()203+ self.tests = set()204+205+ def visit_Filter(self, node):206+ self.generic_visit(node)207+ self.filters.add(node.name)208+209+ def visit_Test(self, node):210+ self.generic_visit(node)211+ self.tests.add(node.name)212+213+ def visit_Block(self, node):214+ """Stop visiting at blocks."""215+216+217+class UndeclaredNameVisitor(NodeVisitor):218+ """A visitor that checks if a name is accessed without being219+ declared. This is different from the frame visitor as it will220+ not stop at closure frames.221+ """222+223+ def __init__(self, names):224+ self.names = set(names)225+ self.undeclared = set()226+227+ def visit_Name(self, node):228+ if node.ctx == "load" and node.name in self.names:229+ self.undeclared.add(node.name)230+ if self.undeclared == self.names:231+ raise VisitorExit()232+ else:233+ self.names.discard(node.name)234+235+ def visit_Block(self, node):236+ """Stop visiting a blocks."""237+238+239+class CompilerExit(Exception):240+ """Raised if the compiler encountered a situation where it just241+ doesn't make sense to further process the code. Any block that242+ raises such an exception is not further processed.243+ """244+245+246+class CodeGenerator(NodeVisitor):247+ def __init__(248+ self, environment, name, filename, stream=None, defer_init=False, optimized=True249+ ):250+ if stream is None:251+ stream = NativeStringIO()252+ self.environment = environment253+ self.name = name254+ self.filename = filename255+ self.stream = stream256+ self.created_block_context = False257+ self.defer_init = defer_init258+ self.optimized = optimized259+ if optimized:260+ self.optimizer = Optimizer(environment)261+262+ # aliases for imports263+ self.import_aliases = {}264+265+ # a registry for all blocks. Because blocks are moved out266+ # into the global python scope they are registered here267+ self.blocks = {}268+269+ # the number of extends statements so far270+ self.extends_so_far = 0271+272+ # some templates have a rootlevel extends. In this case we273+ # can safely assume that we're a child template and do some274+ # more optimizations.275+ self.has_known_extends = False276+277+ # the current line number278+ self.code_lineno = 1279+280+ # registry of all filters and tests (global, not block local)281+ self.tests = {}282+ self.filters = {}283+284+ # the debug information285+ self.debug_info = []286+ self._write_debug_info = None287+288+ # the number of new lines before the next write()289+ self._new_lines = 0290+291+ # the line number of the last written statement292+ self._last_line = 0293+294+ # true if nothing was written so far.295+ self._first_write = True296+297+ # used by the `temporary_identifier` method to get new298+ # unique, temporary identifier299+ self._last_identifier = 0300+301+ # the current indentation302+ self._indentation = 0303+304+ # Tracks toplevel assignments305+ self._assign_stack = []306+307+ # Tracks parameter definition blocks308+ self._param_def_block = []309+310+ # Tracks the current context.311+ self._context_reference_stack = ["context"]312+313+ # -- Various compilation helpers314+315+ def fail(self, msg, lineno):316+ """Fail with a :exc:`TemplateAssertionError`."""317+ raise TemplateAssertionError(msg, lineno, self.name, self.filename)318+319+ def temporary_identifier(self):320+ """Get a new unique identifier."""321+ self._last_identifier += 1322+ return "t_%d" % self._last_identifier323+324+ def buffer(self, frame):325+ """Enable buffering for the frame from that point onwards."""326+ frame.buffer = self.temporary_identifier()327+ self.writeline("%s = []" % frame.buffer)328+329+ def return_buffer_contents(self, frame, force_unescaped=False):330+ """Return the buffer contents of the frame."""331+ if not force_unescaped:332+ if frame.eval_ctx.volatile:333+ self.writeline("if context.eval_ctx.autoescape:")334+ self.indent()335+ self.writeline("return Markup(concat(%s))" % frame.buffer)336+ self.outdent()337+ self.writeline("else:")338+ self.indent()339+ self.writeline("return concat(%s)" % frame.buffer)340+ self.outdent()341+ return342+ elif frame.eval_ctx.autoescape:343+ self.writeline("return Markup(concat(%s))" % frame.buffer)344+ return345+ self.writeline("return concat(%s)" % frame.buffer)346+347+ def indent(self):348+ """Indent by one."""349+ self._indentation += 1350+351+ def outdent(self, step=1):352+ """Outdent by step."""353+ self._indentation -= step354+355+ def start_write(self, frame, node=None):356+ """Yield or write into the frame buffer."""357+ if frame.buffer is None:358+ self.writeline("yield ", node)359+ else:360+ self.writeline("%s.append(" % frame.buffer, node)361+362+ def end_write(self, frame):363+ """End the writing process started by `start_write`."""364+ if frame.buffer is not None:365+ self.write(")")366+367+ def simple_write(self, s, frame, node=None):368+ """Simple shortcut for start_write + write + end_write."""369+ self.start_write(frame, node)370+ self.write(s)371+ self.end_write(frame)372+373+ def blockvisit(self, nodes, frame):374+ """Visit a list of nodes as block in a frame. If the current frame375+ is no buffer a dummy ``if 0: yield None`` is written automatically.376+ """377+ try:378+ self.writeline("pass")379+ for node in nodes:380+ self.visit(node, frame)381+ except CompilerExit:382+ pass383+384+ def write(self, x):385+ """Write a string into the output stream."""386+ if self._new_lines:387+ if not self._first_write:388+ self.stream.write("\n" * self._new_lines)389+ self.code_lineno += self._new_lines390+ if self._write_debug_info is not None:391+ self.debug_info.append((self._write_debug_info, self.code_lineno))392+ self._write_debug_info = None393+ self._first_write = False394+ self.stream.write(" " * self._indentation)395+ self._new_lines = 0396+ self.stream.write(x)397+398+ def writeline(self, x, node=None, extra=0):399+ """Combination of newline and write."""400+ self.newline(node, extra)401+ self.write(x)402+403+ def newline(self, node=None, extra=0):404+ """Add one or more newlines before the next write."""405+ self._new_lines = max(self._new_lines, 1 + extra)406+ if node is not None and node.lineno != self._last_line:407+ self._write_debug_info = node.lineno408+ self._last_line = node.lineno409+410+ def signature(self, node, frame, extra_kwargs=None):411+ """Writes a function call to the stream for the current node.412+ A leading comma is added automatically. The extra keyword413+ arguments may not include python keywords otherwise a syntax414+ error could occur. The extra keyword arguments should be given415+ as python dict.416+ """417+ # if any of the given keyword arguments is a python keyword418+ # we have to make sure that no invalid call is created.419+ kwarg_workaround = False420+ for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):421+ if is_python_keyword(kwarg):422+ kwarg_workaround = True423+ break424+425+ for arg in node.args:426+ self.write(", ")427+ self.visit(arg, frame)428+429+ if not kwarg_workaround:430+ for kwarg in node.kwargs:431+ self.write(", ")432+ self.visit(kwarg, frame)433+ if extra_kwargs is not None:434+ for key, value in iteritems(extra_kwargs):435+ self.write(", %s=%s" % (key, value))436+ if node.dyn_args:437+ self.write(", *")438+ self.visit(node.dyn_args, frame)439+440+ if kwarg_workaround:441+ if node.dyn_kwargs is not None:442+ self.write(", **dict({")443+ else:444+ self.write(", **{")445+ for kwarg in node.kwargs:446+ self.write("%r: " % kwarg.key)447+ self.visit(kwarg.value, frame)448+ self.write(", ")449+ if extra_kwargs is not None:450+ for key, value in iteritems(extra_kwargs):451+ self.write("%r: %s, " % (key, value))452+ if node.dyn_kwargs is not None:453+ self.write("}, **")454+ self.visit(node.dyn_kwargs, frame)455+ self.write(")")456+ else:457+ self.write("}")458+459+ elif node.dyn_kwargs is not None:460+ self.write(", **")461+ self.visit(node.dyn_kwargs, frame)462+463+ def pull_dependencies(self, nodes):464+ """Pull all the dependencies."""465+ visitor = DependencyFinderVisitor()466+ for node in nodes:467+ visitor.visit(node)468+ for dependency in "filters", "tests":469+ mapping = getattr(self, dependency)470+ for name in getattr(visitor, dependency):471+ if name not in mapping:472+ mapping[name] = self.temporary_identifier()473+ self.writeline(474+ "%s = environment.%s[%r]" % (mapping[name], dependency, name)475+ )476+477+ def enter_frame(self, frame):478+ undefs = []479+ for target, (action, param) in iteritems(frame.symbols.loads):480+ if action == VAR_LOAD_PARAMETER:481+ pass482+ elif action == VAR_LOAD_RESOLVE:483+ self.writeline("%s = %s(%r)" % (target, self.get_resolve_func(), param))484+ elif action == VAR_LOAD_ALIAS:485+ self.writeline("%s = %s" % (target, param))486+ elif action == VAR_LOAD_UNDEFINED:487+ undefs.append(target)488+ else:489+ raise NotImplementedError("unknown load instruction")490+ if undefs:491+ self.writeline("%s = missing" % " = ".join(undefs))492+493+ def leave_frame(self, frame, with_python_scope=False):494+ if not with_python_scope:495+ undefs = []496+ for target, _ in iteritems(frame.symbols.loads):497+ undefs.append(target)498+ if undefs:499+ self.writeline("%s = missing" % " = ".join(undefs))500+501+ def func(self, name):502+ if self.environment.is_async:503+ return "async def %s" % name504+ return "def %s" % name505+506+ def macro_body(self, node, frame):507+ """Dump the function def of a macro or call block."""508+ frame = frame.inner()509+ frame.symbols.analyze_node(node)510+ macro_ref = MacroRef(node)511+512+ explicit_caller = None513+ skip_special_params = set()514+ args = []515+ for idx, arg in enumerate(node.args):516+ if arg.name == "caller":517+ explicit_caller = idx518+ if arg.name in ("kwargs", "varargs"):519+ skip_special_params.add(arg.name)520+ args.append(frame.symbols.ref(arg.name))521+522+ undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs"))523+524+ if "caller" in undeclared:525+ # In older Jinja versions there was a bug that allowed caller526+ # to retain the special behavior even if it was mentioned in527+ # the argument list. However thankfully this was only really528+ # working if it was the last argument. So we are explicitly529+ # checking this now and error out if it is anywhere else in530+ # the argument list.531+ if explicit_caller is not None:532+ try:533+ node.defaults[explicit_caller - len(node.args)]534+ except IndexError:535+ self.fail(536+ "When defining macros or call blocks the "537+ 'special "caller" argument must be omitted '538+ "or be given a default.",539+ node.lineno,540+ )541+ else:542+ args.append(frame.symbols.declare_parameter("caller"))543+ macro_ref.accesses_caller = True544+ if "kwargs" in undeclared and "kwargs" not in skip_special_params:545+ args.append(frame.symbols.declare_parameter("kwargs"))546+ macro_ref.accesses_kwargs = True547+ if "varargs" in undeclared and "varargs" not in skip_special_params:548+ args.append(frame.symbols.declare_parameter("varargs"))549+ macro_ref.accesses_varargs = True550+551+ # macros are delayed, they never require output checks552+ frame.require_output_check = False553+ frame.symbols.analyze_node(node)554+ self.writeline("%s(%s):" % (self.func("macro"), ", ".join(args)), node)555+ self.indent()556+557+ self.buffer(frame)558+ self.enter_frame(frame)559+560+ self.push_parameter_definitions(frame)561+ for idx, arg in enumerate(node.args):562+ ref = frame.symbols.ref(arg.name)563+ self.writeline("if %s is missing:" % ref)564+ self.indent()565+ try:566+ default = node.defaults[idx - len(node.args)]567+ except IndexError:568+ self.writeline(569+ "%s = undefined(%r, name=%r)"570+ % (ref, "parameter %r was not provided" % arg.name, arg.name)571+ )572+ else:573+ self.writeline("%s = " % ref)574+ self.visit(default, frame)575+ self.mark_parameter_stored(ref)576+ self.outdent()577+ self.pop_parameter_definitions()578+579+ self.blockvisit(node.body, frame)580+ self.return_buffer_contents(frame, force_unescaped=True)581+ self.leave_frame(frame, with_python_scope=True)582+ self.outdent()583+584+ return frame, macro_ref585+586+ def macro_def(self, macro_ref, frame):587+ """Dump the macro definition for the def created by macro_body."""588+ arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args)589+ name = getattr(macro_ref.node, "name", None)590+ if len(macro_ref.node.args) == 1:591+ arg_tuple += ","592+ self.write(593+ "Macro(environment, macro, %r, (%s), %r, %r, %r, "594+ "context.eval_ctx.autoescape)"595+ % (596+ name,597+ arg_tuple,598+ macro_ref.accesses_kwargs,599+ macro_ref.accesses_varargs,600+ macro_ref.accesses_caller,601+ )602+ )603+604+ def position(self, node):605+ """Return a human readable position for the node."""606+ rv = "line %d" % node.lineno607+ if self.name is not None:608+ rv += " in " + repr(self.name)609+ return rv610+611+ def dump_local_context(self, frame):612+ return "{%s}" % ", ".join(613+ "%r: %s" % (name, target)614+ for name, target in iteritems(frame.symbols.dump_stores())615+ )616+617+ def write_commons(self):618+ """Writes a common preamble that is used by root and block functions.619+ Primarily this sets up common local helpers and enforces a generator620+ through a dead branch.621+ """622+ self.writeline("resolve = context.resolve_or_missing")623+ self.writeline("undefined = environment.undefined")624+ # always use the standard Undefined class for the implicit else of625+ # conditional expressions626+ self.writeline("cond_expr_undefined = Undefined")627+ self.writeline("if 0: yield None")628+629+ def push_parameter_definitions(self, frame):630+ """Pushes all parameter targets from the given frame into a local631+ stack that permits tracking of yet to be assigned parameters. In632+ particular this enables the optimization from `visit_Name` to skip633+ undefined expressions for parameters in macros as macros can reference634+ otherwise unbound parameters.635+ """636+ self._param_def_block.append(frame.symbols.dump_param_targets())637+638+ def pop_parameter_definitions(self):639+ """Pops the current parameter definitions set."""640+ self._param_def_block.pop()641+642+ def mark_parameter_stored(self, target):643+ """Marks a parameter in the current parameter definitions as stored.644+ This will skip the enforced undefined checks.645+ """646+ if self._param_def_block:647+ self._param_def_block[-1].discard(target)648+649+ def push_context_reference(self, target):650+ self._context_reference_stack.append(target)651+652+ def pop_context_reference(self):653+ self._context_reference_stack.pop()654+655+ def get_context_ref(self):656+ return self._context_reference_stack[-1]657+658+ def get_resolve_func(self):659+ target = self._context_reference_stack[-1]660+ if target == "context":661+ return "resolve"662+ return "%s.resolve" % target663+664+ def derive_context(self, frame):665+ return "%s.derived(%s)" % (666+ self.get_context_ref(),667+ self.dump_local_context(frame),668+ )669+670+ def parameter_is_undeclared(self, target):671+ """Checks if a given target is an undeclared parameter."""672+ if not self._param_def_block:673+ return False674+ return target in self._param_def_block[-1]675+676+ def push_assign_tracking(self):677+ """Pushes a new layer for assignment tracking."""678+ self._assign_stack.append(set())679+680+ def pop_assign_tracking(self, frame):681+ """Pops the topmost level for assignment tracking and updates the682+ context variables if necessary.683+ """684+ vars = self._assign_stack.pop()685+ if not frame.toplevel or not vars:686+ return687+ public_names = [x for x in vars if x[:1] != "_"]688+ if len(vars) == 1:689+ name = next(iter(vars))690+ ref = frame.symbols.ref(name)691+ self.writeline("context.vars[%r] = %s" % (name, ref))692+ else:693+ self.writeline("context.vars.update({")694+ for idx, name in enumerate(vars):695+ if idx:696+ self.write(", ")697+ ref = frame.symbols.ref(name)698+ self.write("%r: %s" % (name, ref))699+ self.write("})")700+ if public_names:701+ if len(public_names) == 1:702+ self.writeline("context.exported_vars.add(%r)" % public_names[0])703+ else:704+ self.writeline(705+ "context.exported_vars.update((%s))"706+ % ", ".join(imap(repr, public_names))707+ )708+709+ # -- Statement Visitors710+711+ def visit_Template(self, node, frame=None):712+ assert frame is None, "no root frame allowed"713+ eval_ctx = EvalContext(self.environment, self.name)714+715+ from .runtime import __all__ as exported716+717+ self.writeline("from __future__ import %s" % ", ".join(code_features))718+ self.writeline("from jinja2.runtime import " + ", ".join(exported))719+720+ if self.environment.is_async:721+ self.writeline(722+ "from jinja2.asyncsupport import auto_await, "723+ "auto_aiter, AsyncLoopContext"724+ )725+726+ # if we want a deferred initialization we cannot move the727+ # environment into a local name728+ envenv = not self.defer_init and ", environment=environment" or ""729+730+ # do we have an extends tag at all? If not, we can save some731+ # overhead by just not processing any inheritance code.732+ have_extends = node.find(nodes.Extends) is not None733+734+ # find all blocks735+ for block in node.find_all(nodes.Block):736+ if block.name in self.blocks:737+ self.fail("block %r defined twice" % block.name, block.lineno)738+ self.blocks[block.name] = block739+740+ # find all imports and import them741+ for import_ in node.find_all(nodes.ImportedName):742+ if import_.importname not in self.import_aliases:743+ imp = import_.importname744+ self.import_aliases[imp] = alias = self.temporary_identifier()745+ if "." in imp:746+ module, obj = imp.rsplit(".", 1)747+ self.writeline("from %s import %s as %s" % (module, obj, alias))748+ else:749+ self.writeline("import %s as %s" % (imp, alias))750+751+ # add the load name752+ self.writeline("name = %r" % self.name)753+754+ # generate the root render function.755+ self.writeline(756+ "%s(context, missing=missing%s):" % (self.func("root"), envenv), extra=1757+ )758+ self.indent()759+ self.write_commons()760+761+ # process the root762+ frame = Frame(eval_ctx)763+ if "self" in find_undeclared(node.body, ("self",)):764+ ref = frame.symbols.declare_parameter("self")765+ self.writeline("%s = TemplateReference(context)" % ref)766+ frame.symbols.analyze_node(node)767+ frame.toplevel = frame.rootlevel = True768+ frame.require_output_check = have_extends and not self.has_known_extends769+ if have_extends:770+ self.writeline("parent_template = None")771+ self.enter_frame(frame)772+ self.pull_dependencies(node.body)773+ self.blockvisit(node.body, frame)774+ self.leave_frame(frame, with_python_scope=True)775+ self.outdent()776+777+ # make sure that the parent root is called.778+ if have_extends:779+ if not self.has_known_extends:780+ self.indent()781+ self.writeline("if parent_template is not None:")782+ self.indent()783+ if supports_yield_from and not self.environment.is_async:784+ self.writeline("yield from parent_template.root_render_func(context)")785+ else:786+ self.writeline(787+ "%sfor event in parent_template."788+ "root_render_func(context):"789+ % (self.environment.is_async and "async " or "")790+ )791+ self.indent()792+ self.writeline("yield event")793+ self.outdent()794+ self.outdent(1 + (not self.has_known_extends))795+796+ # at this point we now have the blocks collected and can visit them too.797+ for name, block in iteritems(self.blocks):798+ self.writeline(799+ "%s(context, missing=missing%s):"800+ % (self.func("block_" + name), envenv),801+ block,802+ 1,803+ )804+ self.indent()805+ self.write_commons()806+ # It's important that we do not make this frame a child of the807+ # toplevel template. This would cause a variety of808+ # interesting issues with identifier tracking.809+ block_frame = Frame(eval_ctx)810+ undeclared = find_undeclared(block.body, ("self", "super"))811+ if "self" in undeclared:812+ ref = block_frame.symbols.declare_parameter("self")813+ self.writeline("%s = TemplateReference(context)" % ref)814+ if "super" in undeclared:815+ ref = block_frame.symbols.declare_parameter("super")816+ self.writeline("%s = context.super(%r, block_%s)" % (ref, name, name))817+ block_frame.symbols.analyze_node(block)818+ block_frame.block = name819+ self.enter_frame(block_frame)820+ self.pull_dependencies(block.body)821+ self.blockvisit(block.body, block_frame)822+ self.leave_frame(block_frame, with_python_scope=True)823+ self.outdent()824+825+ self.writeline(826+ "blocks = {%s}" % ", ".join("%r: block_%s" % (x, x) for x in self.blocks),827+ extra=1,828+ )829+830+ # add a function that returns the debug info831+ self.writeline(832+ "debug_info = %r" % "&".join("%s=%s" % x for x in self.debug_info)833+ )834+835+ def visit_Block(self, node, frame):836+ """Call a block and register it for the template."""837+ level = 0838+ if frame.toplevel:839+ # if we know that we are a child template, there is no need to840+ # check if we are one841+ if self.has_known_extends:842+ return843+ if self.extends_so_far > 0:844+ self.writeline("if parent_template is None:")845+ self.indent()846+ level += 1847+848+ if node.scoped:849+ context = self.derive_context(frame)850+ else:851+ context = self.get_context_ref()852+853+ if (854+ supports_yield_from855+ and not self.environment.is_async856+ and frame.buffer is None857+ ):858+ self.writeline(859+ "yield from context.blocks[%r][0](%s)" % (node.name, context), node860+ )861+ else:862+ loop = self.environment.is_async and "async for" or "for"863+ self.writeline(864+ "%s event in context.blocks[%r][0](%s):" % (loop, node.name, context),865+ node,866+ )867+ self.indent()868+ self.simple_write("event", frame)869+ self.outdent()870+871+ self.outdent(level)872+873+ def visit_Extends(self, node, frame):874+ """Calls the extender."""875+ if not frame.toplevel:876+ self.fail("cannot use extend from a non top-level scope", node.lineno)877+878+ # if the number of extends statements in general is zero so879+ # far, we don't have to add a check if something extended880+ # the template before this one.881+ if self.extends_so_far > 0:882+883+ # if we have a known extends we just add a template runtime884+ # error into the generated code. We could catch that at compile885+ # time too, but i welcome it not to confuse users by throwing the886+ # same error at different times just "because we can".887+ if not self.has_known_extends:888+ self.writeline("if parent_template is not None:")889+ self.indent()890+ self.writeline("raise TemplateRuntimeError(%r)" % "extended multiple times")891+892+ # if we have a known extends already we don't need that code here893+ # as we know that the template execution will end here.894+ if self.has_known_extends:895+ raise CompilerExit()896+ else:897+ self.outdent()898+899+ self.writeline("parent_template = environment.get_template(", node)900+ self.visit(node.template, frame)901+ self.write(", %r)" % self.name)902+ self.writeline(903+ "for name, parent_block in parent_template.blocks.%s():" % dict_item_iter904+ )905+ self.indent()906+ self.writeline("context.blocks.setdefault(name, []).append(parent_block)")907+ self.outdent()908+909+ # if this extends statement was in the root level we can take910+ # advantage of that information and simplify the generated code911+ # in the top level from this point onwards912+ if frame.rootlevel:913+ self.has_known_extends = True914+915+ # and now we have one more916+ self.extends_so_far += 1917+918+ def visit_Include(self, node, frame):919+ """Handles includes."""920+ if node.ignore_missing:921+ self.writeline("try:")922+ self.indent()923+924+ func_name = "get_or_select_template"925+ if isinstance(node.template, nodes.Const):926+ if isinstance(node.template.value, string_types):927+ func_name = "get_template"928+ elif isinstance(node.template.value, (tuple, list)):929+ func_name = "select_template"930+ elif isinstance(node.template, (nodes.Tuple, nodes.List)):931+ func_name = "select_template"932+933+ self.writeline("template = environment.%s(" % func_name, node)934+ self.visit(node.template, frame)935+ self.write(", %r)" % self.name)936+ if node.ignore_missing:937+ self.outdent()938+ self.writeline("except TemplateNotFound:")939+ self.indent()940+ self.writeline("pass")941+ self.outdent()942+ self.writeline("else:")943+ self.indent()944+945+ skip_event_yield = False946+ if node.with_context:947+ loop = self.environment.is_async and "async for" or "for"948+ self.writeline(949+ "%s event in template.root_render_func("950+ "template.new_context(context.get_all(), True, "951+ "%s)):" % (loop, self.dump_local_context(frame))952+ )953+ elif self.environment.is_async:954+ self.writeline(955+ "for event in (await "956+ "template._get_default_module_async())"957+ "._body_stream:"958+ )959+ else:960+ if supports_yield_from:961+ self.writeline("yield from template._get_default_module()._body_stream")962+ skip_event_yield = True963+ else:964+ self.writeline(965+ "for event in template._get_default_module()._body_stream:"966+ )967+968+ if not skip_event_yield:969+ self.indent()970+ self.simple_write("event", frame)971+ self.outdent()972+973+ if node.ignore_missing:974+ self.outdent()975+976+ def visit_Import(self, node, frame):977+ """Visit regular imports."""978+ self.writeline("%s = " % frame.symbols.ref(node.target), node)979+ if frame.toplevel:980+ self.write("context.vars[%r] = " % node.target)981+ if self.environment.is_async:982+ self.write("await ")983+ self.write("environment.get_template(")984+ self.visit(node.template, frame)985+ self.write(", %r)." % self.name)986+ if node.with_context:987+ self.write(988+ "make_module%s(context.get_all(), True, %s)"989+ % (990+ self.environment.is_async and "_async" or "",991+ self.dump_local_context(frame),992+ )993+ )994+ elif self.environment.is_async:995+ self.write("_get_default_module_async()")996+ else:997+ self.write("_get_default_module()")998+ if frame.toplevel and not node.target.startswith("_"):999+ self.writeline("context.exported_vars.discard(%r)" % node.target)1000+1001+ def visit_FromImport(self, node, frame):1002+ """Visit named imports."""1003+ self.newline(node)1004+ self.write(1005+ "included_template = %senvironment.get_template("1006+ % (self.environment.is_async and "await " or "")1007+ )1008+ self.visit(node.template, frame)1009+ self.write(", %r)." % self.name)1010+ if node.with_context:1011+ self.write(1012+ "make_module%s(context.get_all(), True, %s)"1013+ % (1014+ self.environment.is_async and "_async" or "",1015+ self.dump_local_context(frame),1016+ )1017+ )1018+ elif self.environment.is_async:1019+ self.write("_get_default_module_async()")1020+ else:1021+ self.write("_get_default_module()")1022+1023+ var_names = []1024+ discarded_names = []1025+ for name in node.names:1026+ if isinstance(name, tuple):1027+ name, alias = name1028+ else:1029+ alias = name1030+ self.writeline(1031+ "%s = getattr(included_template, "1032+ "%r, missing)" % (frame.symbols.ref(alias), name)1033+ )1034+ self.writeline("if %s is missing:" % frame.symbols.ref(alias))1035+ self.indent()1036+ self.writeline(1037+ "%s = undefined(%r %% "1038+ "included_template.__name__, "1039+ "name=%r)"1040+ % (1041+ frame.symbols.ref(alias),1042+ "the template %%r (imported on %s) does "1043+ "not export the requested name %s"1044+ % (self.position(node), repr(name)),1045+ name,1046+ )1047+ )1048+ self.outdent()1049+ if frame.toplevel:1050+ var_names.append(alias)1051+ if not alias.startswith("_"):1052+ discarded_names.append(alias)1053+1054+ if var_names:1055+ if len(var_names) == 1:1056+ name = var_names[0]1057+ self.writeline(1058+ "context.vars[%r] = %s" % (name, frame.symbols.ref(name))1059+ )1060+ else:1061+ self.writeline(1062+ "context.vars.update({%s})"1063+ % ", ".join(1064+ "%r: %s" % (name, frame.symbols.ref(name)) for name in var_names1065+ )1066+ )1067+ if discarded_names:1068+ if len(discarded_names) == 1:1069+ self.writeline("context.exported_vars.discard(%r)" % discarded_names[0])1070+ else:1071+ self.writeline(1072+ "context.exported_vars.difference_"1073+ "update((%s))" % ", ".join(imap(repr, discarded_names))1074+ )1075+1076+ def visit_For(self, node, frame):1077+ loop_frame = frame.inner()1078+ test_frame = frame.inner()1079+ else_frame = frame.inner()1080+1081+ # try to figure out if we have an extended loop. An extended loop1082+ # is necessary if the loop is in recursive mode if the special loop1083+ # variable is accessed in the body.1084+ extended_loop = node.recursive or "loop" in find_undeclared(1085+ node.iter_child_nodes(only=("body",)), ("loop",)1086+ )1087+1088+ loop_ref = None1089+ if extended_loop:1090+ loop_ref = loop_frame.symbols.declare_parameter("loop")1091+1092+ loop_frame.symbols.analyze_node(node, for_branch="body")1093+ if node.else_:1094+ else_frame.symbols.analyze_node(node, for_branch="else")1095+1096+ if node.test:1097+ loop_filter_func = self.temporary_identifier()1098+ test_frame.symbols.analyze_node(node, for_branch="test")1099+ self.writeline("%s(fiter):" % self.func(loop_filter_func), node.test)1100+ self.indent()1101+ self.enter_frame(test_frame)1102+ self.writeline(self.environment.is_async and "async for " or "for ")1103+ self.visit(node.target, loop_frame)1104+ self.write(" in ")1105+ self.write(self.environment.is_async and "auto_aiter(fiter)" or "fiter")1106+ self.write(":")1107+ self.indent()1108+ self.writeline("if ", node.test)1109+ self.visit(node.test, test_frame)1110+ self.write(":")1111+ self.indent()1112+ self.writeline("yield ")1113+ self.visit(node.target, loop_frame)1114+ self.outdent(3)1115+ self.leave_frame(test_frame, with_python_scope=True)1116+1117+ # if we don't have an recursive loop we have to find the shadowed1118+ # variables at that point. Because loops can be nested but the loop1119+ # variable is a special one we have to enforce aliasing for it.1120+ if node.recursive:1121+ self.writeline(1122+ "%s(reciter, loop_render_func, depth=0):" % self.func("loop"), node1123+ )1124+ self.indent()1125+ self.buffer(loop_frame)1126+1127+ # Use the same buffer for the else frame1128+ else_frame.buffer = loop_frame.buffer1129+1130+ # make sure the loop variable is a special one and raise a template1131+ # assertion error if a loop tries to write to loop1132+ if extended_loop:1133+ self.writeline("%s = missing" % loop_ref)1134+1135+ for name in node.find_all(nodes.Name):1136+ if name.ctx == "store" and name.name == "loop":1137+ self.fail(1138+ "Can't assign to special loop variable in for-loop target",1139+ name.lineno,1140+ )1141+1142+ if node.else_:1143+ iteration_indicator = self.temporary_identifier()1144+ self.writeline("%s = 1" % iteration_indicator)1145+1146+ self.writeline(self.environment.is_async and "async for " or "for ", node)1147+ self.visit(node.target, loop_frame)1148+ if extended_loop:1149+ if self.environment.is_async:1150+ self.write(", %s in AsyncLoopContext(" % loop_ref)1151+ else:1152+ self.write(", %s in LoopContext(" % loop_ref)1153+ else:1154+ self.write(" in ")1155+1156+ if node.test:1157+ self.write("%s(" % loop_filter_func)1158+ if node.recursive:1159+ self.write("reciter")1160+ else:1161+ if self.environment.is_async and not extended_loop:1162+ self.write("auto_aiter(")1163+ self.visit(node.iter, frame)1164+ if self.environment.is_async and not extended_loop:1165+ self.write(")")1166+ if node.test:1167+ self.write(")")1168+1169+ if node.recursive:1170+ self.write(", undefined, loop_render_func, depth):")1171+ else:1172+ self.write(extended_loop and ", undefined):" or ":")1173+1174+ self.indent()1175+ self.enter_frame(loop_frame)1176+1177+ self.blockvisit(node.body, loop_frame)1178+ if node.else_:1179+ self.writeline("%s = 0" % iteration_indicator)1180+ self.outdent()1181+ self.leave_frame(1182+ loop_frame, with_python_scope=node.recursive and not node.else_1183+ )1184+1185+ if node.else_:1186+ self.writeline("if %s:" % iteration_indicator)1187+ self.indent()1188+ self.enter_frame(else_frame)1189+ self.blockvisit(node.else_, else_frame)1190+ self.leave_frame(else_frame)1191+ self.outdent()1192+1193+ # if the node was recursive we have to return the buffer contents1194+ # and start the iteration code1195+ if node.recursive:1196+ self.return_buffer_contents(loop_frame)1197+ self.outdent()1198+ self.start_write(frame, node)1199+ if self.environment.is_async:1200+ self.write("await ")1201+ self.write("loop(")1202+ if self.environment.is_async:1203+ self.write("auto_aiter(")1204+ self.visit(node.iter, frame)1205+ if self.environment.is_async:1206+ self.write(")")1207+ self.write(", loop)")1208+ self.end_write(frame)1209+1210+ def visit_If(self, node, frame):1211+ if_frame = frame.soft()1212+ self.writeline("if ", node)1213+ self.visit(node.test, if_frame)1214+ self.write(":")1215+ self.indent()1216+ self.blockvisit(node.body, if_frame)1217+ self.outdent()1218+ for elif_ in node.elif_:1219+ self.writeline("elif ", elif_)1220+ self.visit(elif_.test, if_frame)1221+ self.write(":")1222+ self.indent()1223+ self.blockvisit(elif_.body, if_frame)1224+ self.outdent()1225+ if node.else_:1226+ self.writeline("else:")1227+ self.indent()1228+ self.blockvisit(node.else_, if_frame)1229+ self.outdent()1230+1231+ def visit_Macro(self, node, frame):1232+ macro_frame, macro_ref = self.macro_body(node, frame)1233+ self.newline()1234+ if frame.toplevel:1235+ if not node.name.startswith("_"):1236+ self.write("context.exported_vars.add(%r)" % node.name)1237+ self.writeline("context.vars[%r] = " % node.name)1238+ self.write("%s = " % frame.symbols.ref(node.name))1239+ self.macro_def(macro_ref, macro_frame)1240+1241+ def visit_CallBlock(self, node, frame):1242+ call_frame, macro_ref = self.macro_body(node, frame)1243+ self.writeline("caller = ")1244+ self.macro_def(macro_ref, call_frame)1245+ self.start_write(frame, node)1246+ self.visit_Call(node.call, frame, forward_caller=True)1247+ self.end_write(frame)1248+1249+ def visit_FilterBlock(self, node, frame):1250+ filter_frame = frame.inner()1251+ filter_frame.symbols.analyze_node(node)1252+ self.enter_frame(filter_frame)1253+ self.buffer(filter_frame)1254+ self.blockvisit(node.body, filter_frame)1255+ self.start_write(frame, node)1256+ self.visit_Filter(node.filter, filter_frame)1257+ self.end_write(frame)1258+ self.leave_frame(filter_frame)1259+1260+ def visit_With(self, node, frame):1261+ with_frame = frame.inner()1262+ with_frame.symbols.analyze_node(node)1263+ self.enter_frame(with_frame)1264+ for target, expr in izip(node.targets, node.values):1265+ self.newline()1266+ self.visit(target, with_frame)1267+ self.write(" = ")1268+ self.visit(expr, frame)1269+ self.blockvisit(node.body, with_frame)1270+ self.leave_frame(with_frame)1271+1272+ def visit_ExprStmt(self, node, frame):1273+ self.newline(node)1274+ self.visit(node.node, frame)1275+1276+ _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1277+ #: The default finalize function if the environment isn't configured1278+ #: with one. Or if the environment has one, this is called on that1279+ #: function's output for constants.1280+ _default_finalize = text_type1281+ _finalize = None1282+1283+ def _make_finalize(self):1284+ """Build the finalize function to be used on constants and at1285+ runtime. Cached so it's only created once for all output nodes.1286+1287+ Returns a ``namedtuple`` with the following attributes:1288+1289+ ``const``1290+ A function to finalize constant data at compile time.1291+1292+ ``src``1293+ Source code to output around nodes to be evaluated at1294+ runtime.1295+ """1296+ if self._finalize is not None:1297+ return self._finalize1298+1299+ finalize = default = self._default_finalize1300+ src = None1301+1302+ if self.environment.finalize:1303+ src = "environment.finalize("1304+ env_finalize = self.environment.finalize1305+1306+ def finalize(value):1307+ return default(env_finalize(value))1308+1309+ if getattr(env_finalize, "contextfunction", False):1310+ src += "context, "1311+ finalize = None # noqa: F8111312+ elif getattr(env_finalize, "evalcontextfunction", False):1313+ src += "context.eval_ctx, "1314+ finalize = None1315+ elif getattr(env_finalize, "environmentfunction", False):1316+ src += "environment, "1317+1318+ def finalize(value):1319+ return default(env_finalize(self.environment, value))1320+1321+ self._finalize = self._FinalizeInfo(finalize, src)1322+ return self._finalize1323+1324+ def _output_const_repr(self, group):1325+ """Given a group of constant values converted from ``Output``1326+ child nodes, produce a string to write to the template module1327+ source.1328+ """1329+ return repr(concat(group))1330+1331+ def _output_child_to_const(self, node, frame, finalize):1332+ """Try to optimize a child of an ``Output`` node by trying to1333+ convert it to constant, finalized data at compile time.1334+1335+ If :exc:`Impossible` is raised, the node is not constant and1336+ will be evaluated at runtime. Any other exception will also be1337+ evaluated at runtime for easier debugging.1338+ """1339+ const = node.as_const(frame.eval_ctx)1340+1341+ if frame.eval_ctx.autoescape:1342+ const = escape(const)1343+1344+ # Template data doesn't go through finalize.1345+ if isinstance(node, nodes.TemplateData):1346+ return text_type(const)1347+1348+ return finalize.const(const)1349+1350+ def _output_child_pre(self, node, frame, finalize):1351+ """Output extra source code before visiting a child of an1352+ ``Output`` node.1353+ """1354+ if frame.eval_ctx.volatile:1355+ self.write("(escape if context.eval_ctx.autoescape else to_string)(")1356+ elif frame.eval_ctx.autoescape:1357+ self.write("escape(")1358+ else:1359+ self.write("to_string(")1360+1361+ if finalize.src is not None:1362+ self.write(finalize.src)1363+1364+ def _output_child_post(self, node, frame, finalize):1365+ """Output extra source code after visiting a child of an1366+ ``Output`` node.1367+ """1368+ self.write(")")1369+1370+ if finalize.src is not None:1371+ self.write(")")1372+1373+ def visit_Output(self, node, frame):1374+ # If an extends is active, don't render outside a block.1375+ if frame.require_output_check:1376+ # A top-level extends is known to exist at compile time.1377+ if self.has_known_extends:1378+ return1379+1380+ self.writeline("if parent_template is None:")1381+ self.indent()1382+1383+ finalize = self._make_finalize()1384+ body = []1385+1386+ # Evaluate constants at compile time if possible. Each item in1387+ # body will be either a list of static data or a node to be1388+ # evaluated at runtime.1389+ for child in node.nodes:1390+ try:1391+ if not (1392+ # If the finalize function requires runtime context,1393+ # constants can't be evaluated at compile time.1394+ finalize.const1395+ # Unless it's basic template data that won't be1396+ # finalized anyway.1397+ or isinstance(child, nodes.TemplateData)1398+ ):1399+ raise nodes.Impossible()1400+1401+ const = self._output_child_to_const(child, frame, finalize)1402+ except (nodes.Impossible, Exception):1403+ # The node was not constant and needs to be evaluated at1404+ # runtime. Or another error was raised, which is easier1405+ # to debug at runtime.1406+ body.append(child)1407+ continue1408+1409+ if body and isinstance(body[-1], list):1410+ body[-1].append(const)1411+ else:1412+ body.append([const])1413+1414+ if frame.buffer is not None:1415+ if len(body) == 1:1416+ self.writeline("%s.append(" % frame.buffer)1417+ else:1418+ self.writeline("%s.extend((" % frame.buffer)1419+1420+ self.indent()1421+1422+ for item in body:1423+ if isinstance(item, list):1424+ # A group of constant data to join and output.1425+ val = self._output_const_repr(item)1426+1427+ if frame.buffer is None:1428+ self.writeline("yield " + val)1429+ else:1430+ self.writeline(val + ",")1431+ else:1432+ if frame.buffer is None:1433+ self.writeline("yield ", item)1434+ else:1435+ self.newline(item)1436+1437+ # A node to be evaluated at runtime.1438+ self._output_child_pre(item, frame, finalize)1439+ self.visit(item, frame)1440+ self._output_child_post(item, frame, finalize)1441+1442+ if frame.buffer is not None:1443+ self.write(",")1444+1445+ if frame.buffer is not None:1446+ self.outdent()1447+ self.writeline(")" if len(body) == 1 else "))")1448+1449+ if frame.require_output_check:1450+ self.outdent()1451+1452+ def visit_Assign(self, node, frame):1453+ self.push_assign_tracking()1454+ self.newline(node)1455+ self.visit(node.target, frame)1456+ self.write(" = ")1457+ self.visit(node.node, frame)1458+ self.pop_assign_tracking(frame)1459+1460+ def visit_AssignBlock(self, node, frame):1461+ self.push_assign_tracking()1462+ block_frame = frame.inner()1463+ # This is a special case. Since a set block always captures we1464+ # will disable output checks. This way one can use set blocks1465+ # toplevel even in extended templates.1466+ block_frame.require_output_check = False1467+ block_frame.symbols.analyze_node(node)1468+ self.enter_frame(block_frame)1469+ self.buffer(block_frame)1470+ self.blockvisit(node.body, block_frame)1471+ self.newline(node)1472+ self.visit(node.target, frame)1473+ self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")1474+ if node.filter is not None:1475+ self.visit_Filter(node.filter, block_frame)1476+ else:1477+ self.write("concat(%s)" % block_frame.buffer)1478+ self.write(")")1479+ self.pop_assign_tracking(frame)1480+ self.leave_frame(block_frame)1481+1482+ # -- Expression Visitors1483+1484+ def visit_Name(self, node, frame):1485+ if node.ctx == "store" and frame.toplevel:1486+ if self._assign_stack:1487+ self._assign_stack[-1].add(node.name)1488+ ref = frame.symbols.ref(node.name)1489+1490+ # If we are looking up a variable we might have to deal with the1491+ # case where it's undefined. We can skip that case if the load1492+ # instruction indicates a parameter which are always defined.1493+ if node.ctx == "load":1494+ load = frame.symbols.find_load(ref)1495+ if not (1496+ load is not None1497+ and load[0] == VAR_LOAD_PARAMETER1498+ and not self.parameter_is_undeclared(ref)1499+ ):1500+ self.write(1501+ "(undefined(name=%r) if %s is missing else %s)"1502+ % (node.name, ref, ref)1503+ )1504+ return1505+1506+ self.write(ref)1507+1508+ def visit_NSRef(self, node, frame):1509+ # NSRefs can only be used to store values; since they use the normal1510+ # `foo.bar` notation they will be parsed as a normal attribute access1511+ # when used anywhere but in a `set` context1512+ ref = frame.symbols.ref(node.name)1513+ self.writeline("if not isinstance(%s, Namespace):" % ref)1514+ self.indent()1515+ self.writeline(1516+ "raise TemplateRuntimeError(%r)"1517+ % "cannot assign attribute on non-namespace object"1518+ )1519+ self.outdent()1520+ self.writeline("%s[%r]" % (ref, node.attr))1521+1522+ def visit_Const(self, node, frame):1523+ val = node.as_const(frame.eval_ctx)1524+ if isinstance(val, float):1525+ self.write(str(val))1526+ else:1527+ self.write(repr(val))1528+1529+ def visit_TemplateData(self, node, frame):1530+ try:1531+ self.write(repr(node.as_const(frame.eval_ctx)))1532+ except nodes.Impossible:1533+ self.write(1534+ "(Markup if context.eval_ctx.autoescape else identity)(%r)" % node.data1535+ )1536+1537+ def visit_Tuple(self, node, frame):1538+ self.write("(")1539+ idx = -11540+ for idx, item in enumerate(node.items):1541+ if idx:1542+ self.write(", ")1543+ self.visit(item, frame)1544+ self.write(idx == 0 and ",)" or ")")1545+1546+ def visit_List(self, node, frame):1547+ self.write("[")1548+ for idx, item in enumerate(node.items):1549+ if idx:1550+ self.write(", ")1551+ self.visit(item, frame)1552+ self.write("]")1553+1554+ def visit_Dict(self, node, frame):1555+ self.write("{")1556+ for idx, item in enumerate(node.items):1557+ if idx:1558+ self.write(", ")1559+ self.visit(item.key, frame)1560+ self.write(": ")1561+ self.visit(item.value, frame)1562+ self.write("}")1563+1564+ def binop(operator, interceptable=True): # noqa: B9021565+ @optimizeconst1566+ def visitor(self, node, frame):1567+ if (1568+ self.environment.sandboxed1569+ and operator in self.environment.intercepted_binops1570+ ):1571+ self.write("environment.call_binop(context, %r, " % operator)1572+ self.visit(node.left, frame)1573+ self.write(", ")1574+ self.visit(node.right, frame)1575+ else:1576+ self.write("(")1577+ self.visit(node.left, frame)1578+ self.write(" %s " % operator)1579+ self.visit(node.right, frame)1580+ self.write(")")1581+1582+ return visitor1583+1584+ def uaop(operator, interceptable=True): # noqa: B9021585+ @optimizeconst1586+ def visitor(self, node, frame):1587+ if (1588+ self.environment.sandboxed1589+ and operator in self.environment.intercepted_unops1590+ ):1591+ self.write("environment.call_unop(context, %r, " % operator)1592+ self.visit(node.node, frame)1593+ else:1594+ self.write("(" + operator)1595+ self.visit(node.node, frame)1596+ self.write(")")1597+1598+ return visitor1599+1600+ visit_Add = binop("+")1601+ visit_Sub = binop("-")1602+ visit_Mul = binop("*")1603+ visit_Div = binop("/")1604+ visit_FloorDiv = binop("//")1605+ visit_Pow = binop("**")1606+ visit_Mod = binop("%")1607+ visit_And = binop("and", interceptable=False)1608+ visit_Or = binop("or", interceptable=False)1609+ visit_Pos = uaop("+")1610+ visit_Neg = uaop("-")1611+ visit_Not = uaop("not ", interceptable=False)1612+ del binop, uaop1613+1614+ @optimizeconst1615+ def visit_Concat(self, node, frame):1616+ if frame.eval_ctx.volatile:1617+ func_name = "(context.eval_ctx.volatile and markup_join or unicode_join)"1618+ elif frame.eval_ctx.autoescape:1619+ func_name = "markup_join"1620+ else:1621+ func_name = "unicode_join"1622+ self.write("%s((" % func_name)1623+ for arg in node.nodes:1624+ self.visit(arg, frame)1625+ self.write(", ")1626+ self.write("))")1627+1628+ @optimizeconst1629+ def visit_Compare(self, node, frame):1630+ self.write("(")1631+ self.visit(node.expr, frame)1632+ for op in node.ops:1633+ self.visit(op, frame)1634+ self.write(")")1635+1636+ def visit_Operand(self, node, frame):1637+ self.write(" %s " % operators[node.op])1638+ self.visit(node.expr, frame)1639+1640+ @optimizeconst1641+ def visit_Getattr(self, node, frame):1642+ if self.environment.is_async:1643+ self.write("await auto_await(")1644+1645+ self.write("environment.getattr(")1646+ self.visit(node.node, frame)1647+ self.write(", %r)" % node.attr)1648+1649+ if self.environment.is_async:1650+ self.write(")")1651+1652+ @optimizeconst1653+ def visit_Getitem(self, node, frame):1654+ # slices bypass the environment getitem method.1655+ if isinstance(node.arg, nodes.Slice):1656+ self.visit(node.node, frame)1657+ self.write("[")1658+ self.visit(node.arg, frame)1659+ self.write("]")1660+ else:1661+ if self.environment.is_async:1662+ self.write("await auto_await(")1663+1664+ self.write("environment.getitem(")1665+ self.visit(node.node, frame)1666+ self.write(", ")1667+ self.visit(node.arg, frame)1668+ self.write(")")1669+1670+ if self.environment.is_async:1671+ self.write(")")1672+1673+ def visit_Slice(self, node, frame):1674+ if node.start is not None:1675+ self.visit(node.start, frame)1676+ self.write(":")1677+ if node.stop is not None:1678+ self.visit(node.stop, frame)1679+ if node.step is not None:1680+ self.write(":")1681+ self.visit(node.step, frame)1682+1683+ @optimizeconst1684+ def visit_Filter(self, node, frame):1685+ if self.environment.is_async:1686+ self.write("await auto_await(")1687+ self.write(self.filters[node.name] + "(")1688+ func = self.environment.filters.get(node.name)1689+ if func is None:1690+ self.fail("no filter named %r" % node.name, node.lineno)1691+ if getattr(func, "contextfilter", False):1692+ self.write("context, ")1693+ elif getattr(func, "evalcontextfilter", False):1694+ self.write("context.eval_ctx, ")1695+ elif getattr(func, "environmentfilter", False):1696+ self.write("environment, ")1697+1698+ # if the filter node is None we are inside a filter block1699+ # and want to write to the current buffer1700+ if node.node is not None:1701+ self.visit(node.node, frame)1702+ elif frame.eval_ctx.volatile:1703+ self.write(1704+ "(context.eval_ctx.autoescape and"1705+ " Markup(concat(%s)) or concat(%s))" % (frame.buffer, frame.buffer)1706+ )1707+ elif frame.eval_ctx.autoescape:1708+ self.write("Markup(concat(%s))" % frame.buffer)1709+ else:1710+ self.write("concat(%s)" % frame.buffer)1711+ self.signature(node, frame)1712+ self.write(")")1713+ if self.environment.is_async:1714+ self.write(")")1715+1716+ @optimizeconst1717+ def visit_Test(self, node, frame):1718+ self.write(self.tests[node.name] + "(")1719+ if node.name not in self.environment.tests:1720+ self.fail("no test named %r" % node.name, node.lineno)1721+ self.visit(node.node, frame)1722+ self.signature(node, frame)1723+ self.write(")")1724+1725+ @optimizeconst1726+ def visit_CondExpr(self, node, frame):1727+ def write_expr2():1728+ if node.expr2 is not None:1729+ return self.visit(node.expr2, frame)1730+ self.write(1731+ "cond_expr_undefined(%r)"1732+ % (1733+ "the inline if-"1734+ "expression on %s evaluated to false and "1735+ "no else section was defined." % self.position(node)1736+ )1737+ )1738+1739+ self.write("(")1740+ self.visit(node.expr1, frame)1741+ self.write(" if ")1742+ self.visit(node.test, frame)1743+ self.write(" else ")1744+ write_expr2()1745+ self.write(")")1746+1747+ @optimizeconst1748+ def visit_Call(self, node, frame, forward_caller=False):1749+ if self.environment.is_async:1750+ self.write("await auto_await(")1751+ if self.environment.sandboxed:1752+ self.write("environment.call(context, ")1753+ else:1754+ self.write("context.call(")1755+ self.visit(node.node, frame)1756+ extra_kwargs = forward_caller and {"caller": "caller"} or None1757+ self.signature(node, frame, extra_kwargs)1758+ self.write(")")1759+ if self.environment.is_async:1760+ self.write(")")1761+1762+ def visit_Keyword(self, node, frame):1763+ self.write(node.key + "=")1764+ self.visit(node.value, frame)1765+1766+ # -- Unused nodes for extensions1767+1768+ def visit_MarkSafe(self, node, frame):1769+ self.write("Markup(")1770+ self.visit(node.expr, frame)1771+ self.write(")")1772+1773+ def visit_MarkSafeIfAutoescape(self, node, frame):1774+ self.write("(context.eval_ctx.autoescape and Markup or identity)(")1775+ self.visit(node.expr, frame)1776+ self.write(")")1777+1778+ def visit_EnvironmentAttribute(self, node, frame):1779+ self.write("environment." + node.name)1780+1781+ def visit_ExtensionAttribute(self, node, frame):1782+ self.write("environment.extensions[%r].%s" % (node.identifier, node.name))1783+1784+ def visit_ImportedName(self, node, frame):1785+ self.write(self.import_aliases[node.importname])1786+1787+ def visit_InternalName(self, node, frame):1788+ self.write(node.name)1789+1790+ def visit_ContextReference(self, node, frame):1791+ self.write("context")1792+1793+ def visit_DerivedContextReference(self, node, frame):1794+ self.write(self.derive_context(frame))1795+1796+ def visit_Continue(self, node, frame):1797+ self.writeline("continue", node)1798+1799+ def visit_Break(self, node, frame):1800+ self.writeline("break", node)1801+1802+ def visit_Scope(self, node, frame):1803+ scope_frame = frame.inner()1804+ scope_frame.symbols.analyze_node(node)1805+ self.enter_frame(scope_frame)1806+ self.blockvisit(node.body, scope_frame)1807+ self.leave_frame(scope_frame)1808+1809+ def visit_OverlayScope(self, node, frame):1810+ ctx = self.temporary_identifier()1811+ self.writeline("%s = %s" % (ctx, self.derive_context(frame)))1812+ self.writeline("%s.vars = " % ctx)1813+ self.visit(node.context, frame)1814+ self.push_context_reference(ctx)1815+1816+ scope_frame = frame.inner(isolated=True)1817+ scope_frame.symbols.analyze_node(node)1818+ self.enter_frame(scope_frame)1819+ self.blockvisit(node.body, scope_frame)1820+ self.leave_frame(scope_frame)1821+ self.pop_context_reference()1822+1823+ def visit_EvalContextModifier(self, node, frame):1824+ for keyword in node.options:1825+ self.writeline("context.eval_ctx.%s = " % keyword.key)1826+ self.visit(keyword.value, frame)1827+ try:1828+ val = keyword.value.as_const(frame.eval_ctx)1829+ except nodes.Impossible:1830+ frame.eval_ctx.volatile = True1831+ else:1832+ setattr(frame.eval_ctx, keyword.key, val)1833+1834+ def visit_ScopedEvalContextModifier(self, node, frame):1835+ old_ctx_name = self.temporary_identifier()1836+ saved_ctx = frame.eval_ctx.save()1837+ self.writeline("%s = context.eval_ctx.save()" % old_ctx_name)1838+ self.visit_EvalContextModifier(node, frame)1839+ for child in node.body:1840+ self.visit(child, frame)1841+ frame.eval_ctx.revert(saved_ctx)1842+ self.writeline("context.eval_ctx.revert(%s)" % old_ctx_name)added:src/jinja/constants.py+21 added
1+# -*- coding: utf-8 -*-2+#: list of lorem ipsum words used by the lipsum() helper function3+LOREM_IPSUM_WORDS = u"""\4+a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at5+auctor augue bibendum blandit class commodo condimentum congue consectetuer6+consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus7+diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend8+elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames9+faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac10+hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum11+justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem12+luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie13+mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non14+nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque15+penatibus per pharetra phasellus placerat platea porta porttitor posuere16+potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus17+ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit18+sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor19+tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices20+ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus21+viverra volutpat vulputate"""added:src/jinja/debug.py+271 added
1+import sys2+from types import CodeType3+4+from . import TemplateSyntaxError5+from ._compat import PYPY6+from .utils import internal_code7+from .utils import missing8+9+10+def rewrite_traceback_stack(source=None):11+ """Rewrite the current exception to replace any tracebacks from12+ within compiled template code with tracebacks that look like they13+ came from the template source.14+15+ This must be called within an ``except`` block.16+17+ :param exc_info: A :meth:`sys.exc_info` tuple. If not provided,18+ the current ``exc_info`` is used.19+ :param source: For ``TemplateSyntaxError``, the original source if20+ known.21+ :return: A :meth:`sys.exc_info` tuple that can be re-raised.22+ """23+ exc_type, exc_value, tb = sys.exc_info()24+25+ if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:26+ exc_value.translated = True27+ exc_value.source = source28+29+ try:30+ # Remove the old traceback on Python 3, otherwise the frames31+ # from the compiler still show up.32+ exc_value.with_traceback(None)33+ except AttributeError:34+ pass35+36+ # Outside of runtime, so the frame isn't executing template37+ # code, but it still needs to point at the template.38+ tb = fake_traceback(39+ exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno40+ )41+ else:42+ # Skip the frame for the render function.43+ tb = tb.tb_next44+45+ stack = []46+47+ # Build the stack of traceback object, replacing any in template48+ # code with the source file and line information.49+ while tb is not None:50+ # Skip frames decorated with @internalcode. These are internal51+ # calls that aren't useful in template debugging output.52+ if tb.tb_frame.f_code in internal_code:53+ tb = tb.tb_next54+ continue55+56+ template = tb.tb_frame.f_globals.get("__jinja_template__")57+58+ if template is not None:59+ lineno = template.get_corresponding_lineno(tb.tb_lineno)60+ fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)61+ stack.append(fake_tb)62+ else:63+ stack.append(tb)64+65+ tb = tb.tb_next66+67+ tb_next = None68+69+ # Assign tb_next in reverse to avoid circular references.70+ for tb in reversed(stack):71+ tb_next = tb_set_next(tb, tb_next)72+73+ return exc_type, exc_value, tb_next74+75+76+def fake_traceback(exc_value, tb, filename, lineno):77+ """Produce a new traceback object that looks like it came from the78+ template source instead of the compiled code. The filename, line79+ number, and location name will point to the template, and the local80+ variables will be the current template context.81+82+ :param exc_value: The original exception to be re-raised to create83+ the new traceback.84+ :param tb: The original traceback to get the local variables and85+ code info from.86+ :param filename: The template filename.87+ :param lineno: The line number in the template source.88+ """89+ if tb is not None:90+ # Replace the real locals with the context that would be91+ # available at that point in the template.92+ locals = get_template_locals(tb.tb_frame.f_locals)93+ locals.pop("__jinja_exception__", None)94+ else:95+ locals = {}96+97+ globals = {98+ "__name__": filename,99+ "__file__": filename,100+ "__jinja_exception__": exc_value,101+ }102+ # Raise an exception at the correct line number.103+ code = compile("\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec")104+105+ # Build a new code object that points to the template file and106+ # replaces the location with a block name.107+ try:108+ location = "template"109+110+ if tb is not None:111+ function = tb.tb_frame.f_code.co_name112+113+ if function == "root":114+ location = "top-level template code"115+ elif function.startswith("block_"):116+ location = 'block "%s"' % function[6:]117+118+ # Collect arguments for the new code object. CodeType only119+ # accepts positional arguments, and arguments were inserted in120+ # new Python versions.121+ code_args = []122+123+ for attr in (124+ "argcount",125+ "posonlyargcount", # Python 3.8126+ "kwonlyargcount", # Python 3127+ "nlocals",128+ "stacksize",129+ "flags",130+ "code", # codestring131+ "consts", # constants132+ "names",133+ "varnames",134+ ("filename", filename),135+ ("name", location),136+ "firstlineno",137+ "lnotab",138+ "freevars",139+ "cellvars",140+ ):141+ if isinstance(attr, tuple):142+ # Replace with given value.143+ code_args.append(attr[1])144+ continue145+146+ try:147+ # Copy original value if it exists.148+ code_args.append(getattr(code, "co_" + attr))149+ except AttributeError:150+ # Some arguments were added later.151+ continue152+153+ code = CodeType(*code_args)154+ except Exception:155+ # Some environments such as Google App Engine don't support156+ # modifying code objects.157+ pass158+159+ # Execute the new code, which is guaranteed to raise, and return160+ # the new traceback without this frame.161+ try:162+ exec(code, globals, locals)163+ except BaseException:164+ return sys.exc_info()[2].tb_next165+166+167+def get_template_locals(real_locals):168+ """Based on the runtime locals, get the context that would be169+ available at that point in the template.170+ """171+ # Start with the current template context.172+ ctx = real_locals.get("context")173+174+ if ctx:175+ data = ctx.get_all().copy()176+ else:177+ data = {}178+179+ # Might be in a derived context that only sets local variables180+ # rather than pushing a context. Local variables follow the scheme181+ # l_depth_name. Find the highest-depth local that has a value for182+ # each name.183+ local_overrides = {}184+185+ for name, value in real_locals.items():186+ if not name.startswith("l_") or value is missing:187+ # Not a template variable, or no longer relevant.188+ continue189+190+ try:191+ _, depth, name = name.split("_", 2)192+ depth = int(depth)193+ except ValueError:194+ continue195+196+ cur_depth = local_overrides.get(name, (-1,))[0]197+198+ if cur_depth < depth:199+ local_overrides[name] = (depth, value)200+201+ # Modify the context with any derived context.202+ for name, (_, value) in local_overrides.items():203+ if value is missing:204+ data.pop(name, None)205+ else:206+ data[name] = value207+208+ return data209+210+211+if sys.version_info >= (3, 7):212+ # tb_next is directly assignable as of Python 3.7213+ def tb_set_next(tb, tb_next):214+ tb.tb_next = tb_next215+ return tb216+217+218+elif PYPY:219+ # PyPy might have special support, and won't work with ctypes.220+ try:221+ import tputil222+ except ImportError:223+ # Without tproxy support, use the original traceback.224+ def tb_set_next(tb, tb_next):225+ return tb226+227+ else:228+ # With tproxy support, create a proxy around the traceback that229+ # returns the new tb_next.230+ def tb_set_next(tb, tb_next):231+ def controller(op):232+ if op.opname == "__getattribute__" and op.args[0] == "tb_next":233+ return tb_next234+235+ return op.delegate()236+237+ return tputil.make_proxy(controller, obj=tb)238+239+240+else:241+ # Use ctypes to assign tb_next at the C level since it's read-only242+ # from Python.243+ import ctypes244+245+ class _CTraceback(ctypes.Structure):246+ _fields_ = [247+ # Extra PyObject slots when compiled with Py_TRACE_REFS.248+ (249+ "PyObject_HEAD",250+ ctypes.c_byte * (32 if hasattr(sys, "getobjects") else 16),251+ ),252+ # Only care about tb_next as an object, not a traceback.253+ ("tb_next", ctypes.py_object),254+ ]255+256+ def tb_set_next(tb, tb_next):257+ c_tb = _CTraceback.from_address(id(tb))258+259+ # Clear out the old tb_next.260+ if tb.tb_next is not None:261+ c_tb_next = ctypes.py_object(tb.tb_next)262+ c_tb.tb_next = ctypes.py_object()263+ ctypes.pythonapi.Py_DecRef(c_tb_next)264+265+ # Assign the new tb_next.266+ if tb_next is not None:267+ c_tb_next = ctypes.py_object(tb_next)268+ ctypes.pythonapi.Py_IncRef(c_tb_next)269+ c_tb.tb_next = c_tb_next270+271+ return tbadded:src/jinja/defaults.py+47 added
1+# -*- coding: utf-8 -*-2+from ._compat import range_type3+from .filters import FILTERS as DEFAULT_FILTERS # noqa: F4014+from .tests import TESTS as DEFAULT_TESTS # noqa: F4015+from .utils import Cycler6+from .utils import generate_lorem_ipsum7+from .utils import Joiner8+from .utils import Namespace9+10+# defaults for the parser / lexer11+BLOCK_START_STRING = "{%"12+BLOCK_END_STRING = "%}"13+VARIABLE_START_STRING = "{{"14+VARIABLE_END_STRING = "}}"15+COMMENT_START_STRING = "{#"16+COMMENT_END_STRING = "#}"17+LINE_STATEMENT_PREFIX = None18+LINE_COMMENT_PREFIX = None19+TRIM_BLOCKS = False20+LSTRIP_BLOCKS = False21+NEWLINE_SEQUENCE = "\n"22+KEEP_TRAILING_NEWLINE = False23+24+# default filters, tests and namespace25+26+DEFAULT_NAMESPACE = {27+ "range": range_type,28+ "dict": dict,29+ "lipsum": generate_lorem_ipsum,30+ "cycler": Cycler,31+ "joiner": Joiner,32+ "namespace": Namespace,33+}34+35+# default policies36+DEFAULT_POLICIES = {37+ "compiler.ascii_str": True,38+ "urlize.rel": "noopener",39+ "urlize.target": None,40+ "truncate.leeway": 5,41+ "json.dumps_function": None,42+ "json.dumps_kwargs": {"sort_keys": True},43+ "ext.i18n.trimmed": False,44+}45+46+# export all constants47+__all__ = tuple(x for x in locals().keys() if x.isupper())added:src/jinja/environment.py+1361 added
1+# -*- coding: utf-8 -*-2+"""Classes for managing templates and their runtime and compile time3+options.4+"""5+import os6+import sys7+import weakref8+from functools import partial9+from functools import reduce10+11+from . import nodes12+from ._compat import encode_filename13+from ._compat import implements_iterator14+from ._compat import implements_to_string15+from ._compat import iteritems16+from ._compat import PY217+from ._compat import PYPY18+from ._compat import reraise19+from ._compat import string_types20+from ._compat import text_type21+from .compiler import CodeGenerator22+from .compiler import generate23+from .defaults import BLOCK_END_STRING24+from .defaults import BLOCK_START_STRING25+from .defaults import COMMENT_END_STRING26+from .defaults import COMMENT_START_STRING27+from .defaults import DEFAULT_FILTERS28+from .defaults import DEFAULT_NAMESPACE29+from .defaults import DEFAULT_POLICIES30+from .defaults import DEFAULT_TESTS31+from .defaults import KEEP_TRAILING_NEWLINE32+from .defaults import LINE_COMMENT_PREFIX33+from .defaults import LINE_STATEMENT_PREFIX34+from .defaults import LSTRIP_BLOCKS35+from .defaults import NEWLINE_SEQUENCE36+from .defaults import TRIM_BLOCKS37+from .defaults import VARIABLE_END_STRING38+from .defaults import VARIABLE_START_STRING39+from .exceptions import TemplateNotFound40+from .exceptions import TemplateRuntimeError41+from .exceptions import TemplatesNotFound42+from .exceptions import TemplateSyntaxError43+from .exceptions import UndefinedError44+from .lexer import get_lexer45+from .lexer import TokenStream46+from .nodes import EvalContext47+from .parser import Parser48+from .runtime import Context49+from .runtime import new_context50+from .runtime import Undefined51+from .utils import concat52+from .utils import consume53+from .utils import have_async_gen54+from .utils import import_string55+from .utils import internalcode56+from .utils import LRUCache57+from .utils import Markup58+from .utils import missing59+60+# for direct template usage we have up to ten living environments61+_spontaneous_environments = LRUCache(10)62+63+64+def get_spontaneous_environment(cls, *args):65+ """Return a new spontaneous environment. A spontaneous environment66+ is used for templates created directly rather than through an67+ existing environment.68+69+ :param cls: Environment class to create.70+ :param args: Positional arguments passed to environment.71+ """72+ key = (cls, args)73+74+ try:75+ return _spontaneous_environments[key]76+ except KeyError:77+ _spontaneous_environments[key] = env = cls(*args)78+ env.shared = True79+ return env80+81+82+def create_cache(size):83+ """Return the cache class for the given size."""84+ if size == 0:85+ return None86+ if size < 0:87+ return {}88+ return LRUCache(size)89+90+91+def copy_cache(cache):92+ """Create an empty copy of the given cache."""93+ if cache is None:94+ return None95+ elif type(cache) is dict:96+ return {}97+ return LRUCache(cache.capacity)98+99+100+def load_extensions(environment, extensions):101+ """Load the extensions from the list and bind it to the environment.102+ Returns a dict of instantiated environments.103+ """104+ result = {}105+ for extension in extensions:106+ if isinstance(extension, string_types):107+ extension = import_string(extension)108+ result[extension.identifier] = extension(environment)109+ return result110+111+112+def fail_for_missing_callable(string, name):113+ msg = string % name114+ if isinstance(name, Undefined):115+ try:116+ name._fail_with_undefined_error()117+ except Exception as e:118+ msg = "%s (%s; did you forget to quote the callable name?)" % (msg, e)119+ raise TemplateRuntimeError(msg)120+121+122+def _environment_sanity_check(environment):123+ """Perform a sanity check on the environment."""124+ assert issubclass(125+ environment.undefined, Undefined126+ ), "undefined must be a subclass of undefined because filters depend on it."127+ assert (128+ environment.block_start_string129+ != environment.variable_start_string130+ != environment.comment_start_string131+ ), "block, variable and comment start strings must be different"132+ assert environment.newline_sequence in (133+ "\r",134+ "\r\n",135+ "\n",136+ ), "newline_sequence set to unknown line ending string."137+ return environment138+139+140+class Environment(object):141+ r"""The core component of Jinja is the `Environment`. It contains142+ important shared variables like configuration, filters, tests,143+ globals and others. Instances of this class may be modified if144+ they are not shared and if no template was loaded so far.145+ Modifications on environments after the first template was loaded146+ will lead to surprising effects and undefined behavior.147+148+ Here are the possible initialization parameters:149+150+ `block_start_string`151+ The string marking the beginning of a block. Defaults to ``'{%'``.152+153+ `block_end_string`154+ The string marking the end of a block. Defaults to ``'%}'``.155+156+ `variable_start_string`157+ The string marking the beginning of a print statement.158+ Defaults to ``'{{'``.159+160+ `variable_end_string`161+ The string marking the end of a print statement. Defaults to162+ ``'}}'``.163+164+ `comment_start_string`165+ The string marking the beginning of a comment. Defaults to ``'{#'``.166+167+ `comment_end_string`168+ The string marking the end of a comment. Defaults to ``'#}'``.169+170+ `line_statement_prefix`171+ If given and a string, this will be used as prefix for line based172+ statements. See also :ref:`line-statements`.173+174+ `line_comment_prefix`175+ If given and a string, this will be used as prefix for line based176+ comments. See also :ref:`line-statements`.177+178+ .. versionadded:: 2.2179+180+ `trim_blocks`181+ If this is set to ``True`` the first newline after a block is182+ removed (block, not variable tag!). Defaults to `False`.183+184+ `lstrip_blocks`185+ If this is set to ``True`` leading spaces and tabs are stripped186+ from the start of a line to a block. Defaults to `False`.187+188+ `newline_sequence`189+ The sequence that starts a newline. Must be one of ``'\r'``,190+ ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a191+ useful default for Linux and OS X systems as well as web192+ applications.193+194+ `keep_trailing_newline`195+ Preserve the trailing newline when rendering templates.196+ The default is ``False``, which causes a single newline,197+ if present, to be stripped from the end of the template.198+199+ .. versionadded:: 2.7200+201+ `extensions`202+ List of Jinja extensions to use. This can either be import paths203+ as strings or extension classes. For more information have a204+ look at :ref:`the extensions documentation <jinja-extensions>`.205+206+ `optimized`207+ should the optimizer be enabled? Default is ``True``.208+209+ `undefined`210+ :class:`Undefined` or a subclass of it that is used to represent211+ undefined values in the template.212+213+ `finalize`214+ A callable that can be used to process the result of a variable215+ expression before it is output. For example one can convert216+ ``None`` implicitly into an empty string here.217+218+ `autoescape`219+ If set to ``True`` the XML/HTML autoescaping feature is enabled by220+ default. For more details about autoescaping see221+ :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also222+ be a callable that is passed the template name and has to223+ return ``True`` or ``False`` depending on autoescape should be224+ enabled by default.225+226+ .. versionchanged:: 2.4227+ `autoescape` can now be a function228+229+ `loader`230+ The template loader for this environment.231+232+ `cache_size`233+ The size of the cache. Per default this is ``400`` which means234+ that if more than 400 templates are loaded the loader will clean235+ out the least recently used template. If the cache size is set to236+ ``0`` templates are recompiled all the time, if the cache size is237+ ``-1`` the cache will not be cleaned.238+239+ .. versionchanged:: 2.8240+ The cache size was increased to 400 from a low 50.241+242+ `auto_reload`243+ Some loaders load templates from locations where the template244+ sources may change (ie: file system or database). If245+ ``auto_reload`` is set to ``True`` (default) every time a template is246+ requested the loader checks if the source changed and if yes, it247+ will reload the template. For higher performance it's possible to248+ disable that.249+250+ `bytecode_cache`251+ If set to a bytecode cache object, this object will provide a252+ cache for the internal Jinja bytecode so that templates don't253+ have to be parsed if they were not changed.254+255+ See :ref:`bytecode-cache` for more information.256+257+ `enable_async`258+ If set to true this enables async template execution which allows259+ you to take advantage of newer Python features. This requires260+ Python 3.6 or later.261+ """262+263+ #: if this environment is sandboxed. Modifying this variable won't make264+ #: the environment sandboxed though. For a real sandboxed environment265+ #: have a look at jinja2.sandbox. This flag alone controls the code266+ #: generation by the compiler.267+ sandboxed = False268+269+ #: True if the environment is just an overlay270+ overlayed = False271+272+ #: the environment this environment is linked to if it is an overlay273+ linked_to = None274+275+ #: shared environments have this set to `True`. A shared environment276+ #: must not be modified277+ shared = False278+279+ #: the class that is used for code generation. See280+ #: :class:`~jinja2.compiler.CodeGenerator` for more information.281+ code_generator_class = CodeGenerator282+283+ #: the context class thatis used for templates. See284+ #: :class:`~jinja2.runtime.Context` for more information.285+ context_class = Context286+287+ def __init__(288+ self,289+ block_start_string=BLOCK_START_STRING,290+ block_end_string=BLOCK_END_STRING,291+ variable_start_string=VARIABLE_START_STRING,292+ variable_end_string=VARIABLE_END_STRING,293+ comment_start_string=COMMENT_START_STRING,294+ comment_end_string=COMMENT_END_STRING,295+ line_statement_prefix=LINE_STATEMENT_PREFIX,296+ line_comment_prefix=LINE_COMMENT_PREFIX,297+ trim_blocks=TRIM_BLOCKS,298+ lstrip_blocks=LSTRIP_BLOCKS,299+ newline_sequence=NEWLINE_SEQUENCE,300+ keep_trailing_newline=KEEP_TRAILING_NEWLINE,301+ extensions=(),302+ optimized=True,303+ undefined=Undefined,304+ finalize=None,305+ autoescape=False,306+ loader=None,307+ cache_size=400,308+ auto_reload=True,309+ bytecode_cache=None,310+ enable_async=False,311+ ):312+ # !!Important notice!!313+ # The constructor accepts quite a few arguments that should be314+ # passed by keyword rather than position. However it's important to315+ # not change the order of arguments because it's used at least316+ # internally in those cases:317+ # - spontaneous environments (i18n extension and Template)318+ # - unittests319+ # If parameter changes are required only add parameters at the end320+ # and don't change the arguments (or the defaults!) of the arguments321+ # existing already.322+323+ # lexer / parser information324+ self.block_start_string = block_start_string325+ self.block_end_string = block_end_string326+ self.variable_start_string = variable_start_string327+ self.variable_end_string = variable_end_string328+ self.comment_start_string = comment_start_string329+ self.comment_end_string = comment_end_string330+ self.line_statement_prefix = line_statement_prefix331+ self.line_comment_prefix = line_comment_prefix332+ self.trim_blocks = trim_blocks333+ self.lstrip_blocks = lstrip_blocks334+ self.newline_sequence = newline_sequence335+ self.keep_trailing_newline = keep_trailing_newline336+337+ # runtime information338+ self.undefined = undefined339+ self.optimized = optimized340+ self.finalize = finalize341+ self.autoescape = autoescape342+343+ # defaults344+ self.filters = DEFAULT_FILTERS.copy()345+ self.tests = DEFAULT_TESTS.copy()346+ self.globals = DEFAULT_NAMESPACE.copy()347+348+ # set the loader provided349+ self.loader = loader350+ self.cache = create_cache(cache_size)351+ self.bytecode_cache = bytecode_cache352+ self.auto_reload = auto_reload353+354+ # configurable policies355+ self.policies = DEFAULT_POLICIES.copy()356+357+ # load extensions358+ self.extensions = load_extensions(self, extensions)359+360+ self.enable_async = enable_async361+ self.is_async = self.enable_async and have_async_gen362+ if self.is_async:363+ # runs patch_all() to enable async support364+ from . import asyncsupport # noqa: F401365+366+ _environment_sanity_check(self)367+368+ def add_extension(self, extension):369+ """Adds an extension after the environment was created.370+371+ .. versionadded:: 2.5372+ """373+ self.extensions.update(load_extensions(self, [extension]))374+375+ def extend(self, **attributes):376+ """Add the items to the instance of the environment if they do not exist377+ yet. This is used by :ref:`extensions <writing-extensions>` to register378+ callbacks and configuration values without breaking inheritance.379+ """380+ for key, value in iteritems(attributes):381+ if not hasattr(self, key):382+ setattr(self, key, value)383+384+ def overlay(385+ self,386+ block_start_string=missing,387+ block_end_string=missing,388+ variable_start_string=missing,389+ variable_end_string=missing,390+ comment_start_string=missing,391+ comment_end_string=missing,392+ line_statement_prefix=missing,393+ line_comment_prefix=missing,394+ trim_blocks=missing,395+ lstrip_blocks=missing,396+ extensions=missing,397+ optimized=missing,398+ undefined=missing,399+ finalize=missing,400+ autoescape=missing,401+ loader=missing,402+ cache_size=missing,403+ auto_reload=missing,404+ bytecode_cache=missing,405+ ):406+ """Create a new overlay environment that shares all the data with the407+ current environment except for cache and the overridden attributes.408+ Extensions cannot be removed for an overlayed environment. An overlayed409+ environment automatically gets all the extensions of the environment it410+ is linked to plus optional extra extensions.411+412+ Creating overlays should happen after the initial environment was set413+ up completely. Not all attributes are truly linked, some are just414+ copied over so modifications on the original environment may not shine415+ through.416+ """417+ args = dict(locals())418+ del args["self"], args["cache_size"], args["extensions"]419+420+ rv = object.__new__(self.__class__)421+ rv.__dict__.update(self.__dict__)422+ rv.overlayed = True423+ rv.linked_to = self424+425+ for key, value in iteritems(args):426+ if value is not missing:427+ setattr(rv, key, value)428+429+ if cache_size is not missing:430+ rv.cache = create_cache(cache_size)431+ else:432+ rv.cache = copy_cache(self.cache)433+434+ rv.extensions = {}435+ for key, value in iteritems(self.extensions):436+ rv.extensions[key] = value.bind(rv)437+ if extensions is not missing:438+ rv.extensions.update(load_extensions(rv, extensions))439+440+ return _environment_sanity_check(rv)441+442+ lexer = property(get_lexer, doc="The lexer for this environment.")443+444+ def iter_extensions(self):445+ """Iterates over the extensions by priority."""446+ return iter(sorted(self.extensions.values(), key=lambda x: x.priority))447+448+ def getitem(self, obj, argument):449+ """Get an item or attribute of an object but prefer the item."""450+ try:451+ return obj[argument]452+ except (AttributeError, TypeError, LookupError):453+ if isinstance(argument, string_types):454+ try:455+ attr = str(argument)456+ except Exception:457+ pass458+ else:459+ try:460+ return getattr(obj, attr)461+ except AttributeError:462+ pass463+ return self.undefined(obj=obj, name=argument)464+465+ def getattr(self, obj, attribute):466+ """Get an item or attribute of an object but prefer the attribute.467+ Unlike :meth:`getitem` the attribute *must* be a bytestring.468+ """469+ try:470+ return getattr(obj, attribute)471+ except AttributeError:472+ pass473+ try:474+ return obj[attribute]475+ except (TypeError, LookupError, AttributeError):476+ return self.undefined(obj=obj, name=attribute)477+478+ def call_filter(479+ self, name, value, args=None, kwargs=None, context=None, eval_ctx=None480+ ):481+ """Invokes a filter on a value the same way the compiler does it.482+483+ Note that on Python 3 this might return a coroutine in case the484+ filter is running from an environment in async mode and the filter485+ supports async execution. It's your responsibility to await this486+ if needed.487+488+ .. versionadded:: 2.7489+ """490+ func = self.filters.get(name)491+ if func is None:492+ fail_for_missing_callable("no filter named %r", name)493+ args = [value] + list(args or ())494+ if getattr(func, "contextfilter", False):495+ if context is None:496+ raise TemplateRuntimeError(497+ "Attempted to invoke context filter without context"498+ )499+ args.insert(0, context)500+ elif getattr(func, "evalcontextfilter", False):501+ if eval_ctx is None:502+ if context is not None:503+ eval_ctx = context.eval_ctx504+ else:505+ eval_ctx = EvalContext(self)506+ args.insert(0, eval_ctx)507+ elif getattr(func, "environmentfilter", False):508+ args.insert(0, self)509+ return func(*args, **(kwargs or {}))510+511+ def call_test(self, name, value, args=None, kwargs=None):512+ """Invokes a test on a value the same way the compiler does it.513+514+ .. versionadded:: 2.7515+ """516+ func = self.tests.get(name)517+ if func is None:518+ fail_for_missing_callable("no test named %r", name)519+ return func(value, *(args or ()), **(kwargs or {}))520+521+ @internalcode522+ def parse(self, source, name=None, filename=None):523+ """Parse the sourcecode and return the abstract syntax tree. This524+ tree of nodes is used by the compiler to convert the template into525+ executable source- or bytecode. This is useful for debugging or to526+ extract information from templates.527+528+ If you are :ref:`developing Jinja extensions <writing-extensions>`529+ this gives you a good overview of the node tree generated.530+ """531+ try:532+ return self._parse(source, name, filename)533+ except TemplateSyntaxError:534+ self.handle_exception(source=source)535+536+ def _parse(self, source, name, filename):537+ """Internal parsing function used by `parse` and `compile`."""538+ return Parser(self, source, name, encode_filename(filename)).parse()539+540+ def lex(self, source, name=None, filename=None):541+ """Lex the given sourcecode and return a generator that yields542+ tokens as tuples in the form ``(lineno, token_type, value)``.543+ This can be useful for :ref:`extension development <writing-extensions>`544+ and debugging templates.545+546+ This does not perform preprocessing. If you want the preprocessing547+ of the extensions to be applied you have to filter source through548+ the :meth:`preprocess` method.549+ """550+ source = text_type(source)551+ try:552+ return self.lexer.tokeniter(source, name, filename)553+ except TemplateSyntaxError:554+ self.handle_exception(source=source)555+556+ def preprocess(self, source, name=None, filename=None):557+ """Preprocesses the source with all extensions. This is automatically558+ called for all parsing and compiling methods but *not* for :meth:`lex`559+ because there you usually only want the actual source tokenized.560+ """561+ return reduce(562+ lambda s, e: e.preprocess(s, name, filename),563+ self.iter_extensions(),564+ text_type(source),565+ )566+567+ def _tokenize(self, source, name, filename=None, state=None):568+ """Called by the parser to do the preprocessing and filtering569+ for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.570+ """571+ source = self.preprocess(source, name, filename)572+ stream = self.lexer.tokenize(source, name, filename, state)573+ for ext in self.iter_extensions():574+ stream = ext.filter_stream(stream)575+ if not isinstance(stream, TokenStream):576+ stream = TokenStream(stream, name, filename)577+ return stream578+579+ def _generate(self, source, name, filename, defer_init=False):580+ """Internal hook that can be overridden to hook a different generate581+ method in.582+583+ .. versionadded:: 2.5584+ """585+ return generate(586+ source,587+ self,588+ name,589+ filename,590+ defer_init=defer_init,591+ optimized=self.optimized,592+ )593+594+ def _compile(self, source, filename):595+ """Internal hook that can be overridden to hook a different compile596+ method in.597+598+ .. versionadded:: 2.5599+ """600+ return compile(source, filename, "exec")601+602+ @internalcode603+ def compile(self, source, name=None, filename=None, raw=False, defer_init=False):604+ """Compile a node or template source code. The `name` parameter is605+ the load name of the template after it was joined using606+ :meth:`join_path` if necessary, not the filename on the file system.607+ the `filename` parameter is the estimated filename of the template on608+ the file system. If the template came from a database or memory this609+ can be omitted.610+611+ The return value of this method is a python code object. If the `raw`612+ parameter is `True` the return value will be a string with python613+ code equivalent to the bytecode returned otherwise. This method is614+ mainly used internally.615+616+ `defer_init` is use internally to aid the module code generator. This617+ causes the generated code to be able to import without the global618+ environment variable to be set.619+620+ .. versionadded:: 2.4621+ `defer_init` parameter added.622+ """623+ source_hint = None624+ try:625+ if isinstance(source, string_types):626+ source_hint = source627+ source = self._parse(source, name, filename)628+ source = self._generate(source, name, filename, defer_init=defer_init)629+ if raw:630+ return source631+ if filename is None:632+ filename = "<template>"633+ else:634+ filename = encode_filename(filename)635+ return self._compile(source, filename)636+ except TemplateSyntaxError:637+ self.handle_exception(source=source_hint)638+639+ def compile_expression(self, source, undefined_to_none=True):640+ """A handy helper method that returns a callable that accepts keyword641+ arguments that appear as variables in the expression. If called it642+ returns the result of the expression.643+644+ This is useful if applications want to use the same rules as Jinja645+ in template "configuration files" or similar situations.646+647+ Example usage:648+649+ >>> env = Environment()650+ >>> expr = env.compile_expression('foo == 42')651+ >>> expr(foo=23)652+ False653+ >>> expr(foo=42)654+ True655+656+ Per default the return value is converted to `None` if the657+ expression returns an undefined value. This can be changed658+ by setting `undefined_to_none` to `False`.659+660+ >>> env.compile_expression('var')() is None661+ True662+ >>> env.compile_expression('var', undefined_to_none=False)()663+ Undefined664+665+ .. versionadded:: 2.1666+ """667+ parser = Parser(self, source, state="variable")668+ try:669+ expr = parser.parse_expression()670+ if not parser.stream.eos:671+ raise TemplateSyntaxError(672+ "chunk after expression", parser.stream.current.lineno, None, None673+ )674+ expr.set_environment(self)675+ except TemplateSyntaxError:676+ if sys.exc_info() is not None:677+ self.handle_exception(source=source)678+679+ body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]680+ template = self.from_string(nodes.Template(body, lineno=1))681+ return TemplateExpression(template, undefined_to_none)682+683+ def compile_templates(684+ self,685+ target,686+ extensions=None,687+ filter_func=None,688+ zip="deflated",689+ log_function=None,690+ ignore_errors=True,691+ py_compile=False,692+ ):693+ """Finds all the templates the loader can find, compiles them694+ and stores them in `target`. If `zip` is `None`, instead of in a695+ zipfile, the templates will be stored in a directory.696+ By default a deflate zip algorithm is used. To switch to697+ the stored algorithm, `zip` can be set to ``'stored'``.698+699+ `extensions` and `filter_func` are passed to :meth:`list_templates`.700+ Each template returned will be compiled to the target folder or701+ zipfile.702+703+ By default template compilation errors are ignored. In case a704+ log function is provided, errors are logged. If you want template705+ syntax errors to abort the compilation you can set `ignore_errors`706+ to `False` and you will get an exception on syntax errors.707+708+ If `py_compile` is set to `True` .pyc files will be written to the709+ target instead of standard .py files. This flag does not do anything710+ on pypy and Python 3 where pyc files are not picked up by itself and711+ don't give much benefit.712+713+ .. versionadded:: 2.4714+ """715+ from .loaders import ModuleLoader716+717+ if log_function is None:718+719+ def log_function(x):720+ pass721+722+ if py_compile:723+ if not PY2 or PYPY:724+ import warnings725+726+ warnings.warn(727+ "'py_compile=True' has no effect on PyPy or Python"728+ " 3 and will be removed in version 3.0",729+ DeprecationWarning,730+ stacklevel=2,731+ )732+ py_compile = False733+ else:734+ import imp735+ import marshal736+737+ py_header = imp.get_magic() + u"\xff\xff\xff\xff".encode("iso-8859-15")738+739+ # Python 3.3 added a source filesize to the header740+ if sys.version_info >= (3, 3):741+ py_header += u"\x00\x00\x00\x00".encode("iso-8859-15")742+743+ def write_file(filename, data):744+ if zip:745+ info = ZipInfo(filename)746+ info.external_attr = 0o755 << 16747+ zip_file.writestr(info, data)748+ else:749+ if isinstance(data, text_type):750+ data = data.encode("utf8")751+752+ with open(os.path.join(target, filename), "wb") as f:753+ f.write(data)754+755+ if zip is not None:756+ from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED757+758+ zip_file = ZipFile(759+ target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]760+ )761+ log_function('Compiling into Zip archive "%s"' % target)762+ else:763+ if not os.path.isdir(target):764+ os.makedirs(target)765+ log_function('Compiling into folder "%s"' % target)766+767+ try:768+ for name in self.list_templates(extensions, filter_func):769+ source, filename, _ = self.loader.get_source(self, name)770+ try:771+ code = self.compile(source, name, filename, True, True)772+ except TemplateSyntaxError as e:773+ if not ignore_errors:774+ raise775+ log_function('Could not compile "%s": %s' % (name, e))776+ continue777+778+ filename = ModuleLoader.get_module_filename(name)779+780+ if py_compile:781+ c = self._compile(code, encode_filename(filename))782+ write_file(filename + "c", py_header + marshal.dumps(c))783+ log_function('Byte-compiled "%s" as %s' % (name, filename + "c"))784+ else:785+ write_file(filename, code)786+ log_function('Compiled "%s" as %s' % (name, filename))787+ finally:788+ if zip:789+ zip_file.close()790+791+ log_function("Finished compiling templates")792+793+ def list_templates(self, extensions=None, filter_func=None):794+ """Returns a list of templates for this environment. This requires795+ that the loader supports the loader's796+ :meth:`~BaseLoader.list_templates` method.797+798+ If there are other files in the template folder besides the799+ actual templates, the returned list can be filtered. There are two800+ ways: either `extensions` is set to a list of file extensions for801+ templates, or a `filter_func` can be provided which is a callable that802+ is passed a template name and should return `True` if it should end up803+ in the result list.804+805+ If the loader does not support that, a :exc:`TypeError` is raised.806+807+ .. versionadded:: 2.4808+ """809+ names = self.loader.list_templates()810+811+ if extensions is not None:812+ if filter_func is not None:813+ raise TypeError(814+ "either extensions or filter_func can be passed, but not both"815+ )816+817+ def filter_func(x):818+ return "." in x and x.rsplit(".", 1)[1] in extensions819+820+ if filter_func is not None:821+ names = [name for name in names if filter_func(name)]822+823+ return names824+825+ def handle_exception(self, source=None):826+ """Exception handling helper. This is used internally to either raise827+ rewritten exceptions or return a rendered traceback for the template.828+ """829+ from .debug import rewrite_traceback_stack830+831+ reraise(*rewrite_traceback_stack(source=source))832+833+ def join_path(self, template, parent):834+ """Join a template with the parent. By default all the lookups are835+ relative to the loader root so this method returns the `template`836+ parameter unchanged, but if the paths should be relative to the837+ parent template, this function can be used to calculate the real838+ template name.839+840+ Subclasses may override this method and implement template path841+ joining here.842+ """843+ return template844+845+ @internalcode846+ def _load_template(self, name, globals):847+ if self.loader is None:848+ raise TypeError("no loader for this environment specified")849+ cache_key = (weakref.ref(self.loader), name)850+ if self.cache is not None:851+ template = self.cache.get(cache_key)852+ if template is not None and (853+ not self.auto_reload or template.is_up_to_date854+ ):855+ return template856+ template = self.loader.load(self, name, globals)857+ if self.cache is not None:858+ self.cache[cache_key] = template859+ return template860+861+ @internalcode862+ def get_template(self, name, parent=None, globals=None):863+ """Load a template from the loader. If a loader is configured this864+ method asks the loader for the template and returns a :class:`Template`.865+ If the `parent` parameter is not `None`, :meth:`join_path` is called866+ to get the real template name before loading.867+868+ The `globals` parameter can be used to provide template wide globals.869+ These variables are available in the context at render time.870+871+ If the template does not exist a :exc:`TemplateNotFound` exception is872+ raised.873+874+ .. versionchanged:: 2.4875+ If `name` is a :class:`Template` object it is returned from the876+ function unchanged.877+ """878+ if isinstance(name, Template):879+ return name880+ if parent is not None:881+ name = self.join_path(name, parent)882+ return self._load_template(name, self.make_globals(globals))883+884+ @internalcode885+ def select_template(self, names, parent=None, globals=None):886+ """Works like :meth:`get_template` but tries a number of templates887+ before it fails. If it cannot find any of the templates, it will888+ raise a :exc:`TemplatesNotFound` exception.889+890+ .. versionchanged:: 2.11891+ If names is :class:`Undefined`, an :exc:`UndefinedError` is892+ raised instead. If no templates were found and names893+ contains :class:`Undefined`, the message is more helpful.894+895+ .. versionchanged:: 2.4896+ If `names` contains a :class:`Template` object it is returned897+ from the function unchanged.898+899+ .. versionadded:: 2.3900+ """901+ if isinstance(names, Undefined):902+ names._fail_with_undefined_error()903+904+ if not names:905+ raise TemplatesNotFound(906+ message=u"Tried to select from an empty list " u"of templates."907+ )908+ globals = self.make_globals(globals)909+ for name in names:910+ if isinstance(name, Template):911+ return name912+ if parent is not None:913+ name = self.join_path(name, parent)914+ try:915+ return self._load_template(name, globals)916+ except (TemplateNotFound, UndefinedError):917+ pass918+ raise TemplatesNotFound(names)919+920+ @internalcode921+ def get_or_select_template(self, template_name_or_list, parent=None, globals=None):922+ """Does a typecheck and dispatches to :meth:`select_template`923+ if an iterable of template names is given, otherwise to924+ :meth:`get_template`.925+926+ .. versionadded:: 2.3927+ """928+ if isinstance(template_name_or_list, (string_types, Undefined)):929+ return self.get_template(template_name_or_list, parent, globals)930+ elif isinstance(template_name_or_list, Template):931+ return template_name_or_list932+ return self.select_template(template_name_or_list, parent, globals)933+934+ def from_string(self, source, globals=None, template_class=None):935+ """Load a template from a string. This parses the source given and936+ returns a :class:`Template` object.937+ """938+ globals = self.make_globals(globals)939+ cls = template_class or self.template_class940+ return cls.from_code(self, self.compile(source), globals, None)941+942+ def make_globals(self, d):943+ """Return a dict for the globals."""944+ if not d:945+ return self.globals946+ return dict(self.globals, **d)947+948+949+class Template(object):950+ """The central template object. This class represents a compiled template951+ and is used to evaluate it.952+953+ Normally the template object is generated from an :class:`Environment` but954+ it also has a constructor that makes it possible to create a template955+ instance directly using the constructor. It takes the same arguments as956+ the environment constructor but it's not possible to specify a loader.957+958+ Every template object has a few methods and members that are guaranteed959+ to exist. However it's important that a template object should be960+ considered immutable. Modifications on the object are not supported.961+962+ Template objects created from the constructor rather than an environment963+ do have an `environment` attribute that points to a temporary environment964+ that is probably shared with other templates created with the constructor965+ and compatible settings.966+967+ >>> template = Template('Hello {{ name }}!')968+ >>> template.render(name='John Doe') == u'Hello John Doe!'969+ True970+ >>> stream = template.stream(name='John Doe')971+ >>> next(stream) == u'Hello John Doe!'972+ True973+ >>> next(stream)974+ Traceback (most recent call last):975+ ...976+ StopIteration977+ """978+979+ #: Type of environment to create when creating a template directly980+ #: rather than through an existing environment.981+ environment_class = Environment982+983+ def __new__(984+ cls,985+ source,986+ block_start_string=BLOCK_START_STRING,987+ block_end_string=BLOCK_END_STRING,988+ variable_start_string=VARIABLE_START_STRING,989+ variable_end_string=VARIABLE_END_STRING,990+ comment_start_string=COMMENT_START_STRING,991+ comment_end_string=COMMENT_END_STRING,992+ line_statement_prefix=LINE_STATEMENT_PREFIX,993+ line_comment_prefix=LINE_COMMENT_PREFIX,994+ trim_blocks=TRIM_BLOCKS,995+ lstrip_blocks=LSTRIP_BLOCKS,996+ newline_sequence=NEWLINE_SEQUENCE,997+ keep_trailing_newline=KEEP_TRAILING_NEWLINE,998+ extensions=(),999+ optimized=True,1000+ undefined=Undefined,1001+ finalize=None,1002+ autoescape=False,1003+ enable_async=False,1004+ ):1005+ env = get_spontaneous_environment(1006+ cls.environment_class,1007+ block_start_string,1008+ block_end_string,1009+ variable_start_string,1010+ variable_end_string,1011+ comment_start_string,1012+ comment_end_string,1013+ line_statement_prefix,1014+ line_comment_prefix,1015+ trim_blocks,1016+ lstrip_blocks,1017+ newline_sequence,1018+ keep_trailing_newline,1019+ frozenset(extensions),1020+ optimized,1021+ undefined,1022+ finalize,1023+ autoescape,1024+ None,1025+ 0,1026+ False,1027+ None,1028+ enable_async,1029+ )1030+ return env.from_string(source, template_class=cls)1031+1032+ @classmethod1033+ def from_code(cls, environment, code, globals, uptodate=None):1034+ """Creates a template object from compiled code and the globals. This1035+ is used by the loaders and environment to create a template object.1036+ """1037+ namespace = {"environment": environment, "__file__": code.co_filename}1038+ exec(code, namespace)1039+ rv = cls._from_namespace(environment, namespace, globals)1040+ rv._uptodate = uptodate1041+ return rv1042+1043+ @classmethod1044+ def from_module_dict(cls, environment, module_dict, globals):1045+ """Creates a template object from a module. This is used by the1046+ module loader to create a template object.1047+1048+ .. versionadded:: 2.41049+ """1050+ return cls._from_namespace(environment, module_dict, globals)1051+1052+ @classmethod1053+ def _from_namespace(cls, environment, namespace, globals):1054+ t = object.__new__(cls)1055+ t.environment = environment1056+ t.globals = globals1057+ t.name = namespace["name"]1058+ t.filename = namespace["__file__"]1059+ t.blocks = namespace["blocks"]1060+1061+ # render function and module1062+ t.root_render_func = namespace["root"]1063+ t._module = None1064+1065+ # debug and loader helpers1066+ t._debug_info = namespace["debug_info"]1067+ t._uptodate = None1068+1069+ # store the reference1070+ namespace["environment"] = environment1071+ namespace["__jinja_template__"] = t1072+1073+ return t1074+1075+ def render(self, *args, **kwargs):1076+ """This method accepts the same arguments as the `dict` constructor:1077+ A dict, a dict subclass or some keyword arguments. If no arguments1078+ are given the context will be empty. These two calls do the same::1079+1080+ template.render(knights='that say nih')1081+ template.render({'knights': 'that say nih'})1082+1083+ This will return the rendered template as unicode string.1084+ """1085+ vars = dict(*args, **kwargs)1086+ try:1087+ return concat(self.root_render_func(self.new_context(vars)))1088+ except Exception:1089+ self.environment.handle_exception()1090+1091+ def render_async(self, *args, **kwargs):1092+ """This works similar to :meth:`render` but returns a coroutine1093+ that when awaited returns the entire rendered template string. This1094+ requires the async feature to be enabled.1095+1096+ Example usage::1097+1098+ await template.render_async(knights='that say nih; asynchronously')1099+ """1100+ # see asyncsupport for the actual implementation1101+ raise NotImplementedError(1102+ "This feature is not available for this version of Python"1103+ )1104+1105+ def stream(self, *args, **kwargs):1106+ """Works exactly like :meth:`generate` but returns a1107+ :class:`TemplateStream`.1108+ """1109+ return TemplateStream(self.generate(*args, **kwargs))1110+1111+ def generate(self, *args, **kwargs):1112+ """For very large templates it can be useful to not render the whole1113+ template at once but evaluate each statement after another and yield1114+ piece for piece. This method basically does exactly that and returns1115+ a generator that yields one item after another as unicode strings.1116+1117+ It accepts the same arguments as :meth:`render`.1118+ """1119+ vars = dict(*args, **kwargs)1120+ try:1121+ for event in self.root_render_func(self.new_context(vars)):1122+ yield event1123+ except Exception:1124+ yield self.environment.handle_exception()1125+1126+ def generate_async(self, *args, **kwargs):1127+ """An async version of :meth:`generate`. Works very similarly but1128+ returns an async iterator instead.1129+ """1130+ # see asyncsupport for the actual implementation1131+ raise NotImplementedError(1132+ "This feature is not available for this version of Python"1133+ )1134+1135+ def new_context(self, vars=None, shared=False, locals=None):1136+ """Create a new :class:`Context` for this template. The vars1137+ provided will be passed to the template. Per default the globals1138+ are added to the context. If shared is set to `True` the data1139+ is passed as is to the context without adding the globals.1140+1141+ `locals` can be a dict of local variables for internal usage.1142+ """1143+ return new_context(1144+ self.environment, self.name, self.blocks, vars, shared, self.globals, locals1145+ )1146+1147+ def make_module(self, vars=None, shared=False, locals=None):1148+ """This method works like the :attr:`module` attribute when called1149+ without arguments but it will evaluate the template on every call1150+ rather than caching it. It's also possible to provide1151+ a dict which is then used as context. The arguments are the same1152+ as for the :meth:`new_context` method.1153+ """1154+ return TemplateModule(self, self.new_context(vars, shared, locals))1155+1156+ def make_module_async(self, vars=None, shared=False, locals=None):1157+ """As template module creation can invoke template code for1158+ asynchronous executions this method must be used instead of the1159+ normal :meth:`make_module` one. Likewise the module attribute1160+ becomes unavailable in async mode.1161+ """1162+ # see asyncsupport for the actual implementation1163+ raise NotImplementedError(1164+ "This feature is not available for this version of Python"1165+ )1166+1167+ @internalcode1168+ def _get_default_module(self):1169+ if self._module is not None:1170+ return self._module1171+ self._module = rv = self.make_module()1172+ return rv1173+1174+ @property1175+ def module(self):1176+ """The template as module. This is used for imports in the1177+ template runtime but is also useful if one wants to access1178+ exported template variables from the Python layer:1179+1180+ >>> t = Template('{% macro foo() %}42{% endmacro %}23')1181+ >>> str(t.module)1182+ '23'1183+ >>> t.module.foo() == u'42'1184+ True1185+1186+ This attribute is not available if async mode is enabled.1187+ """1188+ return self._get_default_module()1189+1190+ def get_corresponding_lineno(self, lineno):1191+ """Return the source line number of a line number in the1192+ generated bytecode as they are not in sync.1193+ """1194+ for template_line, code_line in reversed(self.debug_info):1195+ if code_line <= lineno:1196+ return template_line1197+ return 11198+1199+ @property1200+ def is_up_to_date(self):1201+ """If this variable is `False` there is a newer version available."""1202+ if self._uptodate is None:1203+ return True1204+ return self._uptodate()1205+1206+ @property1207+ def debug_info(self):1208+ """The debug info mapping."""1209+ if self._debug_info:1210+ return [tuple(map(int, x.split("="))) for x in self._debug_info.split("&")]1211+ return []1212+1213+ def __repr__(self):1214+ if self.name is None:1215+ name = "memory:%x" % id(self)1216+ else:1217+ name = repr(self.name)1218+ return "<%s %s>" % (self.__class__.__name__, name)1219+1220+1221+@implements_to_string1222+class TemplateModule(object):1223+ """Represents an imported template. All the exported names of the1224+ template are available as attributes on this object. Additionally1225+ converting it into an unicode- or bytestrings renders the contents.1226+ """1227+1228+ def __init__(self, template, context, body_stream=None):1229+ if body_stream is None:1230+ if context.environment.is_async:1231+ raise RuntimeError(1232+ "Async mode requires a body stream "1233+ "to be passed to a template module. Use "1234+ "the async methods of the API you are "1235+ "using."1236+ )1237+ body_stream = list(template.root_render_func(context))1238+ self._body_stream = body_stream1239+ self.__dict__.update(context.get_exported())1240+ self.__name__ = template.name1241+1242+ def __html__(self):1243+ return Markup(concat(self._body_stream))1244+1245+ def __str__(self):1246+ return concat(self._body_stream)1247+1248+ def __repr__(self):1249+ if self.__name__ is None:1250+ name = "memory:%x" % id(self)1251+ else:1252+ name = repr(self.__name__)1253+ return "<%s %s>" % (self.__class__.__name__, name)1254+1255+1256+class TemplateExpression(object):1257+ """The :meth:`jinja2.Environment.compile_expression` method returns an1258+ instance of this object. It encapsulates the expression-like access1259+ to the template with an expression it wraps.1260+ """1261+1262+ def __init__(self, template, undefined_to_none):1263+ self._template = template1264+ self._undefined_to_none = undefined_to_none1265+1266+ def __call__(self, *args, **kwargs):1267+ context = self._template.new_context(dict(*args, **kwargs))1268+ consume(self._template.root_render_func(context))1269+ rv = context.vars["result"]1270+ if self._undefined_to_none and isinstance(rv, Undefined):1271+ rv = None1272+ return rv1273+1274+1275+@implements_iterator1276+class TemplateStream(object):1277+ """A template stream works pretty much like an ordinary python generator1278+ but it can buffer multiple items to reduce the number of total iterations.1279+ Per default the output is unbuffered which means that for every unbuffered1280+ instruction in the template one unicode string is yielded.1281+1282+ If buffering is enabled with a buffer size of 5, five items are combined1283+ into a new unicode string. This is mainly useful if you are streaming1284+ big templates to a client via WSGI which flushes after each iteration.1285+ """1286+1287+ def __init__(self, gen):1288+ self._gen = gen1289+ self.disable_buffering()1290+1291+ def dump(self, fp, encoding=None, errors="strict"):1292+ """Dump the complete stream into a file or file-like object.1293+ Per default unicode strings are written, if you want to encode1294+ before writing specify an `encoding`.1295+1296+ Example usage::1297+1298+ Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1299+ """1300+ close = False1301+ if isinstance(fp, string_types):1302+ if encoding is None:1303+ encoding = "utf-8"1304+ fp = open(fp, "wb")1305+ close = True1306+ try:1307+ if encoding is not None:1308+ iterable = (x.encode(encoding, errors) for x in self)1309+ else:1310+ iterable = self1311+ if hasattr(fp, "writelines"):1312+ fp.writelines(iterable)1313+ else:1314+ for item in iterable:1315+ fp.write(item)1316+ finally:1317+ if close:1318+ fp.close()1319+1320+ def disable_buffering(self):1321+ """Disable the output buffering."""1322+ self._next = partial(next, self._gen)1323+ self.buffered = False1324+1325+ def _buffered_generator(self, size):1326+ buf = []1327+ c_size = 01328+ push = buf.append1329+1330+ while 1:1331+ try:1332+ while c_size < size:1333+ c = next(self._gen)1334+ push(c)1335+ if c:1336+ c_size += 11337+ except StopIteration:1338+ if not c_size:1339+ return1340+ yield concat(buf)1341+ del buf[:]1342+ c_size = 01343+1344+ def enable_buffering(self, size=5):1345+ """Enable buffering. Buffer `size` items before yielding them."""1346+ if size <= 1:1347+ raise ValueError("buffer size too small")1348+1349+ self.buffered = True1350+ self._next = partial(next, self._buffered_generator(size))1351+1352+ def __iter__(self):1353+ return self1354+1355+ def __next__(self):1356+ return self._next()1357+1358+1359+# hook in default template class. if anyone reads this comment: ignore that1360+# it's possible to use custom templates ;-)1361+Environment.template_class = Templateadded:src/jinja/exceptions.py+177 added
1+# -*- coding: utf-8 -*-2+from ._compat import imap3+from ._compat import implements_to_string4+from ._compat import PY25+from ._compat import text_type6+7+8+class TemplateError(Exception):9+ """Baseclass for all template errors."""10+11+ if PY2:12+13+ def __init__(self, message=None):14+ if message is not None:15+ message = text_type(message).encode("utf-8")16+ Exception.__init__(self, message)17+18+ @property19+ def message(self):20+ if self.args:21+ message = self.args[0]22+ if message is not None:23+ return message.decode("utf-8", "replace")24+25+ def __unicode__(self):26+ return self.message or u""27+28+ else:29+30+ def __init__(self, message=None):31+ Exception.__init__(self, message)32+33+ @property34+ def message(self):35+ if self.args:36+ message = self.args[0]37+ if message is not None:38+ return message39+40+41+@implements_to_string42+class TemplateNotFound(IOError, LookupError, TemplateError):43+ """Raised if a template does not exist.44+45+ .. versionchanged:: 2.1146+ If the given name is :class:`Undefined` and no message was47+ provided, an :exc:`UndefinedError` is raised.48+ """49+50+ # looks weird, but removes the warning descriptor that just51+ # bogusly warns us about message being deprecated52+ message = None53+54+ def __init__(self, name, message=None):55+ IOError.__init__(self, name)56+57+ if message is None:58+ from .runtime import Undefined59+60+ if isinstance(name, Undefined):61+ name._fail_with_undefined_error()62+63+ message = name64+65+ self.message = message66+ self.name = name67+ self.templates = [name]68+69+ def __str__(self):70+ return self.message71+72+73+class TemplatesNotFound(TemplateNotFound):74+ """Like :class:`TemplateNotFound` but raised if multiple templates75+ are selected. This is a subclass of :class:`TemplateNotFound`76+ exception, so just catching the base exception will catch both.77+78+ .. versionchanged:: 2.1179+ If a name in the list of names is :class:`Undefined`, a message80+ about it being undefined is shown rather than the empty string.81+82+ .. versionadded:: 2.283+ """84+85+ def __init__(self, names=(), message=None):86+ if message is None:87+ from .runtime import Undefined88+89+ parts = []90+91+ for name in names:92+ if isinstance(name, Undefined):93+ parts.append(name._undefined_message)94+ else:95+ parts.append(name)96+97+ message = u"none of the templates given were found: " + u", ".join(98+ imap(text_type, parts)99+ )100+ TemplateNotFound.__init__(self, names and names[-1] or None, message)101+ self.templates = list(names)102+103+104+@implements_to_string105+class TemplateSyntaxError(TemplateError):106+ """Raised to tell the user that there is a problem with the template."""107+108+ def __init__(self, message, lineno, name=None, filename=None):109+ TemplateError.__init__(self, message)110+ self.lineno = lineno111+ self.name = name112+ self.filename = filename113+ self.source = None114+115+ # this is set to True if the debug.translate_syntax_error116+ # function translated the syntax error into a new traceback117+ self.translated = False118+119+ def __str__(self):120+ # for translated errors we only return the message121+ if self.translated:122+ return self.message123+124+ # otherwise attach some stuff125+ location = "line %d" % self.lineno126+ name = self.filename or self.name127+ if name:128+ location = 'File "%s", %s' % (name, location)129+ lines = [self.message, " " + location]130+131+ # if the source is set, add the line to the output132+ if self.source is not None:133+ try:134+ line = self.source.splitlines()[self.lineno - 1]135+ except IndexError:136+ line = None137+ if line:138+ lines.append(" " + line.strip())139+140+ return u"\n".join(lines)141+142+ def __reduce__(self):143+ # https://bugs.python.org/issue1692335 Exceptions that take144+ # multiple required arguments have problems with pickling.145+ # Without this, raises TypeError: __init__() missing 1 required146+ # positional argument: 'lineno'147+ return self.__class__, (self.message, self.lineno, self.name, self.filename)148+149+150+class TemplateAssertionError(TemplateSyntaxError):151+ """Like a template syntax error, but covers cases where something in the152+ template caused an error at compile time that wasn't necessarily caused153+ by a syntax error. However it's a direct subclass of154+ :exc:`TemplateSyntaxError` and has the same attributes.155+ """156+157+158+class TemplateRuntimeError(TemplateError):159+ """A generic runtime error in the template engine. Under some situations160+ Jinja may raise this exception.161+ """162+163+164+class UndefinedError(TemplateRuntimeError):165+ """Raised if a template tries to operate on :class:`Undefined`."""166+167+168+class SecurityError(TemplateRuntimeError):169+ """Raised if a template tries to do something insecure if the170+ sandbox is enabled.171+ """172+173+174+class FilterArgumentError(TemplateRuntimeError):175+ """This error is raised if a filter was called with inappropriate176+ arguments177+ """added:src/jinja/ext.py+703 added
1+# -*- coding: utf-8 -*-2+"""Extension API for adding custom tags and behavior."""3+import pprint4+import re5+from sys import version_info6+7+from . import nodes8+from ._compat import iteritems9+from ._compat import string_types10+from ._compat import with_metaclass11+from .defaults import BLOCK_END_STRING12+from .defaults import BLOCK_START_STRING13+from .defaults import COMMENT_END_STRING14+from .defaults import COMMENT_START_STRING15+from .defaults import KEEP_TRAILING_NEWLINE16+from .defaults import LINE_COMMENT_PREFIX17+from .defaults import LINE_STATEMENT_PREFIX18+from .defaults import LSTRIP_BLOCKS19+from .defaults import NEWLINE_SEQUENCE20+from .defaults import TRIM_BLOCKS21+from .defaults import VARIABLE_END_STRING22+from .defaults import VARIABLE_START_STRING23+from .environment import Environment24+from .exceptions import TemplateAssertionError25+from .exceptions import TemplateSyntaxError26+from .nodes import ContextReference27+from .runtime import concat28+from .utils import contextfunction29+from .utils import import_string30+from .utils import Markup31+32+# the only real useful gettext functions for a Jinja template. Note33+# that ugettext must be assigned to gettext as Jinja doesn't support34+# non unicode strings.35+GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext")36+37+_ws_re = re.compile(r"\s*\n\s*")38+39+40+class ExtensionRegistry(type):41+ """Gives the extension an unique identifier."""42+43+ def __new__(mcs, name, bases, d):44+ rv = type.__new__(mcs, name, bases, d)45+ rv.identifier = rv.__module__ + "." + rv.__name__46+ return rv47+48+49+class Extension(with_metaclass(ExtensionRegistry, object)):50+ """Extensions can be used to add extra functionality to the Jinja template51+ system at the parser level. Custom extensions are bound to an environment52+ but may not store environment specific data on `self`. The reason for53+ this is that an extension can be bound to another environment (for54+ overlays) by creating a copy and reassigning the `environment` attribute.55+56+ As extensions are created by the environment they cannot accept any57+ arguments for configuration. One may want to work around that by using58+ a factory function, but that is not possible as extensions are identified59+ by their import name. The correct way to configure the extension is60+ storing the configuration values on the environment. Because this way the61+ environment ends up acting as central configuration storage the62+ attributes may clash which is why extensions have to ensure that the names63+ they choose for configuration are not too generic. ``prefix`` for example64+ is a terrible name, ``fragment_cache_prefix`` on the other hand is a good65+ name as includes the name of the extension (fragment cache).66+ """67+68+ #: if this extension parses this is the list of tags it's listening to.69+ tags = set()70+71+ #: the priority of that extension. This is especially useful for72+ #: extensions that preprocess values. A lower value means higher73+ #: priority.74+ #:75+ #: .. versionadded:: 2.476+ priority = 10077+78+ def __init__(self, environment):79+ self.environment = environment80+81+ def bind(self, environment):82+ """Create a copy of this extension bound to another environment."""83+ rv = object.__new__(self.__class__)84+ rv.__dict__.update(self.__dict__)85+ rv.environment = environment86+ return rv87+88+ def preprocess(self, source, name, filename=None):89+ """This method is called before the actual lexing and can be used to90+ preprocess the source. The `filename` is optional. The return value91+ must be the preprocessed source.92+ """93+ return source94+95+ def filter_stream(self, stream):96+ """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used97+ to filter tokens returned. This method has to return an iterable of98+ :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a99+ :class:`~jinja2.lexer.TokenStream`.100+ """101+ return stream102+103+ def parse(self, parser):104+ """If any of the :attr:`tags` matched this method is called with the105+ parser as first argument. The token the parser stream is pointing at106+ is the name token that matched. This method has to return one or a107+ list of multiple nodes.108+ """109+ raise NotImplementedError()110+111+ def attr(self, name, lineno=None):112+ """Return an attribute node for the current extension. This is useful113+ to pass constants on extensions to generated template code.114+115+ ::116+117+ self.attr('_my_attribute', lineno=lineno)118+ """119+ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)120+121+ def call_method(122+ self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None123+ ):124+ """Call a method of the extension. This is a shortcut for125+ :meth:`attr` + :class:`jinja2.nodes.Call`.126+ """127+ if args is None:128+ args = []129+ if kwargs is None:130+ kwargs = []131+ return nodes.Call(132+ self.attr(name, lineno=lineno),133+ args,134+ kwargs,135+ dyn_args,136+ dyn_kwargs,137+ lineno=lineno,138+ )139+140+141+@contextfunction142+def _gettext_alias(__context, *args, **kwargs):143+ return __context.call(__context.resolve("gettext"), *args, **kwargs)144+145+146+def _make_new_gettext(func):147+ @contextfunction148+ def gettext(__context, __string, **variables):149+ rv = __context.call(func, __string)150+ if __context.eval_ctx.autoescape:151+ rv = Markup(rv)152+ # Always treat as a format string, even if there are no153+ # variables. This makes translation strings more consistent154+ # and predictable. This requires escaping155+ return rv % variables156+157+ return gettext158+159+160+def _make_new_ngettext(func):161+ @contextfunction162+ def ngettext(__context, __singular, __plural, __num, **variables):163+ variables.setdefault("num", __num)164+ rv = __context.call(func, __singular, __plural, __num)165+ if __context.eval_ctx.autoescape:166+ rv = Markup(rv)167+ # Always treat as a format string, see gettext comment above.168+ return rv % variables169+170+ return ngettext171+172+173+class InternationalizationExtension(Extension):174+ """This extension adds gettext support to Jinja."""175+176+ tags = {"trans"}177+178+ # TODO: the i18n extension is currently reevaluating values in a few179+ # situations. Take this example:180+ # {% trans count=something() %}{{ count }} foo{% pluralize181+ # %}{{ count }} fooss{% endtrans %}182+ # something is called twice here. One time for the gettext value and183+ # the other time for the n-parameter of the ngettext function.184+185+ def __init__(self, environment):186+ Extension.__init__(self, environment)187+ environment.globals["_"] = _gettext_alias188+ environment.extend(189+ install_gettext_translations=self._install,190+ install_null_translations=self._install_null,191+ install_gettext_callables=self._install_callables,192+ uninstall_gettext_translations=self._uninstall,193+ extract_translations=self._extract,194+ newstyle_gettext=False,195+ )196+197+ def _install(self, translations, newstyle=None):198+ gettext = getattr(translations, "ugettext", None)199+ if gettext is None:200+ gettext = translations.gettext201+ ngettext = getattr(translations, "ungettext", None)202+ if ngettext is None:203+ ngettext = translations.ngettext204+ self._install_callables(gettext, ngettext, newstyle)205+206+ def _install_null(self, newstyle=None):207+ self._install_callables(208+ lambda x: x, lambda s, p, n: (n != 1 and (p,) or (s,))[0], newstyle209+ )210+211+ def _install_callables(self, gettext, ngettext, newstyle=None):212+ if newstyle is not None:213+ self.environment.newstyle_gettext = newstyle214+ if self.environment.newstyle_gettext:215+ gettext = _make_new_gettext(gettext)216+ ngettext = _make_new_ngettext(ngettext)217+ self.environment.globals.update(gettext=gettext, ngettext=ngettext)218+219+ def _uninstall(self, translations):220+ for key in "gettext", "ngettext":221+ self.environment.globals.pop(key, None)222+223+ def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):224+ if isinstance(source, string_types):225+ source = self.environment.parse(source)226+ return extract_from_ast(source, gettext_functions)227+228+ def parse(self, parser):229+ """Parse a translatable tag."""230+ lineno = next(parser.stream).lineno231+ num_called_num = False232+233+ # find all the variables referenced. Additionally a variable can be234+ # defined in the body of the trans block too, but this is checked at235+ # a later state.236+ plural_expr = None237+ plural_expr_assignment = None238+ variables = {}239+ trimmed = None240+ while parser.stream.current.type != "block_end":241+ if variables:242+ parser.stream.expect("comma")243+244+ # skip colon for python compatibility245+ if parser.stream.skip_if("colon"):246+ break247+248+ name = parser.stream.expect("name")249+ if name.value in variables:250+ parser.fail(251+ "translatable variable %r defined twice." % name.value,252+ name.lineno,253+ exc=TemplateAssertionError,254+ )255+256+ # expressions257+ if parser.stream.current.type == "assign":258+ next(parser.stream)259+ variables[name.value] = var = parser.parse_expression()260+ elif trimmed is None and name.value in ("trimmed", "notrimmed"):261+ trimmed = name.value == "trimmed"262+ continue263+ else:264+ variables[name.value] = var = nodes.Name(name.value, "load")265+266+ if plural_expr is None:267+ if isinstance(var, nodes.Call):268+ plural_expr = nodes.Name("_trans", "load")269+ variables[name.value] = plural_expr270+ plural_expr_assignment = nodes.Assign(271+ nodes.Name("_trans", "store"), var272+ )273+ else:274+ plural_expr = var275+ num_called_num = name.value == "num"276+277+ parser.stream.expect("block_end")278+279+ plural = None280+ have_plural = False281+ referenced = set()282+283+ # now parse until endtrans or pluralize284+ singular_names, singular = self._parse_block(parser, True)285+ if singular_names:286+ referenced.update(singular_names)287+ if plural_expr is None:288+ plural_expr = nodes.Name(singular_names[0], "load")289+ num_called_num = singular_names[0] == "num"290+291+ # if we have a pluralize block, we parse that too292+ if parser.stream.current.test("name:pluralize"):293+ have_plural = True294+ next(parser.stream)295+ if parser.stream.current.type != "block_end":296+ name = parser.stream.expect("name")297+ if name.value not in variables:298+ parser.fail(299+ "unknown variable %r for pluralization" % name.value,300+ name.lineno,301+ exc=TemplateAssertionError,302+ )303+ plural_expr = variables[name.value]304+ num_called_num = name.value == "num"305+ parser.stream.expect("block_end")306+ plural_names, plural = self._parse_block(parser, False)307+ next(parser.stream)308+ referenced.update(plural_names)309+ else:310+ next(parser.stream)311+312+ # register free names as simple name expressions313+ for var in referenced:314+ if var not in variables:315+ variables[var] = nodes.Name(var, "load")316+317+ if not have_plural:318+ plural_expr = None319+ elif plural_expr is None:320+ parser.fail("pluralize without variables", lineno)321+322+ if trimmed is None:323+ trimmed = self.environment.policies["ext.i18n.trimmed"]324+ if trimmed:325+ singular = self._trim_whitespace(singular)326+ if plural:327+ plural = self._trim_whitespace(plural)328+329+ node = self._make_node(330+ singular,331+ plural,332+ variables,333+ plural_expr,334+ bool(referenced),335+ num_called_num and have_plural,336+ )337+ node.set_lineno(lineno)338+ if plural_expr_assignment is not None:339+ return [plural_expr_assignment, node]340+ else:341+ return node342+343+ def _trim_whitespace(self, string, _ws_re=_ws_re):344+ return _ws_re.sub(" ", string.strip())345+346+ def _parse_block(self, parser, allow_pluralize):347+ """Parse until the next block tag with a given name."""348+ referenced = []349+ buf = []350+ while 1:351+ if parser.stream.current.type == "data":352+ buf.append(parser.stream.current.value.replace("%", "%%"))353+ next(parser.stream)354+ elif parser.stream.current.type == "variable_begin":355+ next(parser.stream)356+ name = parser.stream.expect("name").value357+ referenced.append(name)358+ buf.append("%%(%s)s" % name)359+ parser.stream.expect("variable_end")360+ elif parser.stream.current.type == "block_begin":361+ next(parser.stream)362+ if parser.stream.current.test("name:endtrans"):363+ break364+ elif parser.stream.current.test("name:pluralize"):365+ if allow_pluralize:366+ break367+ parser.fail(368+ "a translatable section can have only one pluralize section"369+ )370+ parser.fail(371+ "control structures in translatable sections are not allowed"372+ )373+ elif parser.stream.eos:374+ parser.fail("unclosed translation block")375+ else:376+ raise RuntimeError("internal parser error")377+378+ return referenced, concat(buf)379+380+ def _make_node(381+ self, singular, plural, variables, plural_expr, vars_referenced, num_called_num382+ ):383+ """Generates a useful node from the data provided."""384+ # no variables referenced? no need to escape for old style385+ # gettext invocations only if there are vars.386+ if not vars_referenced and not self.environment.newstyle_gettext:387+ singular = singular.replace("%%", "%")388+ if plural:389+ plural = plural.replace("%%", "%")390+391+ # singular only:392+ if plural_expr is None:393+ gettext = nodes.Name("gettext", "load")394+ node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None)395+396+ # singular and plural397+ else:398+ ngettext = nodes.Name("ngettext", "load")399+ node = nodes.Call(400+ ngettext,401+ [nodes.Const(singular), nodes.Const(plural), plural_expr],402+ [],403+ None,404+ None,405+ )406+407+ # in case newstyle gettext is used, the method is powerful408+ # enough to handle the variable expansion and autoescape409+ # handling itself410+ if self.environment.newstyle_gettext:411+ for key, value in iteritems(variables):412+ # the function adds that later anyways in case num was413+ # called num, so just skip it.414+ if num_called_num and key == "num":415+ continue416+ node.kwargs.append(nodes.Keyword(key, value))417+418+ # otherwise do that here419+ else:420+ # mark the return value as safe if we are in an421+ # environment with autoescaping turned on422+ node = nodes.MarkSafeIfAutoescape(node)423+ if variables:424+ node = nodes.Mod(425+ node,426+ nodes.Dict(427+ [428+ nodes.Pair(nodes.Const(key), value)429+ for key, value in variables.items()430+ ]431+ ),432+ )433+ return nodes.Output([node])434+435+436+class ExprStmtExtension(Extension):437+ """Adds a `do` tag to Jinja that works like the print statement just438+ that it doesn't print the return value.439+ """440+441+ tags = set(["do"])442+443+ def parse(self, parser):444+ node = nodes.ExprStmt(lineno=next(parser.stream).lineno)445+ node.node = parser.parse_tuple()446+ return node447+448+449+class LoopControlExtension(Extension):450+ """Adds break and continue to the template engine."""451+452+ tags = set(["break", "continue"])453+454+ def parse(self, parser):455+ token = next(parser.stream)456+ if token.value == "break":457+ return nodes.Break(lineno=token.lineno)458+ return nodes.Continue(lineno=token.lineno)459+460+461+class WithExtension(Extension):462+ pass463+464+465+class AutoEscapeExtension(Extension):466+ pass467+468+469+class DebugExtension(Extension):470+ """A ``{% debug %}`` tag that dumps the available variables,471+ filters, and tests.472+473+ .. code-block:: html+jinja474+475+ <pre>{% debug %}</pre>476+477+ .. code-block:: text478+479+ {'context': {'cycler': <class 'jinja2.utils.Cycler'>,480+ ...,481+ 'namespace': <class 'jinja2.utils.Namespace'>},482+ 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',483+ ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],484+ 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',485+ ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}486+487+ .. versionadded:: 2.11.0488+ """489+490+ tags = {"debug"}491+492+ def parse(self, parser):493+ lineno = parser.stream.expect("name:debug").lineno494+ context = ContextReference()495+ result = self.call_method("_render", [context], lineno=lineno)496+ return nodes.Output([result], lineno=lineno)497+498+ def _render(self, context):499+ result = {500+ "context": context.get_all(),501+ "filters": sorted(self.environment.filters.keys()),502+ "tests": sorted(self.environment.tests.keys()),503+ }504+505+ # Set the depth since the intent is to show the top few names.506+ if version_info[:2] >= (3, 4):507+ return pprint.pformat(result, depth=3, compact=True)508+ else:509+ return pprint.pformat(result, depth=3)510+511+512+def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True):513+ """Extract localizable strings from the given template node. Per514+ default this function returns matches in babel style that means non string515+ parameters as well as keyword arguments are returned as `None`. This516+ allows Babel to figure out what you really meant if you are using517+ gettext functions that allow keyword arguments for placeholder expansion.518+ If you don't want that behavior set the `babel_style` parameter to `False`519+ which causes only strings to be returned and parameters are always stored520+ in tuples. As a consequence invalid gettext calls (calls without a single521+ string parameter or string parameters after non-string parameters) are522+ skipped.523+524+ This example explains the behavior:525+526+ >>> from jinja2 import Environment527+ >>> env = Environment()528+ >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')529+ >>> list(extract_from_ast(node))530+ [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]531+ >>> list(extract_from_ast(node, babel_style=False))532+ [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]533+534+ For every string found this function yields a ``(lineno, function,535+ message)`` tuple, where:536+537+ * ``lineno`` is the number of the line on which the string was found,538+ * ``function`` is the name of the ``gettext`` function used (if the539+ string was extracted from embedded Python code), and540+ * ``message`` is the string itself (a ``unicode`` object, or a tuple541+ of ``unicode`` objects for functions with multiple string arguments).542+543+ This extraction function operates on the AST and is because of that unable544+ to extract any comments. For comment support you have to use the babel545+ extraction interface or extract comments yourself.546+ """547+ for node in node.find_all(nodes.Call):548+ if (549+ not isinstance(node.node, nodes.Name)550+ or node.node.name not in gettext_functions551+ ):552+ continue553+554+ strings = []555+ for arg in node.args:556+ if isinstance(arg, nodes.Const) and isinstance(arg.value, string_types):557+ strings.append(arg.value)558+ else:559+ strings.append(None)560+561+ for _ in node.kwargs:562+ strings.append(None)563+ if node.dyn_args is not None:564+ strings.append(None)565+ if node.dyn_kwargs is not None:566+ strings.append(None)567+568+ if not babel_style:569+ strings = tuple(x for x in strings if x is not None)570+ if not strings:571+ continue572+ else:573+ if len(strings) == 1:574+ strings = strings[0]575+ else:576+ strings = tuple(strings)577+ yield node.lineno, node.node.name, strings578+579+580+class _CommentFinder(object):581+ """Helper class to find comments in a token stream. Can only582+ find comments for gettext calls forwards. Once the comment583+ from line 4 is found, a comment for line 1 will not return a584+ usable value.585+ """586+587+ def __init__(self, tokens, comment_tags):588+ self.tokens = tokens589+ self.comment_tags = comment_tags590+ self.offset = 0591+ self.last_lineno = 0592+593+ def find_backwards(self, offset):594+ try:595+ for _, token_type, token_value in reversed(596+ self.tokens[self.offset : offset]597+ ):598+ if token_type in ("comment", "linecomment"):599+ try:600+ prefix, comment = token_value.split(None, 1)601+ except ValueError:602+ continue603+ if prefix in self.comment_tags:604+ return [comment.rstrip()]605+ return []606+ finally:607+ self.offset = offset608+609+ def find_comments(self, lineno):610+ if not self.comment_tags or self.last_lineno > lineno:611+ return []612+ for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):613+ if token_lineno > lineno:614+ return self.find_backwards(self.offset + idx)615+ return self.find_backwards(len(self.tokens))616+617+618+def babel_extract(fileobj, keywords, comment_tags, options):619+ """Babel extraction method for Jinja templates.620+621+ .. versionchanged:: 2.3622+ Basic support for translation comments was added. If `comment_tags`623+ is now set to a list of keywords for extraction, the extractor will624+ try to find the best preceding comment that begins with one of the625+ keywords. For best results, make sure to not have more than one626+ gettext call in one line of code and the matching comment in the627+ same line or the line before.628+629+ .. versionchanged:: 2.5.1630+ The `newstyle_gettext` flag can be set to `True` to enable newstyle631+ gettext calls.632+633+ .. versionchanged:: 2.7634+ A `silent` option can now be provided. If set to `False` template635+ syntax errors are propagated instead of being ignored.636+637+ :param fileobj: the file-like object the messages should be extracted from638+ :param keywords: a list of keywords (i.e. function names) that should be639+ recognized as translation functions640+ :param comment_tags: a list of translator tags to search for and include641+ in the results.642+ :param options: a dictionary of additional options (optional)643+ :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.644+ (comments will be empty currently)645+ """646+ extensions = set()647+ for extension in options.get("extensions", "").split(","):648+ extension = extension.strip()649+ if not extension:650+ continue651+ extensions.add(import_string(extension))652+ if InternationalizationExtension not in extensions:653+ extensions.add(InternationalizationExtension)654+655+ def getbool(options, key, default=False):656+ return options.get(key, str(default)).lower() in ("1", "on", "yes", "true")657+658+ silent = getbool(options, "silent", True)659+ environment = Environment(660+ options.get("block_start_string", BLOCK_START_STRING),661+ options.get("block_end_string", BLOCK_END_STRING),662+ options.get("variable_start_string", VARIABLE_START_STRING),663+ options.get("variable_end_string", VARIABLE_END_STRING),664+ options.get("comment_start_string", COMMENT_START_STRING),665+ options.get("comment_end_string", COMMENT_END_STRING),666+ options.get("line_statement_prefix") or LINE_STATEMENT_PREFIX,667+ options.get("line_comment_prefix") or LINE_COMMENT_PREFIX,668+ getbool(options, "trim_blocks", TRIM_BLOCKS),669+ getbool(options, "lstrip_blocks", LSTRIP_BLOCKS),670+ NEWLINE_SEQUENCE,671+ getbool(options, "keep_trailing_newline", KEEP_TRAILING_NEWLINE),672+ frozenset(extensions),673+ cache_size=0,674+ auto_reload=False,675+ )676+677+ if getbool(options, "trimmed"):678+ environment.policies["ext.i18n.trimmed"] = True679+ if getbool(options, "newstyle_gettext"):680+ environment.newstyle_gettext = True681+682+ source = fileobj.read().decode(options.get("encoding", "utf-8"))683+ try:684+ node = environment.parse(source)685+ tokens = list(environment.lex(environment.preprocess(source)))686+ except TemplateSyntaxError:687+ if not silent:688+ raise689+ # skip templates with syntax errors690+ return691+692+ finder = _CommentFinder(tokens, comment_tags)693+ for lineno, func, message in extract_from_ast(node, keywords):694+ yield lineno, func, message, finder.find_comments(lineno)695+696+697+#: nicer import names698+i18n = InternationalizationExtension699+do = ExprStmtExtension700+loopcontrols = LoopControlExtension701+with_ = WithExtension702+autoescape = AutoEscapeExtension703+debug = DebugExtensionadded:src/jinja/filters.py+1382 added
1+# -*- coding: utf-8 -*-2+"""Built-in template filters used with the ``|`` operator."""3+import math4+import random5+import re6+import warnings7+from collections import namedtuple8+from itertools import chain9+from itertools import groupby10+11+from markupsafe import escape12+from markupsafe import Markup13+from markupsafe import soft_unicode14+15+from ._compat import abc16+from ._compat import imap17+from ._compat import iteritems18+from ._compat import string_types19+from ._compat import text_type20+from .exceptions import FilterArgumentError21+from .runtime import Undefined22+from .utils import htmlsafe_json_dumps23+from .utils import pformat24+from .utils import unicode_urlencode25+from .utils import urlize26+27+_word_re = re.compile(r"\w+", re.UNICODE)28+_word_beginning_split_re = re.compile(r"([-\s\(\{\[\<]+)", re.UNICODE)29+30+31+def contextfilter(f):32+ """Decorator for marking context dependent filters. The current33+ :class:`Context` will be passed as first argument.34+ """35+ f.contextfilter = True36+ return f37+38+39+def evalcontextfilter(f):40+ """Decorator for marking eval-context dependent filters. An eval41+ context object is passed as first argument. For more information42+ about the eval context, see :ref:`eval-context`.43+44+ .. versionadded:: 2.445+ """46+ f.evalcontextfilter = True47+ return f48+49+50+def environmentfilter(f):51+ """Decorator for marking environment dependent filters. The current52+ :class:`Environment` is passed to the filter as first argument.53+ """54+ f.environmentfilter = True55+ return f56+57+58+def ignore_case(value):59+ """For use as a postprocessor for :func:`make_attrgetter`. Converts strings60+ to lowercase and returns other types as-is."""61+ return value.lower() if isinstance(value, string_types) else value62+63+64+def make_attrgetter(environment, attribute, postprocess=None, default=None):65+ """Returns a callable that looks up the given attribute from a66+ passed object with the rules of the environment. Dots are allowed67+ to access attributes of attributes. Integer parts in paths are68+ looked up as integers.69+ """70+ attribute = _prepare_attribute_parts(attribute)71+72+ def attrgetter(item):73+ for part in attribute:74+ item = environment.getitem(item, part)75+76+ if default and isinstance(item, Undefined):77+ item = default78+79+ if postprocess is not None:80+ item = postprocess(item)81+82+ return item83+84+ return attrgetter85+86+87+def make_multi_attrgetter(environment, attribute, postprocess=None):88+ """Returns a callable that looks up the given comma separated89+ attributes from a passed object with the rules of the environment.90+ Dots are allowed to access attributes of each attribute. Integer91+ parts in paths are looked up as integers.92+93+ The value returned by the returned callable is a list of extracted94+ attribute values.95+96+ Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.97+ """98+ attribute_parts = (99+ attribute.split(",") if isinstance(attribute, string_types) else [attribute]100+ )101+ attribute = [102+ _prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts103+ ]104+105+ def attrgetter(item):106+ items = [None] * len(attribute)107+ for i, attribute_part in enumerate(attribute):108+ item_i = item109+ for part in attribute_part:110+ item_i = environment.getitem(item_i, part)111+112+ if postprocess is not None:113+ item_i = postprocess(item_i)114+115+ items[i] = item_i116+ return items117+118+ return attrgetter119+120+121+def _prepare_attribute_parts(attr):122+ if attr is None:123+ return []124+ elif isinstance(attr, string_types):125+ return [int(x) if x.isdigit() else x for x in attr.split(".")]126+ else:127+ return [attr]128+129+130+def do_forceescape(value):131+ """Enforce HTML escaping. This will probably double escape variables."""132+ if hasattr(value, "__html__"):133+ value = value.__html__()134+ return escape(text_type(value))135+136+137+def do_urlencode(value):138+ """Quote data for use in a URL path or query using UTF-8.139+140+ Basic wrapper around :func:`urllib.parse.quote` when given a141+ string, or :func:`urllib.parse.urlencode` for a dict or iterable.142+143+ :param value: Data to quote. A string will be quoted directly. A144+ dict or iterable of ``(key, value)`` pairs will be joined as a145+ query string.146+147+ When given a string, "/" is not quoted. HTTP servers treat "/" and148+ "%2F" equivalently in paths. If you need quoted slashes, use the149+ ``|replace("/", "%2F")`` filter.150+151+ .. versionadded:: 2.7152+ """153+ if isinstance(value, string_types) or not isinstance(value, abc.Iterable):154+ return unicode_urlencode(value)155+156+ if isinstance(value, dict):157+ items = iteritems(value)158+ else:159+ items = iter(value)160+161+ return u"&".join(162+ "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))163+ for k, v in items164+ )165+166+167+@evalcontextfilter168+def do_replace(eval_ctx, s, old, new, count=None):169+ """Return a copy of the value with all occurrences of a substring170+ replaced with a new one. The first argument is the substring171+ that should be replaced, the second is the replacement string.172+ If the optional third argument ``count`` is given, only the first173+ ``count`` occurrences are replaced:174+175+ .. sourcecode:: jinja176+177+ {{ "Hello World"|replace("Hello", "Goodbye") }}178+ -> Goodbye World179+180+ {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}181+ -> d'oh, d'oh, aaargh182+ """183+ if count is None:184+ count = -1185+ if not eval_ctx.autoescape:186+ return text_type(s).replace(text_type(old), text_type(new), count)187+ if (188+ hasattr(old, "__html__")189+ or hasattr(new, "__html__")190+ and not hasattr(s, "__html__")191+ ):192+ s = escape(s)193+ else:194+ s = soft_unicode(s)195+ return s.replace(soft_unicode(old), soft_unicode(new), count)196+197+198+def do_upper(s):199+ """Convert a value to uppercase."""200+ return soft_unicode(s).upper()201+202+203+def do_lower(s):204+ """Convert a value to lowercase."""205+ return soft_unicode(s).lower()206+207+208+@evalcontextfilter209+def do_xmlattr(_eval_ctx, d, autospace=True):210+ """Create an SGML/XML attribute string based on the items in a dict.211+ All values that are neither `none` nor `undefined` are automatically212+ escaped:213+214+ .. sourcecode:: html+jinja215+216+ <ul{{ {'class': 'my_list', 'missing': none,217+ 'id': 'list-%d'|format(variable)}|xmlattr }}>218+ ...219+ </ul>220+221+ Results in something like this:222+223+ .. sourcecode:: html224+225+ <ul class="my_list" id="list-42">226+ ...227+ </ul>228+229+ As you can see it automatically prepends a space in front of the item230+ if the filter returned something unless the second parameter is false.231+ """232+ rv = u" ".join(233+ u'%s="%s"' % (escape(key), escape(value))234+ for key, value in iteritems(d)235+ if value is not None and not isinstance(value, Undefined)236+ )237+ if autospace and rv:238+ rv = u" " + rv239+ if _eval_ctx.autoescape:240+ rv = Markup(rv)241+ return rv242+243+244+def do_capitalize(s):245+ """Capitalize a value. The first character will be uppercase, all others246+ lowercase.247+ """248+ return soft_unicode(s).capitalize()249+250+251+def do_title(s):252+ """Return a titlecased version of the value. I.e. words will start with253+ uppercase letters, all remaining characters are lowercase.254+ """255+ return "".join(256+ [257+ item[0].upper() + item[1:].lower()258+ for item in _word_beginning_split_re.split(soft_unicode(s))259+ if item260+ ]261+ )262+263+264+def do_dictsort(value, case_sensitive=False, by="key", reverse=False):265+ """Sort a dict and yield (key, value) pairs. Because python dicts are266+ unsorted you may want to use this function to order them by either267+ key or value:268+269+ .. sourcecode:: jinja270+271+ {% for item in mydict|dictsort %}272+ sort the dict by key, case insensitive273+274+ {% for item in mydict|dictsort(reverse=true) %}275+ sort the dict by key, case insensitive, reverse order276+277+ {% for item in mydict|dictsort(true) %}278+ sort the dict by key, case sensitive279+280+ {% for item in mydict|dictsort(false, 'value') %}281+ sort the dict by value, case insensitive282+ """283+ if by == "key":284+ pos = 0285+ elif by == "value":286+ pos = 1287+ else:288+ raise FilterArgumentError('You can only sort by either "key" or "value"')289+290+ def sort_func(item):291+ value = item[pos]292+293+ if not case_sensitive:294+ value = ignore_case(value)295+296+ return value297+298+ return sorted(value.items(), key=sort_func, reverse=reverse)299+300+301+@environmentfilter302+def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):303+ """Sort an iterable using Python's :func:`sorted`.304+305+ .. sourcecode:: jinja306+307+ {% for city in cities|sort %}308+ ...309+ {% endfor %}310+311+ :param reverse: Sort descending instead of ascending.312+ :param case_sensitive: When sorting strings, sort upper and lower313+ case separately.314+ :param attribute: When sorting objects or dicts, an attribute or315+ key to sort by. Can use dot notation like ``"address.city"``.316+ Can be a list of attributes like ``"age,name"``.317+318+ The sort is stable, it does not change the relative order of319+ elements that compare equal. This makes it is possible to chain320+ sorts on different attributes and ordering.321+322+ .. sourcecode:: jinja323+324+ {% for user in users|sort(attribute="name")325+ |sort(reverse=true, attribute="age") %}326+ ...327+ {% endfor %}328+329+ As a shortcut to chaining when the direction is the same for all330+ attributes, pass a comma separate list of attributes.331+332+ .. sourcecode:: jinja333+334+ {% for user users|sort(attribute="age,name") %}335+ ...336+ {% endfor %}337+338+ .. versionchanged:: 2.11.0339+ The ``attribute`` parameter can be a comma separated list of340+ attributes, e.g. ``"age,name"``.341+342+ .. versionchanged:: 2.6343+ The ``attribute`` parameter was added.344+ """345+ key_func = make_multi_attrgetter(346+ environment, attribute, postprocess=ignore_case if not case_sensitive else None347+ )348+ return sorted(value, key=key_func, reverse=reverse)349+350+351+@environmentfilter352+def do_unique(environment, value, case_sensitive=False, attribute=None):353+ """Returns a list of unique items from the given iterable.354+355+ .. sourcecode:: jinja356+357+ {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}358+ -> ['foo', 'bar', 'foobar']359+360+ The unique items are yielded in the same order as their first occurrence in361+ the iterable passed to the filter.362+363+ :param case_sensitive: Treat upper and lower case strings as distinct.364+ :param attribute: Filter objects with unique values for this attribute.365+ """366+ getter = make_attrgetter(367+ environment, attribute, postprocess=ignore_case if not case_sensitive else None368+ )369+ seen = set()370+371+ for item in value:372+ key = getter(item)373+374+ if key not in seen:375+ seen.add(key)376+ yield item377+378+379+def _min_or_max(environment, value, func, case_sensitive, attribute):380+ it = iter(value)381+382+ try:383+ first = next(it)384+ except StopIteration:385+ return environment.undefined("No aggregated item, sequence was empty.")386+387+ key_func = make_attrgetter(388+ environment, attribute, postprocess=ignore_case if not case_sensitive else None389+ )390+ return func(chain([first], it), key=key_func)391+392+393+@environmentfilter394+def do_min(environment, value, case_sensitive=False, attribute=None):395+ """Return the smallest item from the sequence.396+397+ .. sourcecode:: jinja398+399+ {{ [1, 2, 3]|min }}400+ -> 1401+402+ :param case_sensitive: Treat upper and lower case strings as distinct.403+ :param attribute: Get the object with the min value of this attribute.404+ """405+ return _min_or_max(environment, value, min, case_sensitive, attribute)406+407+408+@environmentfilter409+def do_max(environment, value, case_sensitive=False, attribute=None):410+ """Return the largest item from the sequence.411+412+ .. sourcecode:: jinja413+414+ {{ [1, 2, 3]|max }}415+ -> 3416+417+ :param case_sensitive: Treat upper and lower case strings as distinct.418+ :param attribute: Get the object with the max value of this attribute.419+ """420+ return _min_or_max(environment, value, max, case_sensitive, attribute)421+422+423+def do_default(value, default_value=u"", boolean=False):424+ """If the value is undefined it will return the passed default value,425+ otherwise the value of the variable:426+427+ .. sourcecode:: jinja428+429+ {{ my_variable|default('my_variable is not defined') }}430+431+ This will output the value of ``my_variable`` if the variable was432+ defined, otherwise ``'my_variable is not defined'``. If you want433+ to use default with variables that evaluate to false you have to434+ set the second parameter to `true`:435+436+ .. sourcecode:: jinja437+438+ {{ ''|default('the string was empty', true) }}439+440+ .. versionchanged:: 2.11441+ It's now possible to configure the :class:`~jinja2.Environment` with442+ :class:`~jinja2.ChainableUndefined` to make the `default` filter work443+ on nested elements and attributes that may contain undefined values444+ in the chain without getting an :exc:`~jinja2.UndefinedError`.445+ """446+ if isinstance(value, Undefined) or (boolean and not value):447+ return default_value448+ return value449+450+451+@evalcontextfilter452+def do_join(eval_ctx, value, d=u"", attribute=None):453+ """Return a string which is the concatenation of the strings in the454+ sequence. The separator between elements is an empty string per455+ default, you can define it with the optional parameter:456+457+ .. sourcecode:: jinja458+459+ {{ [1, 2, 3]|join('|') }}460+ -> 1|2|3461+462+ {{ [1, 2, 3]|join }}463+ -> 123464+465+ It is also possible to join certain attributes of an object:466+467+ .. sourcecode:: jinja468+469+ {{ users|join(', ', attribute='username') }}470+471+ .. versionadded:: 2.6472+ The `attribute` parameter was added.473+ """474+ if attribute is not None:475+ value = imap(make_attrgetter(eval_ctx.environment, attribute), value)476+477+ # no automatic escaping? joining is a lot easier then478+ if not eval_ctx.autoescape:479+ return text_type(d).join(imap(text_type, value))480+481+ # if the delimiter doesn't have an html representation we check482+ # if any of the items has. If yes we do a coercion to Markup483+ if not hasattr(d, "__html__"):484+ value = list(value)485+ do_escape = False486+ for idx, item in enumerate(value):487+ if hasattr(item, "__html__"):488+ do_escape = True489+ else:490+ value[idx] = text_type(item)491+ if do_escape:492+ d = escape(d)493+ else:494+ d = text_type(d)495+ return d.join(value)496+497+ # no html involved, to normal joining498+ return soft_unicode(d).join(imap(soft_unicode, value))499+500+501+def do_center(value, width=80):502+ """Centers the value in a field of a given width."""503+ return text_type(value).center(width)504+505+506+@environmentfilter507+def do_first(environment, seq):508+ """Return the first item of a sequence."""509+ try:510+ return next(iter(seq))511+ except StopIteration:512+ return environment.undefined("No first item, sequence was empty.")513+514+515+@environmentfilter516+def do_last(environment, seq):517+ """518+ Return the last item of a sequence.519+520+ Note: Does not work with generators. You may want to explicitly521+ convert it to a list:522+523+ .. sourcecode:: jinja524+525+ {{ data | selectattr('name', '==', 'Jinja') | list | last }}526+ """527+ try:528+ return next(iter(reversed(seq)))529+ except StopIteration:530+ return environment.undefined("No last item, sequence was empty.")531+532+533+@contextfilter534+def do_random(context, seq):535+ """Return a random item from the sequence."""536+ try:537+ return random.choice(seq)538+ except IndexError:539+ return context.environment.undefined("No random item, sequence was empty.")540+541+542+def do_filesizeformat(value, binary=False):543+ """Format the value like a 'human-readable' file size (i.e. 13 kB,544+ 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,545+ Giga, etc.), if the second parameter is set to `True` the binary546+ prefixes are used (Mebi, Gibi).547+ """548+ bytes = float(value)549+ base = binary and 1024 or 1000550+ prefixes = [551+ (binary and "KiB" or "kB"),552+ (binary and "MiB" or "MB"),553+ (binary and "GiB" or "GB"),554+ (binary and "TiB" or "TB"),555+ (binary and "PiB" or "PB"),556+ (binary and "EiB" or "EB"),557+ (binary and "ZiB" or "ZB"),558+ (binary and "YiB" or "YB"),559+ ]560+ if bytes == 1:561+ return "1 Byte"562+ elif bytes < base:563+ return "%d Bytes" % bytes564+ else:565+ for i, prefix in enumerate(prefixes):566+ unit = base ** (i + 2)567+ if bytes < unit:568+ return "%.1f %s" % ((base * bytes / unit), prefix)569+ return "%.1f %s" % ((base * bytes / unit), prefix)570+571+572+def do_pprint(value, verbose=False):573+ """Pretty print a variable. Useful for debugging.574+575+ With Jinja 1.2 onwards you can pass it a parameter. If this parameter576+ is truthy the output will be more verbose (this requires `pretty`)577+ """578+ return pformat(value, verbose=verbose)579+580+581+@evalcontextfilter582+def do_urlize(583+ eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None584+):585+ """Converts URLs in plain text into clickable links.586+587+ If you pass the filter an additional integer it will shorten the urls588+ to that number. Also a third argument exists that makes the urls589+ "nofollow":590+591+ .. sourcecode:: jinja592+593+ {{ mytext|urlize(40, true) }}594+ links are shortened to 40 chars and defined with rel="nofollow"595+596+ If *target* is specified, the ``target`` attribute will be added to the597+ ``<a>`` tag:598+599+ .. sourcecode:: jinja600+601+ {{ mytext|urlize(40, target='_blank') }}602+603+ .. versionchanged:: 2.8+604+ The *target* parameter was added.605+ """606+ policies = eval_ctx.environment.policies607+ rel = set((rel or "").split() or [])608+ if nofollow:609+ rel.add("nofollow")610+ rel.update((policies["urlize.rel"] or "").split())611+ if target is None:612+ target = policies["urlize.target"]613+ rel = " ".join(sorted(rel)) or None614+ rv = urlize(value, trim_url_limit, rel=rel, target=target)615+ if eval_ctx.autoescape:616+ rv = Markup(rv)617+ return rv618+619+620+def do_indent(s, width=4, first=False, blank=False, indentfirst=None):621+ """Return a copy of the string with each line indented by 4 spaces. The622+ first line and blank lines are not indented by default.623+624+ :param width: Number of spaces to indent by.625+ :param first: Don't skip indenting the first line.626+ :param blank: Don't skip indenting empty lines.627+628+ .. versionchanged:: 2.10629+ Blank lines are not indented by default.630+631+ Rename the ``indentfirst`` argument to ``first``.632+ """633+ if indentfirst is not None:634+ warnings.warn(635+ "The 'indentfirst' argument is renamed to 'first' and will"636+ " be removed in version 3.0.",637+ DeprecationWarning,638+ stacklevel=2,639+ )640+ first = indentfirst641+642+ indention = u" " * width643+ newline = u"\n"644+645+ if isinstance(s, Markup):646+ indention = Markup(indention)647+ newline = Markup(newline)648+649+ s += newline # this quirk is necessary for splitlines method650+651+ if blank:652+ rv = (newline + indention).join(s.splitlines())653+ else:654+ lines = s.splitlines()655+ rv = lines.pop(0)656+657+ if lines:658+ rv += newline + newline.join(659+ indention + line if line else line for line in lines660+ )661+662+ if first:663+ rv = indention + rv664+665+ return rv666+667+668+@environmentfilter669+def do_truncate(env, s, length=255, killwords=False, end="...", leeway=None):670+ """Return a truncated copy of the string. The length is specified671+ with the first parameter which defaults to ``255``. If the second672+ parameter is ``true`` the filter will cut the text at length. Otherwise673+ it will discard the last word. If the text was in fact674+ truncated it will append an ellipsis sign (``"..."``). If you want a675+ different ellipsis sign than ``"..."`` you can specify it using the676+ third parameter. Strings that only exceed the length by the tolerance677+ margin given in the fourth parameter will not be truncated.678+679+ .. sourcecode:: jinja680+681+ {{ "foo bar baz qux"|truncate(9) }}682+ -> "foo..."683+ {{ "foo bar baz qux"|truncate(9, True) }}684+ -> "foo ba..."685+ {{ "foo bar baz qux"|truncate(11) }}686+ -> "foo bar baz qux"687+ {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}688+ -> "foo bar..."689+690+ The default leeway on newer Jinja versions is 5 and was 0 before but691+ can be reconfigured globally.692+ """693+ if leeway is None:694+ leeway = env.policies["truncate.leeway"]695+ assert length >= len(end), "expected length >= %s, got %s" % (len(end), length)696+ assert leeway >= 0, "expected leeway >= 0, got %s" % leeway697+ if len(s) <= length + leeway:698+ return s699+ if killwords:700+ return s[: length - len(end)] + end701+ result = s[: length - len(end)].rsplit(" ", 1)[0]702+ return result + end703+704+705+@environmentfilter706+def do_wordwrap(707+ environment,708+ s,709+ width=79,710+ break_long_words=True,711+ wrapstring=None,712+ break_on_hyphens=True,713+):714+ """Wrap a string to the given width. Existing newlines are treated715+ as paragraphs to be wrapped separately.716+717+ :param s: Original text to wrap.718+ :param width: Maximum length of wrapped lines.719+ :param break_long_words: If a word is longer than ``width``, break720+ it across lines.721+ :param break_on_hyphens: If a word contains hyphens, it may be split722+ across lines.723+ :param wrapstring: String to join each wrapped line. Defaults to724+ :attr:`Environment.newline_sequence`.725+726+ .. versionchanged:: 2.11727+ Existing newlines are treated as paragraphs wrapped separately.728+729+ .. versionchanged:: 2.11730+ Added the ``break_on_hyphens`` parameter.731+732+ .. versionchanged:: 2.7733+ Added the ``wrapstring`` parameter.734+ """735+736+ import textwrap737+738+ if not wrapstring:739+ wrapstring = environment.newline_sequence740+741+ # textwrap.wrap doesn't consider existing newlines when wrapping.742+ # If the string has a newline before width, wrap will still insert743+ # a newline at width, resulting in a short line. Instead, split and744+ # wrap each paragraph individually.745+ return wrapstring.join(746+ [747+ wrapstring.join(748+ textwrap.wrap(749+ line,750+ width=width,751+ expand_tabs=False,752+ replace_whitespace=False,753+ break_long_words=break_long_words,754+ break_on_hyphens=break_on_hyphens,755+ )756+ )757+ for line in s.splitlines()758+ ]759+ )760+761+762+def do_wordcount(s):763+ """Count the words in that string."""764+ return len(_word_re.findall(s))765+766+767+def do_int(value, default=0, base=10):768+ """Convert the value into an integer. If the769+ conversion doesn't work it will return ``0``. You can770+ override this default using the first parameter. You771+ can also override the default base (10) in the second772+ parameter, which handles input with prefixes such as773+ 0b, 0o and 0x for bases 2, 8 and 16 respectively.774+ The base is ignored for decimal numbers and non-string values.775+ """776+ try:777+ if isinstance(value, string_types):778+ return int(value, base)779+ return int(value)780+ except (TypeError, ValueError):781+ # this quirk is necessary so that "42.23"|int gives 42.782+ try:783+ return int(float(value))784+ except (TypeError, ValueError):785+ return default786+787+788+def do_float(value, default=0.0):789+ """Convert the value into a floating point number. If the790+ conversion doesn't work it will return ``0.0``. You can791+ override this default using the first parameter.792+ """793+ try:794+ return float(value)795+ except (TypeError, ValueError):796+ return default797+798+799+def do_format(value, *args, **kwargs):800+ """Apply the given values to a `printf-style`_ format string, like801+ ``string % values``.802+803+ .. sourcecode:: jinja804+805+ {{ "%s, %s!"|format(greeting, name) }}806+ Hello, World!807+808+ In most cases it should be more convenient and efficient to use the809+ ``%`` operator or :meth:`str.format`.810+811+ .. code-block:: text812+813+ {{ "%s, %s!" % (greeting, name) }}814+ {{ "{}, {}!".format(greeting, name) }}815+816+ .. _printf-style: https://docs.python.org/library/stdtypes.html817+ #printf-style-string-formatting818+ """819+ if args and kwargs:820+ raise FilterArgumentError(821+ "can't handle positional and keyword arguments at the same time"822+ )823+ return soft_unicode(value) % (kwargs or args)824+825+826+def do_trim(value, chars=None):827+ """Strip leading and trailing characters, by default whitespace."""828+ return soft_unicode(value).strip(chars)829+830+831+def do_striptags(value):832+ """Strip SGML/XML tags and replace adjacent whitespace by one space."""833+ if hasattr(value, "__html__"):834+ value = value.__html__()835+ return Markup(text_type(value)).striptags()836+837+838+def do_slice(value, slices, fill_with=None):839+ """Slice an iterator and return a list of lists containing840+ those items. Useful if you want to create a div containing841+ three ul tags that represent columns:842+843+ .. sourcecode:: html+jinja844+845+ <div class="columnwrapper">846+ {%- for column in items|slice(3) %}847+ <ul class="column-{{ loop.index }}">848+ {%- for item in column %}849+ <li>{{ item }}</li>850+ {%- endfor %}851+ </ul>852+ {%- endfor %}853+ </div>854+855+ If you pass it a second argument it's used to fill missing856+ values on the last iteration.857+ """858+ seq = list(value)859+ length = len(seq)860+ items_per_slice = length // slices861+ slices_with_extra = length % slices862+ offset = 0863+ for slice_number in range(slices):864+ start = offset + slice_number * items_per_slice865+ if slice_number < slices_with_extra:866+ offset += 1867+ end = offset + (slice_number + 1) * items_per_slice868+ tmp = seq[start:end]869+ if fill_with is not None and slice_number >= slices_with_extra:870+ tmp.append(fill_with)871+ yield tmp872+873+874+def do_batch(value, linecount, fill_with=None):875+ """876+ A filter that batches items. It works pretty much like `slice`877+ just the other way round. It returns a list of lists with the878+ given number of items. If you provide a second parameter this879+ is used to fill up missing items. See this example:880+881+ .. sourcecode:: html+jinja882+883+ <table>884+ {%- for row in items|batch(3, ' ') %}885+ <tr>886+ {%- for column in row %}887+ <td>{{ column }}</td>888+ {%- endfor %}889+ </tr>890+ {%- endfor %}891+ </table>892+ """893+ tmp = []894+ for item in value:895+ if len(tmp) == linecount:896+ yield tmp897+ tmp = []898+ tmp.append(item)899+ if tmp:900+ if fill_with is not None and len(tmp) < linecount:901+ tmp += [fill_with] * (linecount - len(tmp))902+ yield tmp903+904+905+def do_round(value, precision=0, method="common"):906+ """Round the number to a given precision. The first907+ parameter specifies the precision (default is ``0``), the908+ second the rounding method:909+910+ - ``'common'`` rounds either up or down911+ - ``'ceil'`` always rounds up912+ - ``'floor'`` always rounds down913+914+ If you don't specify a method ``'common'`` is used.915+916+ .. sourcecode:: jinja917+918+ {{ 42.55|round }}919+ -> 43.0920+ {{ 42.55|round(1, 'floor') }}921+ -> 42.5922+923+ Note that even if rounded to 0 precision, a float is returned. If924+ you need a real integer, pipe it through `int`:925+926+ .. sourcecode:: jinja927+928+ {{ 42.55|round|int }}929+ -> 43930+ """931+ if method not in {"common", "ceil", "floor"}:932+ raise FilterArgumentError("method must be common, ceil or floor")933+ if method == "common":934+ return round(value, precision)935+ func = getattr(math, method)936+ return func(value * (10 ** precision)) / (10 ** precision)937+938+939+# Use a regular tuple repr here. This is what we did in the past and we940+# really want to hide this custom type as much as possible. In particular941+# we do not want to accidentally expose an auto generated repr in case942+# people start to print this out in comments or something similar for943+# debugging.944+_GroupTuple = namedtuple("_GroupTuple", ["grouper", "list"])945+_GroupTuple.__repr__ = tuple.__repr__946+_GroupTuple.__str__ = tuple.__str__947+948+949+@environmentfilter950+def do_groupby(environment, value, attribute):951+ """Group a sequence of objects by an attribute using Python's952+ :func:`itertools.groupby`. The attribute can use dot notation for953+ nested access, like ``"address.city"``. Unlike Python's ``groupby``,954+ the values are sorted first so only one group is returned for each955+ unique value.956+957+ For example, a list of ``User`` objects with a ``city`` attribute958+ can be rendered in groups. In this example, ``grouper`` refers to959+ the ``city`` value of the group.960+961+ .. sourcecode:: html+jinja962+963+ <ul>{% for city, items in users|groupby("city") %}964+ <li>{{ city }}965+ <ul>{% for user in items %}966+ <li>{{ user.name }}967+ {% endfor %}</ul>968+ </li>969+ {% endfor %}</ul>970+971+ ``groupby`` yields namedtuples of ``(grouper, list)``, which972+ can be used instead of the tuple unpacking above. ``grouper`` is the973+ value of the attribute, and ``list`` is the items with that value.974+975+ .. sourcecode:: html+jinja976+977+ <ul>{% for group in users|groupby("city") %}978+ <li>{{ group.grouper }}: {{ group.list|join(", ") }}979+ {% endfor %}</ul>980+981+ .. versionchanged:: 2.6982+ The attribute supports dot notation for nested access.983+ """984+ expr = make_attrgetter(environment, attribute)985+ return [986+ _GroupTuple(key, list(values))987+ for key, values in groupby(sorted(value, key=expr), expr)988+ ]989+990+991+@environmentfilter992+def do_sum(environment, iterable, attribute=None, start=0):993+ """Returns the sum of a sequence of numbers plus the value of parameter994+ 'start' (which defaults to 0). When the sequence is empty it returns995+ start.996+997+ It is also possible to sum up only certain attributes:998+999+ .. sourcecode:: jinja1000+1001+ Total: {{ items|sum(attribute='price') }}1002+1003+ .. versionchanged:: 2.61004+ The `attribute` parameter was added to allow suming up over1005+ attributes. Also the `start` parameter was moved on to the right.1006+ """1007+ if attribute is not None:1008+ iterable = imap(make_attrgetter(environment, attribute), iterable)1009+ return sum(iterable, start)1010+1011+1012+def do_list(value):1013+ """Convert the value into a list. If it was a string the returned list1014+ will be a list of characters.1015+ """1016+ return list(value)1017+1018+1019+def do_mark_safe(value):1020+ """Mark the value as safe which means that in an environment with automatic1021+ escaping enabled this variable will not be escaped.1022+ """1023+ return Markup(value)1024+1025+1026+def do_mark_unsafe(value):1027+ """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1028+ return text_type(value)1029+1030+1031+def do_reverse(value):1032+ """Reverse the object or return an iterator that iterates over it the other1033+ way round.1034+ """1035+ if isinstance(value, string_types):1036+ return value[::-1]1037+ try:1038+ return reversed(value)1039+ except TypeError:1040+ try:1041+ rv = list(value)1042+ rv.reverse()1043+ return rv1044+ except TypeError:1045+ raise FilterArgumentError("argument must be iterable")1046+1047+1048+@environmentfilter1049+def do_attr(environment, obj, name):1050+ """Get an attribute of an object. ``foo|attr("bar")`` works like1051+ ``foo.bar`` just that always an attribute is returned and items are not1052+ looked up.1053+1054+ See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.1055+ """1056+ try:1057+ name = str(name)1058+ except UnicodeError:1059+ pass1060+ else:1061+ try:1062+ value = getattr(obj, name)1063+ except AttributeError:1064+ pass1065+ else:1066+ if environment.sandboxed and not environment.is_safe_attribute(1067+ obj, name, value1068+ ):1069+ return environment.unsafe_undefined(obj, name)1070+ return value1071+ return environment.undefined(obj=obj, name=name)1072+1073+1074+@contextfilter1075+def do_map(*args, **kwargs):1076+ """Applies a filter on a sequence of objects or looks up an attribute.1077+ This is useful when dealing with lists of objects but you are really1078+ only interested in a certain value of it.1079+1080+ The basic usage is mapping on an attribute. Imagine you have a list1081+ of users but you are only interested in a list of usernames:1082+1083+ .. sourcecode:: jinja1084+1085+ Users on this page: {{ users|map(attribute='username')|join(', ') }}1086+1087+ You can specify a ``default`` value to use if an object in the list1088+ does not have the given attribute.1089+1090+ .. sourcecode:: jinja1091+1092+ {{ users|map(attribute="username", default="Anonymous")|join(", ") }}1093+1094+ Alternatively you can let it invoke a filter by passing the name of the1095+ filter and the arguments afterwards. A good example would be applying a1096+ text conversion filter on a sequence:1097+1098+ .. sourcecode:: jinja1099+1100+ Users on this page: {{ titles|map('lower')|join(', ') }}1101+1102+ Similar to a generator comprehension such as:1103+1104+ .. code-block:: python1105+1106+ (u.username for u in users)1107+ (u.username or "Anonymous" for u in users)1108+ (do_lower(x) for x in titles)1109+1110+ .. versionchanged:: 2.11.01111+ Added the ``default`` parameter.1112+1113+ .. versionadded:: 2.71114+ """1115+ seq, func = prepare_map(args, kwargs)1116+ if seq:1117+ for item in seq:1118+ yield func(item)1119+1120+1121+@contextfilter1122+def do_select(*args, **kwargs):1123+ """Filters a sequence of objects by applying a test to each object,1124+ and only selecting the objects with the test succeeding.1125+1126+ If no test is specified, each object will be evaluated as a boolean.1127+1128+ Example usage:1129+1130+ .. sourcecode:: jinja1131+1132+ {{ numbers|select("odd") }}1133+ {{ numbers|select("odd") }}1134+ {{ numbers|select("divisibleby", 3) }}1135+ {{ numbers|select("lessthan", 42) }}1136+ {{ strings|select("equalto", "mystring") }}1137+1138+ Similar to a generator comprehension such as:1139+1140+ .. code-block:: python1141+1142+ (n for n in numbers if test_odd(n))1143+ (n for n in numbers if test_divisibleby(n, 3))1144+1145+ .. versionadded:: 2.71146+ """1147+ return select_or_reject(args, kwargs, lambda x: x, False)1148+1149+1150+@contextfilter1151+def do_reject(*args, **kwargs):1152+ """Filters a sequence of objects by applying a test to each object,1153+ and rejecting the objects with the test succeeding.1154+1155+ If no test is specified, each object will be evaluated as a boolean.1156+1157+ Example usage:1158+1159+ .. sourcecode:: jinja1160+1161+ {{ numbers|reject("odd") }}1162+1163+ Similar to a generator comprehension such as:1164+1165+ .. code-block:: python1166+1167+ (n for n in numbers if not test_odd(n))1168+1169+ .. versionadded:: 2.71170+ """1171+ return select_or_reject(args, kwargs, lambda x: not x, False)1172+1173+1174+@contextfilter1175+def do_selectattr(*args, **kwargs):1176+ """Filters a sequence of objects by applying a test to the specified1177+ attribute of each object, and only selecting the objects with the1178+ test succeeding.1179+1180+ If no test is specified, the attribute's value will be evaluated as1181+ a boolean.1182+1183+ Example usage:1184+1185+ .. sourcecode:: jinja1186+1187+ {{ users|selectattr("is_active") }}1188+ {{ users|selectattr("email", "none") }}1189+1190+ Similar to a generator comprehension such as:1191+1192+ .. code-block:: python1193+1194+ (u for user in users if user.is_active)1195+ (u for user in users if test_none(user.email))1196+1197+ .. versionadded:: 2.71198+ """1199+ return select_or_reject(args, kwargs, lambda x: x, True)1200+1201+1202+@contextfilter1203+def do_rejectattr(*args, **kwargs):1204+ """Filters a sequence of objects by applying a test to the specified1205+ attribute of each object, and rejecting the objects with the test1206+ succeeding.1207+1208+ If no test is specified, the attribute's value will be evaluated as1209+ a boolean.1210+1211+ .. sourcecode:: jinja1212+1213+ {{ users|rejectattr("is_active") }}1214+ {{ users|rejectattr("email", "none") }}1215+1216+ Similar to a generator comprehension such as:1217+1218+ .. code-block:: python1219+1220+ (u for user in users if not user.is_active)1221+ (u for user in users if not test_none(user.email))1222+1223+ .. versionadded:: 2.71224+ """1225+ return select_or_reject(args, kwargs, lambda x: not x, True)1226+1227+1228+@evalcontextfilter1229+def do_tojson(eval_ctx, value, indent=None):1230+ """Dumps a structure to JSON so that it's safe to use in ``<script>``1231+ tags. It accepts the same arguments and returns a JSON string. Note that1232+ this is available in templates through the ``|tojson`` filter which will1233+ also mark the result as safe. Due to how this function escapes certain1234+ characters this is safe even if used outside of ``<script>`` tags.1235+1236+ The following characters are escaped in strings:1237+1238+ - ``<``1239+ - ``>``1240+ - ``&``1241+ - ``'``1242+1243+ This makes it safe to embed such strings in any place in HTML with the1244+ notable exception of double quoted attributes. In that case single1245+ quote your attributes or HTML escape it in addition.1246+1247+ The indent parameter can be used to enable pretty printing. Set it to1248+ the number of spaces that the structures should be indented with.1249+1250+ Note that this filter is for use in HTML contexts only.1251+1252+ .. versionadded:: 2.91253+ """1254+ policies = eval_ctx.environment.policies1255+ dumper = policies["json.dumps_function"]1256+ options = policies["json.dumps_kwargs"]1257+ if indent is not None:1258+ options = dict(options)1259+ options["indent"] = indent1260+ return htmlsafe_json_dumps(value, dumper=dumper, **options)1261+1262+1263+def prepare_map(args, kwargs):1264+ context = args[0]1265+ seq = args[1]1266+ default = None1267+1268+ if len(args) == 2 and "attribute" in kwargs:1269+ attribute = kwargs.pop("attribute")1270+ default = kwargs.pop("default", None)1271+ if kwargs:1272+ raise FilterArgumentError(1273+ "Unexpected keyword argument %r" % next(iter(kwargs))1274+ )1275+ func = make_attrgetter(context.environment, attribute, default=default)1276+ else:1277+ try:1278+ name = args[2]1279+ args = args[3:]1280+ except LookupError:1281+ raise FilterArgumentError("map requires a filter argument")1282+1283+ def func(item):1284+ return context.environment.call_filter(1285+ name, item, args, kwargs, context=context1286+ )1287+1288+ return seq, func1289+1290+1291+def prepare_select_or_reject(args, kwargs, modfunc, lookup_attr):1292+ context = args[0]1293+ seq = args[1]1294+ if lookup_attr:1295+ try:1296+ attr = args[2]1297+ except LookupError:1298+ raise FilterArgumentError("Missing parameter for attribute name")1299+ transfunc = make_attrgetter(context.environment, attr)1300+ off = 11301+ else:1302+ off = 01303+1304+ def transfunc(x):1305+ return x1306+1307+ try:1308+ name = args[2 + off]1309+ args = args[3 + off :]1310+1311+ def func(item):1312+ return context.environment.call_test(name, item, args, kwargs)1313+1314+ except LookupError:1315+ func = bool1316+1317+ return seq, lambda item: modfunc(func(transfunc(item)))1318+1319+1320+def select_or_reject(args, kwargs, modfunc, lookup_attr):1321+ seq, func = prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)1322+ if seq:1323+ for item in seq:1324+ if func(item):1325+ yield item1326+1327+1328+FILTERS = {1329+ "abs": abs,1330+ "attr": do_attr,1331+ "batch": do_batch,1332+ "capitalize": do_capitalize,1333+ "center": do_center,1334+ "count": len,1335+ "d": do_default,1336+ "default": do_default,1337+ "dictsort": do_dictsort,1338+ "e": escape,1339+ "escape": escape,1340+ "filesizeformat": do_filesizeformat,1341+ "first": do_first,1342+ "float": do_float,1343+ "forceescape": do_forceescape,1344+ "format": do_format,1345+ "groupby": do_groupby,1346+ "indent": do_indent,1347+ "int": do_int,1348+ "join": do_join,1349+ "last": do_last,1350+ "length": len,1351+ "list": do_list,1352+ "lower": do_lower,1353+ "map": do_map,1354+ "min": do_min,1355+ "max": do_max,1356+ "pprint": do_pprint,1357+ "random": do_random,1358+ "reject": do_reject,1359+ "rejectattr": do_rejectattr,1360+ "replace": do_replace,1361+ "reverse": do_reverse,1362+ "round": do_round,1363+ "safe": do_mark_safe,1364+ "select": do_select,1365+ "selectattr": do_selectattr,1366+ "slice": do_slice,1367+ "sort": do_sort,1368+ "string": soft_unicode,1369+ "striptags": do_striptags,1370+ "sum": do_sum,1371+ "title": do_title,1372+ "trim": do_trim,1373+ "truncate": do_truncate,1374+ "unique": do_unique,1375+ "upper": do_upper,1376+ "urlencode": do_urlencode,1377+ "urlize": do_urlize,1378+ "wordcount": do_wordcount,1379+ "wordwrap": do_wordwrap,1380+ "xmlattr": do_xmlattr,1381+ "tojson": do_tojson,1382+}added:src/jinja/idtracking.py+290 added
1+from ._compat import iteritems2+from .visitor import NodeVisitor3+4+VAR_LOAD_PARAMETER = "param"5+VAR_LOAD_RESOLVE = "resolve"6+VAR_LOAD_ALIAS = "alias"7+VAR_LOAD_UNDEFINED = "undefined"8+9+10+def find_symbols(nodes, parent_symbols=None):11+ sym = Symbols(parent=parent_symbols)12+ visitor = FrameSymbolVisitor(sym)13+ for node in nodes:14+ visitor.visit(node)15+ return sym16+17+18+def symbols_for_node(node, parent_symbols=None):19+ sym = Symbols(parent=parent_symbols)20+ sym.analyze_node(node)21+ return sym22+23+24+class Symbols(object):25+ def __init__(self, parent=None, level=None):26+ if level is None:27+ if parent is None:28+ level = 029+ else:30+ level = parent.level + 131+ self.level = level32+ self.parent = parent33+ self.refs = {}34+ self.loads = {}35+ self.stores = set()36+37+ def analyze_node(self, node, **kwargs):38+ visitor = RootVisitor(self)39+ visitor.visit(node, **kwargs)40+41+ def _define_ref(self, name, load=None):42+ ident = "l_%d_%s" % (self.level, name)43+ self.refs[name] = ident44+ if load is not None:45+ self.loads[ident] = load46+ return ident47+48+ def find_load(self, target):49+ if target in self.loads:50+ return self.loads[target]51+ if self.parent is not None:52+ return self.parent.find_load(target)53+54+ def find_ref(self, name):55+ if name in self.refs:56+ return self.refs[name]57+ if self.parent is not None:58+ return self.parent.find_ref(name)59+60+ def ref(self, name):61+ rv = self.find_ref(name)62+ if rv is None:63+ raise AssertionError(64+ "Tried to resolve a name to a reference that "65+ "was unknown to the frame (%r)" % name66+ )67+ return rv68+69+ def copy(self):70+ rv = object.__new__(self.__class__)71+ rv.__dict__.update(self.__dict__)72+ rv.refs = self.refs.copy()73+ rv.loads = self.loads.copy()74+ rv.stores = self.stores.copy()75+ return rv76+77+ def store(self, name):78+ self.stores.add(name)79+80+ # If we have not see the name referenced yet, we need to figure81+ # out what to set it to.82+ if name not in self.refs:83+ # If there is a parent scope we check if the name has a84+ # reference there. If it does it means we might have to alias85+ # to a variable there.86+ if self.parent is not None:87+ outer_ref = self.parent.find_ref(name)88+ if outer_ref is not None:89+ self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref))90+ return91+92+ # Otherwise we can just set it to undefined.93+ self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))94+95+ def declare_parameter(self, name):96+ self.stores.add(name)97+ return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))98+99+ def load(self, name):100+ target = self.find_ref(name)101+ if target is None:102+ self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))103+104+ def branch_update(self, branch_symbols):105+ stores = {}106+ for branch in branch_symbols:107+ for target in branch.stores:108+ if target in self.stores:109+ continue110+ stores[target] = stores.get(target, 0) + 1111+112+ for sym in branch_symbols:113+ self.refs.update(sym.refs)114+ self.loads.update(sym.loads)115+ self.stores.update(sym.stores)116+117+ for name, branch_count in iteritems(stores):118+ if branch_count == len(branch_symbols):119+ continue120+ target = self.find_ref(name)121+ assert target is not None, "should not happen"122+123+ if self.parent is not None:124+ outer_target = self.parent.find_ref(name)125+ if outer_target is not None:126+ self.loads[target] = (VAR_LOAD_ALIAS, outer_target)127+ continue128+ self.loads[target] = (VAR_LOAD_RESOLVE, name)129+130+ def dump_stores(self):131+ rv = {}132+ node = self133+ while node is not None:134+ for name in node.stores:135+ if name not in rv:136+ rv[name] = self.find_ref(name)137+ node = node.parent138+ return rv139+140+ def dump_param_targets(self):141+ rv = set()142+ node = self143+ while node is not None:144+ for target, (instr, _) in iteritems(self.loads):145+ if instr == VAR_LOAD_PARAMETER:146+ rv.add(target)147+ node = node.parent148+ return rv149+150+151+class RootVisitor(NodeVisitor):152+ def __init__(self, symbols):153+ self.sym_visitor = FrameSymbolVisitor(symbols)154+155+ def _simple_visit(self, node, **kwargs):156+ for child in node.iter_child_nodes():157+ self.sym_visitor.visit(child)158+159+ visit_Template = (160+ visit_Block161+ ) = (162+ visit_Macro163+ ) = (164+ visit_FilterBlock165+ ) = visit_Scope = visit_If = visit_ScopedEvalContextModifier = _simple_visit166+167+ def visit_AssignBlock(self, node, **kwargs):168+ for child in node.body:169+ self.sym_visitor.visit(child)170+171+ def visit_CallBlock(self, node, **kwargs):172+ for child in node.iter_child_nodes(exclude=("call",)):173+ self.sym_visitor.visit(child)174+175+ def visit_OverlayScope(self, node, **kwargs):176+ for child in node.body:177+ self.sym_visitor.visit(child)178+179+ def visit_For(self, node, for_branch="body", **kwargs):180+ if for_branch == "body":181+ self.sym_visitor.visit(node.target, store_as_param=True)182+ branch = node.body183+ elif for_branch == "else":184+ branch = node.else_185+ elif for_branch == "test":186+ self.sym_visitor.visit(node.target, store_as_param=True)187+ if node.test is not None:188+ self.sym_visitor.visit(node.test)189+ return190+ else:191+ raise RuntimeError("Unknown for branch")192+ for item in branch or ():193+ self.sym_visitor.visit(item)194+195+ def visit_With(self, node, **kwargs):196+ for target in node.targets:197+ self.sym_visitor.visit(target)198+ for child in node.body:199+ self.sym_visitor.visit(child)200+201+ def generic_visit(self, node, *args, **kwargs):202+ raise NotImplementedError(203+ "Cannot find symbols for %r" % node.__class__.__name__204+ )205+206+207+class FrameSymbolVisitor(NodeVisitor):208+ """A visitor for `Frame.inspect`."""209+210+ def __init__(self, symbols):211+ self.symbols = symbols212+213+ def visit_Name(self, node, store_as_param=False, **kwargs):214+ """All assignments to names go through this function."""215+ if store_as_param or node.ctx == "param":216+ self.symbols.declare_parameter(node.name)217+ elif node.ctx == "store":218+ self.symbols.store(node.name)219+ elif node.ctx == "load":220+ self.symbols.load(node.name)221+222+ def visit_NSRef(self, node, **kwargs):223+ self.symbols.load(node.name)224+225+ def visit_If(self, node, **kwargs):226+ self.visit(node.test, **kwargs)227+228+ original_symbols = self.symbols229+230+ def inner_visit(nodes):231+ self.symbols = rv = original_symbols.copy()232+ for subnode in nodes:233+ self.visit(subnode, **kwargs)234+ self.symbols = original_symbols235+ return rv236+237+ body_symbols = inner_visit(node.body)238+ elif_symbols = inner_visit(node.elif_)239+ else_symbols = inner_visit(node.else_ or ())240+241+ self.symbols.branch_update([body_symbols, elif_symbols, else_symbols])242+243+ def visit_Macro(self, node, **kwargs):244+ self.symbols.store(node.name)245+246+ def visit_Import(self, node, **kwargs):247+ self.generic_visit(node, **kwargs)248+ self.symbols.store(node.target)249+250+ def visit_FromImport(self, node, **kwargs):251+ self.generic_visit(node, **kwargs)252+ for name in node.names:253+ if isinstance(name, tuple):254+ self.symbols.store(name[1])255+ else:256+ self.symbols.store(name)257+258+ def visit_Assign(self, node, **kwargs):259+ """Visit assignments in the correct order."""260+ self.visit(node.node, **kwargs)261+ self.visit(node.target, **kwargs)262+263+ def visit_For(self, node, **kwargs):264+ """Visiting stops at for blocks. However the block sequence265+ is visited as part of the outer scope.266+ """267+ self.visit(node.iter, **kwargs)268+269+ def visit_CallBlock(self, node, **kwargs):270+ self.visit(node.call, **kwargs)271+272+ def visit_FilterBlock(self, node, **kwargs):273+ self.visit(node.filter, **kwargs)274+275+ def visit_With(self, node, **kwargs):276+ for target in node.values:277+ self.visit(target)278+279+ def visit_AssignBlock(self, node, **kwargs):280+ """Stop visiting at block assigns."""281+ self.visit(node.target, **kwargs)282+283+ def visit_Scope(self, node, **kwargs):284+ """Stop visiting at scopes."""285+286+ def visit_Block(self, node, **kwargs):287+ """Stop visiting at blocks."""288+289+ def visit_OverlayScope(self, node, **kwargs):290+ """Do not visit into overlay scopes."""added:src/jinja/lexer.py+841 added
1+# -*- coding: utf-8 -*-2+"""Implements a Jinja / Python combination lexer. The ``Lexer`` class3+is used to do some preprocessing. It filters out invalid operators like4+the bitshift operators we don't allow in templates. It separates5+template code and python code in expressions.6+"""7+import re8+from ast import literal_eval9+from collections import deque10+from operator import itemgetter11+12+from ._compat import implements_iterator13+from ._compat import intern14+from ._compat import iteritems15+from ._compat import text_type16+from .exceptions import TemplateSyntaxError17+from .utils import LRUCache18+19+# cache for the lexers. Exists in order to be able to have multiple20+# environments with the same lexer21+_lexer_cache = LRUCache(50)22+23+# static regular expressions24+whitespace_re = re.compile(r"\s+", re.U)25+newline_re = re.compile(r"(\r\n|\r|\n)")26+string_re = re.compile(27+ r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S28+)29+integer_re = re.compile(r"(\d+_)*\d+")30+float_re = re.compile(31+ r"""32+ (?<!\.) # doesn't start with a .33+ (\d+_)*\d+ # digits, possibly _ separated34+ (35+ (\.(\d+_)*\d+)? # optional fractional part36+ e[+\-]?(\d+_)*\d+ # exponent part37+ |38+ \.(\d+_)*\d+ # required fractional part39+ )40+ """,41+ re.IGNORECASE | re.VERBOSE,42+)43+44+try:45+ # check if this Python supports Unicode identifiers46+ compile("föö", "<unknown>", "eval")47+except SyntaxError:48+ # Python 2, no Unicode support, use ASCII identifiers49+ name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*")50+ check_ident = False51+else:52+ # Unicode support, import generated re pattern and set flag to use53+ # str.isidentifier to validate during lexing.54+ from ._identifier import pattern as name_re55+56+ check_ident = True57+58+# internal the tokens and keep references to them59+TOKEN_ADD = intern("add")60+TOKEN_ASSIGN = intern("assign")61+TOKEN_COLON = intern("colon")62+TOKEN_COMMA = intern("comma")63+TOKEN_DIV = intern("div")64+TOKEN_DOT = intern("dot")65+TOKEN_EQ = intern("eq")66+TOKEN_FLOORDIV = intern("floordiv")67+TOKEN_GT = intern("gt")68+TOKEN_GTEQ = intern("gteq")69+TOKEN_LBRACE = intern("lbrace")70+TOKEN_LBRACKET = intern("lbracket")71+TOKEN_LPAREN = intern("lparen")72+TOKEN_LT = intern("lt")73+TOKEN_LTEQ = intern("lteq")74+TOKEN_MOD = intern("mod")75+TOKEN_MUL = intern("mul")76+TOKEN_NE = intern("ne")77+TOKEN_PIPE = intern("pipe")78+TOKEN_POW = intern("pow")79+TOKEN_RBRACE = intern("rbrace")80+TOKEN_RBRACKET = intern("rbracket")81+TOKEN_RPAREN = intern("rparen")82+TOKEN_SEMICOLON = intern("semicolon")83+TOKEN_SUB = intern("sub")84+TOKEN_TILDE = intern("tilde")85+TOKEN_WHITESPACE = intern("whitespace")86+TOKEN_FLOAT = intern("float")87+TOKEN_INTEGER = intern("integer")88+TOKEN_NAME = intern("name")89+TOKEN_STRING = intern("string")90+TOKEN_OPERATOR = intern("operator")91+TOKEN_BLOCK_BEGIN = intern("block_begin")92+TOKEN_BLOCK_END = intern("block_end")93+TOKEN_VARIABLE_BEGIN = intern("variable_begin")94+TOKEN_VARIABLE_END = intern("variable_end")95+TOKEN_RAW_BEGIN = intern("raw_begin")96+TOKEN_RAW_END = intern("raw_end")97+TOKEN_COMMENT_BEGIN = intern("comment_begin")98+TOKEN_COMMENT_END = intern("comment_end")99+TOKEN_COMMENT = intern("comment")100+TOKEN_LINESTATEMENT_BEGIN = intern("linestatement_begin")101+TOKEN_LINESTATEMENT_END = intern("linestatement_end")102+TOKEN_LINECOMMENT_BEGIN = intern("linecomment_begin")103+TOKEN_LINECOMMENT_END = intern("linecomment_end")104+TOKEN_LINECOMMENT = intern("linecomment")105+TOKEN_DATA = intern("data")106+TOKEN_INITIAL = intern("initial")107+TOKEN_EOF = intern("eof")108+109+# bind operators to token types110+operators = {111+ "+": TOKEN_ADD,112+ "-": TOKEN_SUB,113+ "/": TOKEN_DIV,114+ "//": TOKEN_FLOORDIV,115+ "*": TOKEN_MUL,116+ "%": TOKEN_MOD,117+ "**": TOKEN_POW,118+ "~": TOKEN_TILDE,119+ "[": TOKEN_LBRACKET,120+ "]": TOKEN_RBRACKET,121+ "(": TOKEN_LPAREN,122+ ")": TOKEN_RPAREN,123+ "{": TOKEN_LBRACE,124+ "}": TOKEN_RBRACE,125+ "==": TOKEN_EQ,126+ "!=": TOKEN_NE,127+ ">": TOKEN_GT,128+ ">=": TOKEN_GTEQ,129+ "<": TOKEN_LT,130+ "<=": TOKEN_LTEQ,131+ "=": TOKEN_ASSIGN,132+ ".": TOKEN_DOT,133+ ":": TOKEN_COLON,134+ "|": TOKEN_PIPE,135+ ",": TOKEN_COMMA,136+ ";": TOKEN_SEMICOLON,137+}138+139+reverse_operators = dict([(v, k) for k, v in iteritems(operators)])140+assert len(operators) == len(reverse_operators), "operators dropped"141+operator_re = re.compile(142+ "(%s)" % "|".join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))143+)144+145+ignored_tokens = frozenset(146+ [147+ TOKEN_COMMENT_BEGIN,148+ TOKEN_COMMENT,149+ TOKEN_COMMENT_END,150+ TOKEN_WHITESPACE,151+ TOKEN_LINECOMMENT_BEGIN,152+ TOKEN_LINECOMMENT_END,153+ TOKEN_LINECOMMENT,154+ ]155+)156+ignore_if_empty = frozenset(157+ [TOKEN_WHITESPACE, TOKEN_DATA, TOKEN_COMMENT, TOKEN_LINECOMMENT]158+)159+160+161+def _describe_token_type(token_type):162+ if token_type in reverse_operators:163+ return reverse_operators[token_type]164+ return {165+ TOKEN_COMMENT_BEGIN: "begin of comment",166+ TOKEN_COMMENT_END: "end of comment",167+ TOKEN_COMMENT: "comment",168+ TOKEN_LINECOMMENT: "comment",169+ TOKEN_BLOCK_BEGIN: "begin of statement block",170+ TOKEN_BLOCK_END: "end of statement block",171+ TOKEN_VARIABLE_BEGIN: "begin of print statement",172+ TOKEN_VARIABLE_END: "end of print statement",173+ TOKEN_LINESTATEMENT_BEGIN: "begin of line statement",174+ TOKEN_LINESTATEMENT_END: "end of line statement",175+ TOKEN_DATA: "template data / text",176+ TOKEN_EOF: "end of template",177+ }.get(token_type, token_type)178+179+180+def describe_token(token):181+ """Returns a description of the token."""182+ if token.type == TOKEN_NAME:183+ return token.value184+ return _describe_token_type(token.type)185+186+187+def describe_token_expr(expr):188+ """Like `describe_token` but for token expressions."""189+ if ":" in expr:190+ type, value = expr.split(":", 1)191+ if type == TOKEN_NAME:192+ return value193+ else:194+ type = expr195+ return _describe_token_type(type)196+197+198+def count_newlines(value):199+ """Count the number of newline characters in the string. This is200+ useful for extensions that filter a stream.201+ """202+ return len(newline_re.findall(value))203+204+205+def compile_rules(environment):206+ """Compiles all the rules from the environment into a list of rules."""207+ e = re.escape208+ rules = [209+ (210+ len(environment.comment_start_string),211+ TOKEN_COMMENT_BEGIN,212+ e(environment.comment_start_string),213+ ),214+ (215+ len(environment.block_start_string),216+ TOKEN_BLOCK_BEGIN,217+ e(environment.block_start_string),218+ ),219+ (220+ len(environment.variable_start_string),221+ TOKEN_VARIABLE_BEGIN,222+ e(environment.variable_start_string),223+ ),224+ ]225+226+ if environment.line_statement_prefix is not None:227+ rules.append(228+ (229+ len(environment.line_statement_prefix),230+ TOKEN_LINESTATEMENT_BEGIN,231+ r"^[ \t\v]*" + e(environment.line_statement_prefix),232+ )233+ )234+ if environment.line_comment_prefix is not None:235+ rules.append(236+ (237+ len(environment.line_comment_prefix),238+ TOKEN_LINECOMMENT_BEGIN,239+ r"(?:^|(?<=\S))[^\S\r\n]*" + e(environment.line_comment_prefix),240+ )241+ )242+243+ return [x[1:] for x in sorted(rules, reverse=True)]244+245+246+class Failure(object):247+ """Class that raises a `TemplateSyntaxError` if called.248+ Used by the `Lexer` to specify known errors.249+ """250+251+ def __init__(self, message, cls=TemplateSyntaxError):252+ self.message = message253+ self.error_class = cls254+255+ def __call__(self, lineno, filename):256+ raise self.error_class(self.message, lineno, filename)257+258+259+class Token(tuple):260+ """Token class."""261+262+ __slots__ = ()263+ lineno, type, value = (property(itemgetter(x)) for x in range(3))264+265+ def __new__(cls, lineno, type, value):266+ return tuple.__new__(cls, (lineno, intern(str(type)), value))267+268+ def __str__(self):269+ if self.type in reverse_operators:270+ return reverse_operators[self.type]271+ elif self.type == "name":272+ return self.value273+ return self.type274+275+ def test(self, expr):276+ """Test a token against a token expression. This can either be a277+ token type or ``'token_type:token_value'``. This can only test278+ against string values and types.279+ """280+ # here we do a regular string equality check as test_any is usually281+ # passed an iterable of not interned strings.282+ if self.type == expr:283+ return True284+ elif ":" in expr:285+ return expr.split(":", 1) == [self.type, self.value]286+ return False287+288+ def test_any(self, *iterable):289+ """Test against multiple token expressions."""290+ for expr in iterable:291+ if self.test(expr):292+ return True293+ return False294+295+ def __repr__(self):296+ return "Token(%r, %r, %r)" % (self.lineno, self.type, self.value)297+298+299+@implements_iterator300+class TokenStreamIterator(object):301+ """The iterator for tokenstreams. Iterate over the stream302+ until the eof token is reached.303+ """304+305+ def __init__(self, stream):306+ self.stream = stream307+308+ def __iter__(self):309+ return self310+311+ def __next__(self):312+ token = self.stream.current313+ if token.type is TOKEN_EOF:314+ self.stream.close()315+ raise StopIteration()316+ next(self.stream)317+ return token318+319+320+@implements_iterator321+class TokenStream(object):322+ """A token stream is an iterable that yields :class:`Token`\\s. The323+ parser however does not iterate over it but calls :meth:`next` to go324+ one token ahead. The current active token is stored as :attr:`current`.325+ """326+327+ def __init__(self, generator, name, filename):328+ self._iter = iter(generator)329+ self._pushed = deque()330+ self.name = name331+ self.filename = filename332+ self.closed = False333+ self.current = Token(1, TOKEN_INITIAL, "")334+ next(self)335+336+ def __iter__(self):337+ return TokenStreamIterator(self)338+339+ def __bool__(self):340+ return bool(self._pushed) or self.current.type is not TOKEN_EOF341+342+ __nonzero__ = __bool__ # py2343+344+ @property345+ def eos(self):346+ """Are we at the end of the stream?"""347+ return not self348+349+ def push(self, token):350+ """Push a token back to the stream."""351+ self._pushed.append(token)352+353+ def look(self):354+ """Look at the next token."""355+ old_token = next(self)356+ result = self.current357+ self.push(result)358+ self.current = old_token359+ return result360+361+ def skip(self, n=1):362+ """Got n tokens ahead."""363+ for _ in range(n):364+ next(self)365+366+ def next_if(self, expr):367+ """Perform the token test and return the token if it matched.368+ Otherwise the return value is `None`.369+ """370+ if self.current.test(expr):371+ return next(self)372+373+ def skip_if(self, expr):374+ """Like :meth:`next_if` but only returns `True` or `False`."""375+ return self.next_if(expr) is not None376+377+ def __next__(self):378+ """Go one token ahead and return the old one.379+380+ Use the built-in :func:`next` instead of calling this directly.381+ """382+ rv = self.current383+ if self._pushed:384+ self.current = self._pushed.popleft()385+ elif self.current.type is not TOKEN_EOF:386+ try:387+ self.current = next(self._iter)388+ except StopIteration:389+ self.close()390+ return rv391+392+ def close(self):393+ """Close the stream."""394+ self.current = Token(self.current.lineno, TOKEN_EOF, "")395+ self._iter = None396+ self.closed = True397+398+ def expect(self, expr):399+ """Expect a given token type and return it. This accepts the same400+ argument as :meth:`jinja2.lexer.Token.test`.401+ """402+ if not self.current.test(expr):403+ expr = describe_token_expr(expr)404+ if self.current.type is TOKEN_EOF:405+ raise TemplateSyntaxError(406+ "unexpected end of template, expected %r." % expr,407+ self.current.lineno,408+ self.name,409+ self.filename,410+ )411+ raise TemplateSyntaxError(412+ "expected token %r, got %r" % (expr, describe_token(self.current)),413+ self.current.lineno,414+ self.name,415+ self.filename,416+ )417+ try:418+ return self.current419+ finally:420+ next(self)421+422+423+def get_lexer(environment):424+ """Return a lexer which is probably cached."""425+ key = (426+ environment.block_start_string,427+ environment.block_end_string,428+ environment.variable_start_string,429+ environment.variable_end_string,430+ environment.comment_start_string,431+ environment.comment_end_string,432+ environment.line_statement_prefix,433+ environment.line_comment_prefix,434+ environment.trim_blocks,435+ environment.lstrip_blocks,436+ environment.newline_sequence,437+ environment.keep_trailing_newline,438+ )439+ lexer = _lexer_cache.get(key)440+ if lexer is None:441+ lexer = Lexer(environment)442+ _lexer_cache[key] = lexer443+ return lexer444+445+446+class OptionalLStrip(tuple):447+ """A special tuple for marking a point in the state that can have448+ lstrip applied.449+ """450+451+ __slots__ = ()452+453+ # Even though it looks like a no-op, creating instances fails454+ # without this.455+ def __new__(cls, *members, **kwargs):456+ return super(OptionalLStrip, cls).__new__(cls, members)457+458+459+class Lexer(object):460+ """Class that implements a lexer for a given environment. Automatically461+ created by the environment class, usually you don't have to do that.462+463+ Note that the lexer is not automatically bound to an environment.464+ Multiple environments can share the same lexer.465+ """466+467+ def __init__(self, environment):468+ # shortcuts469+ e = re.escape470+471+ def c(x):472+ return re.compile(x, re.M | re.S)473+474+ # lexing rules for tags475+ tag_rules = [476+ (whitespace_re, TOKEN_WHITESPACE, None),477+ (float_re, TOKEN_FLOAT, None),478+ (integer_re, TOKEN_INTEGER, None),479+ (name_re, TOKEN_NAME, None),480+ (string_re, TOKEN_STRING, None),481+ (operator_re, TOKEN_OPERATOR, None),482+ ]483+484+ # assemble the root lexing rule. because "|" is ungreedy485+ # we have to sort by length so that the lexer continues working486+ # as expected when we have parsing rules like <% for block and487+ # <%= for variables. (if someone wants asp like syntax)488+ # variables are just part of the rules if variable processing489+ # is required.490+ root_tag_rules = compile_rules(environment)491+492+ # block suffix if trimming is enabled493+ block_suffix_re = environment.trim_blocks and "\\n?" or ""494+495+ # If lstrip is enabled, it should not be applied if there is any496+ # non-whitespace between the newline and block.497+ self.lstrip_unless_re = c(r"[^ \t]") if environment.lstrip_blocks else None498+499+ self.newline_sequence = environment.newline_sequence500+ self.keep_trailing_newline = environment.keep_trailing_newline501+502+ # global lexing rules503+ self.rules = {504+ "root": [505+ # directives506+ (507+ c(508+ "(.*?)(?:%s)"509+ % "|".join(510+ [511+ r"(?P<raw_begin>%s(\-|\+|)\s*raw\s*(?:\-%s\s*|%s))"512+ % (513+ e(environment.block_start_string),514+ e(environment.block_end_string),515+ e(environment.block_end_string),516+ )517+ ]518+ + [519+ r"(?P<%s>%s(\-|\+|))" % (n, r)520+ for n, r in root_tag_rules521+ ]522+ )523+ ),524+ OptionalLStrip(TOKEN_DATA, "#bygroup"),525+ "#bygroup",526+ ),527+ # data528+ (c(".+"), TOKEN_DATA, None),529+ ],530+ # comments531+ TOKEN_COMMENT_BEGIN: [532+ (533+ c(534+ r"(.*?)((?:\-%s\s*|%s)%s)"535+ % (536+ e(environment.comment_end_string),537+ e(environment.comment_end_string),538+ block_suffix_re,539+ )540+ ),541+ (TOKEN_COMMENT, TOKEN_COMMENT_END),542+ "#pop",543+ ),544+ (c("(.)"), (Failure("Missing end of comment tag"),), None),545+ ],546+ # blocks547+ TOKEN_BLOCK_BEGIN: [548+ (549+ c(550+ r"(?:\-%s\s*|%s)%s"551+ % (552+ e(environment.block_end_string),553+ e(environment.block_end_string),554+ block_suffix_re,555+ )556+ ),557+ TOKEN_BLOCK_END,558+ "#pop",559+ ),560+ ]561+ + tag_rules,562+ # variables563+ TOKEN_VARIABLE_BEGIN: [564+ (565+ c(566+ r"\-%s\s*|%s"567+ % (568+ e(environment.variable_end_string),569+ e(environment.variable_end_string),570+ )571+ ),572+ TOKEN_VARIABLE_END,573+ "#pop",574+ )575+ ]576+ + tag_rules,577+ # raw block578+ TOKEN_RAW_BEGIN: [579+ (580+ c(581+ r"(.*?)((?:%s(\-|\+|))\s*endraw\s*(?:\-%s\s*|%s%s))"582+ % (583+ e(environment.block_start_string),584+ e(environment.block_end_string),585+ e(environment.block_end_string),586+ block_suffix_re,587+ )588+ ),589+ OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END),590+ "#pop",591+ ),592+ (c("(.)"), (Failure("Missing end of raw directive"),), None),593+ ],594+ # line statements595+ TOKEN_LINESTATEMENT_BEGIN: [596+ (c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")597+ ]598+ + tag_rules,599+ # line comments600+ TOKEN_LINECOMMENT_BEGIN: [601+ (602+ c(r"(.*?)()(?=\n|$)"),603+ (TOKEN_LINECOMMENT, TOKEN_LINECOMMENT_END),604+ "#pop",605+ )606+ ],607+ }608+609+ def _normalize_newlines(self, value):610+ """Called for strings and template data to normalize it to unicode."""611+ return newline_re.sub(self.newline_sequence, value)612+613+ def tokenize(self, source, name=None, filename=None, state=None):614+ """Calls tokeniter + tokenize and wraps it in a token stream."""615+ stream = self.tokeniter(source, name, filename, state)616+ return TokenStream(self.wrap(stream, name, filename), name, filename)617+618+ def wrap(self, stream, name=None, filename=None):619+ """This is called with the stream as returned by `tokenize` and wraps620+ every token in a :class:`Token` and converts the value.621+ """622+ for lineno, token, value in stream:623+ if token in ignored_tokens:624+ continue625+ elif token == TOKEN_LINESTATEMENT_BEGIN:626+ token = TOKEN_BLOCK_BEGIN627+ elif token == TOKEN_LINESTATEMENT_END:628+ token = TOKEN_BLOCK_END629+ # we are not interested in those tokens in the parser630+ elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END):631+ continue632+ elif token == TOKEN_DATA:633+ value = self._normalize_newlines(value)634+ elif token == "keyword":635+ token = value636+ elif token == TOKEN_NAME:637+ value = str(value)638+ if check_ident and not value.isidentifier():639+ raise TemplateSyntaxError(640+ "Invalid character in identifier", lineno, name, filename641+ )642+ elif token == TOKEN_STRING:643+ # try to unescape string644+ try:645+ value = (646+ self._normalize_newlines(value[1:-1])647+ .encode("ascii", "backslashreplace")648+ .decode("unicode-escape")649+ )650+ except Exception as e:651+ msg = str(e).split(":")[-1].strip()652+ raise TemplateSyntaxError(msg, lineno, name, filename)653+ elif token == TOKEN_INTEGER:654+ value = int(value.replace("_", ""))655+ elif token == TOKEN_FLOAT:656+ # remove all "_" first to support more Python versions657+ value = literal_eval(value.replace("_", ""))658+ elif token == TOKEN_OPERATOR:659+ token = operators[value]660+ yield Token(lineno, token, value)661+662+ def tokeniter(self, source, name, filename=None, state=None):663+ """This method tokenizes the text and returns the tokens in a664+ generator. Use this method if you just want to tokenize a template.665+ """666+ source = text_type(source)667+ lines = source.splitlines()668+ if self.keep_trailing_newline and source:669+ for newline in ("\r\n", "\r", "\n"):670+ if source.endswith(newline):671+ lines.append("")672+ break673+ source = "\n".join(lines)674+ pos = 0675+ lineno = 1676+ stack = ["root"]677+ if state is not None and state != "root":678+ assert state in ("variable", "block"), "invalid state"679+ stack.append(state + "_begin")680+ statetokens = self.rules[stack[-1]]681+ source_length = len(source)682+ balancing_stack = []683+ lstrip_unless_re = self.lstrip_unless_re684+685+ while 1:686+ # tokenizer loop687+ for regex, tokens, new_state in statetokens:688+ m = regex.match(source, pos)689+ # if no match we try again with the next rule690+ if m is None:691+ continue692+693+ # we only match blocks and variables if braces / parentheses694+ # are balanced. continue parsing with the lower rule which695+ # is the operator rule. do this only if the end tags look696+ # like operators697+ if balancing_stack and tokens in (698+ TOKEN_VARIABLE_END,699+ TOKEN_BLOCK_END,700+ TOKEN_LINESTATEMENT_END,701+ ):702+ continue703+704+ # tuples support more options705+ if isinstance(tokens, tuple):706+ groups = m.groups()707+708+ if isinstance(tokens, OptionalLStrip):709+ # Rule supports lstrip. Match will look like710+ # text, block type, whitespace control, type, control, ...711+ text = groups[0]712+713+ # Skipping the text and first type, every other group is the714+ # whitespace control for each type. One of the groups will be715+ # -, +, or empty string instead of None.716+ strip_sign = next(g for g in groups[2::2] if g is not None)717+718+ if strip_sign == "-":719+ # Strip all whitespace between the text and the tag.720+ groups = (text.rstrip(),) + groups[1:]721+ elif (722+ # Not marked for preserving whitespace.723+ strip_sign != "+"724+ # lstrip is enabled.725+ and lstrip_unless_re is not None726+ # Not a variable expression.727+ and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)728+ ):729+ # The start of text between the last newline and the tag.730+ l_pos = text.rfind("\n") + 1731+732+ # If there's only whitespace between the newline and the733+ # tag, strip it.734+ if not lstrip_unless_re.search(text, l_pos):735+ groups = (text[:l_pos],) + groups[1:]736+737+ for idx, token in enumerate(tokens):738+ # failure group739+ if token.__class__ is Failure:740+ raise token(lineno, filename)741+ # bygroup is a bit more complex, in that case we742+ # yield for the current token the first named743+ # group that matched744+ elif token == "#bygroup":745+ for key, value in iteritems(m.groupdict()):746+ if value is not None:747+ yield lineno, key, value748+ lineno += value.count("\n")749+ break750+ else:751+ raise RuntimeError(752+ "%r wanted to resolve "753+ "the token dynamically"754+ " but no group matched" % regex755+ )756+ # normal group757+ else:758+ data = groups[idx]759+ if data or token not in ignore_if_empty:760+ yield lineno, token, data761+ lineno += data.count("\n")762+763+ # strings as token just are yielded as it.764+ else:765+ data = m.group()766+ # update brace/parentheses balance767+ if tokens == TOKEN_OPERATOR:768+ if data == "{":769+ balancing_stack.append("}")770+ elif data == "(":771+ balancing_stack.append(")")772+ elif data == "[":773+ balancing_stack.append("]")774+ elif data in ("}", ")", "]"):775+ if not balancing_stack:776+ raise TemplateSyntaxError(777+ "unexpected '%s'" % data, lineno, name, filename778+ )779+ expected_op = balancing_stack.pop()780+ if expected_op != data:781+ raise TemplateSyntaxError(782+ "unexpected '%s', "783+ "expected '%s'" % (data, expected_op),784+ lineno,785+ name,786+ filename,787+ )788+ # yield items789+ if data or tokens not in ignore_if_empty:790+ yield lineno, tokens, data791+ lineno += data.count("\n")792+793+ # fetch new position into new variable so that we can check794+ # if there is a internal parsing error which would result795+ # in an infinite loop796+ pos2 = m.end()797+798+ # handle state changes799+ if new_state is not None:800+ # remove the uppermost state801+ if new_state == "#pop":802+ stack.pop()803+ # resolve the new state by group checking804+ elif new_state == "#bygroup":805+ for key, value in iteritems(m.groupdict()):806+ if value is not None:807+ stack.append(key)808+ break809+ else:810+ raise RuntimeError(811+ "%r wanted to resolve the "812+ "new state dynamically but"813+ " no group matched" % regex814+ )815+ # direct state name given816+ else:817+ stack.append(new_state)818+ statetokens = self.rules[stack[-1]]819+ # we are still at the same position and no stack change.820+ # this means a loop without break condition, avoid that and821+ # raise error822+ elif pos2 == pos:823+ raise RuntimeError(824+ "%r yielded empty string without stack change" % regex825+ )826+ # publish new function and start again827+ pos = pos2828+ break829+ # if loop terminated without break we haven't found a single match830+ # either we are at the end of the file or we have a problem831+ else:832+ # end of text833+ if pos >= source_length:834+ return835+ # something went wrong836+ raise TemplateSyntaxError(837+ "unexpected char %r at %d" % (source[pos], pos),838+ lineno,839+ name,840+ filename,841+ )added:src/jinja/loaders.py+572 added
1+# -*- coding: utf-8 -*-2+"""API and implementations for loading templates from different data3+sources.4+"""5+import os6+import pkgutil7+import sys8+import weakref9+from hashlib import sha110+from importlib import import_module11+from os import path12+from types import ModuleType13+14+from ._compat import abc15+from ._compat import fspath16+from ._compat import iteritems17+from ._compat import string_types18+from .exceptions import TemplateNotFound19+from .utils import internalcode20+from .utils import open_if_exists21+22+23+def split_template_path(template):24+ """Split a path into segments and perform a sanity check. If it detects25+ '..' in the path it will raise a `TemplateNotFound` error.26+ """27+ pieces = []28+ for piece in template.split("/"):29+ if (30+ path.sep in piece31+ or (path.altsep and path.altsep in piece)32+ or piece == path.pardir33+ ):34+ raise TemplateNotFound(template)35+ elif piece and piece != ".":36+ pieces.append(piece)37+ return pieces38+39+40+class BaseLoader(object):41+ """Baseclass for all loaders. Subclass this and override `get_source` to42+ implement a custom loading mechanism. The environment provides a43+ `get_template` method that calls the loader's `load` method to get the44+ :class:`Template` object.45+46+ A very basic example for a loader that looks up templates on the file47+ system could look like this::48+49+ from jinja2 import BaseLoader, TemplateNotFound50+ from os.path import join, exists, getmtime51+52+ class MyLoader(BaseLoader):53+54+ def __init__(self, path):55+ self.path = path56+57+ def get_source(self, environment, template):58+ path = join(self.path, template)59+ if not exists(path):60+ raise TemplateNotFound(template)61+ mtime = getmtime(path)62+ with file(path) as f:63+ source = f.read().decode('utf-8')64+ return source, path, lambda: mtime == getmtime(path)65+ """66+67+ #: if set to `False` it indicates that the loader cannot provide access68+ #: to the source of templates.69+ #:70+ #: .. versionadded:: 2.471+ has_source_access = True72+73+ def get_source(self, environment, template):74+ """Get the template source, filename and reload helper for a template.75+ It's passed the environment and template name and has to return a76+ tuple in the form ``(source, filename, uptodate)`` or raise a77+ `TemplateNotFound` error if it can't locate the template.78+79+ The source part of the returned tuple must be the source of the80+ template as unicode string or a ASCII bytestring. The filename should81+ be the name of the file on the filesystem if it was loaded from there,82+ otherwise `None`. The filename is used by python for the tracebacks83+ if no loader extension is used.84+85+ The last item in the tuple is the `uptodate` function. If auto86+ reloading is enabled it's always called to check if the template87+ changed. No arguments are passed so the function must store the88+ old state somewhere (for example in a closure). If it returns `False`89+ the template will be reloaded.90+ """91+ if not self.has_source_access:92+ raise RuntimeError(93+ "%s cannot provide access to the source" % self.__class__.__name__94+ )95+ raise TemplateNotFound(template)96+97+ def list_templates(self):98+ """Iterates over all templates. If the loader does not support that99+ it should raise a :exc:`TypeError` which is the default behavior.100+ """101+ raise TypeError("this loader cannot iterate over all templates")102+103+ @internalcode104+ def load(self, environment, name, globals=None):105+ """Loads a template. This method looks up the template in the cache106+ or loads one by calling :meth:`get_source`. Subclasses should not107+ override this method as loaders working on collections of other108+ loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)109+ will not call this method but `get_source` directly.110+ """111+ code = None112+ if globals is None:113+ globals = {}114+115+ # first we try to get the source for this template together116+ # with the filename and the uptodate function.117+ source, filename, uptodate = self.get_source(environment, name)118+119+ # try to load the code from the bytecode cache if there is a120+ # bytecode cache configured.121+ bcc = environment.bytecode_cache122+ if bcc is not None:123+ bucket = bcc.get_bucket(environment, name, filename, source)124+ code = bucket.code125+126+ # if we don't have code so far (not cached, no longer up to127+ # date) etc. we compile the template128+ if code is None:129+ code = environment.compile(source, name, filename)130+131+ # if the bytecode cache is available and the bucket doesn't132+ # have a code so far, we give the bucket the new code and put133+ # it back to the bytecode cache.134+ if bcc is not None and bucket.code is None:135+ bucket.code = code136+ bcc.set_bucket(bucket)137+138+ return environment.template_class.from_code(139+ environment, code, globals, uptodate140+ )141+142+143+class FileSystemLoader(BaseLoader):144+ """Loads templates from the file system. This loader can find templates145+ in folders on the file system and is the preferred way to load them.146+147+ The loader takes the path to the templates as string, or if multiple148+ locations are wanted a list of them which is then looked up in the149+ given order::150+151+ >>> loader = FileSystemLoader('/path/to/templates')152+ >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])153+154+ Per default the template encoding is ``'utf-8'`` which can be changed155+ by setting the `encoding` parameter to something else.156+157+ To follow symbolic links, set the *followlinks* parameter to ``True``::158+159+ >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)160+161+ .. versionchanged:: 2.8162+ The ``followlinks`` parameter was added.163+ """164+165+ def __init__(self, searchpath, encoding="utf-8", followlinks=False):166+ if not isinstance(searchpath, abc.Iterable) or isinstance(167+ searchpath, string_types168+ ):169+ searchpath = [searchpath]170+171+ # In Python 3.5, os.path.join doesn't support Path. This can be172+ # simplified to list(searchpath) when Python 3.5 is dropped.173+ self.searchpath = [fspath(p) for p in searchpath]174+175+ self.encoding = encoding176+ self.followlinks = followlinks177+178+ def get_source(self, environment, template):179+ pieces = split_template_path(template)180+ for searchpath in self.searchpath:181+ filename = path.join(searchpath, *pieces)182+ f = open_if_exists(filename)183+ if f is None:184+ continue185+ try:186+ contents = f.read().decode(self.encoding)187+ finally:188+ f.close()189+190+ mtime = path.getmtime(filename)191+192+ def uptodate():193+ try:194+ return path.getmtime(filename) == mtime195+ except OSError:196+ return False197+198+ return contents, filename, uptodate199+ raise TemplateNotFound(template)200+201+ def list_templates(self):202+ found = set()203+ for searchpath in self.searchpath:204+ walk_dir = os.walk(searchpath, followlinks=self.followlinks)205+ for dirpath, _, filenames in walk_dir:206+ for filename in filenames:207+ template = (208+ os.path.join(dirpath, filename)[len(searchpath) :]209+ .strip(os.path.sep)210+ .replace(os.path.sep, "/")211+ )212+ if template[:2] == "./":213+ template = template[2:]214+ if template not in found:215+ found.add(template)216+ return sorted(found)217+218+219+class PackageLoader(BaseLoader):220+ """Load templates from a directory in a Python package.221+222+ :param package_name: Import name of the package that contains the223+ template directory.224+ :param package_path: Directory within the imported package that225+ contains the templates.226+ :param encoding: Encoding of template files.227+228+ The following example looks up templates in the ``pages`` directory229+ within the ``project.ui`` package.230+231+ .. code-block:: python232+233+ loader = PackageLoader("project.ui", "pages")234+235+ Only packages installed as directories (standard pip behavior) or236+ zip/egg files (less common) are supported. The Python API for237+ introspecting data in packages is too limited to support other238+ installation methods the way this loader requires.239+240+ There is limited support for :pep:`420` namespace packages. The241+ template directory is assumed to only be in one namespace242+ contributor. Zip files contributing to a namespace are not243+ supported.244+245+ .. versionchanged:: 2.11.0246+ No longer uses ``setuptools`` as a dependency.247+248+ .. versionchanged:: 2.11.0249+ Limited PEP 420 namespace package support.250+ """251+252+ def __init__(self, package_name, package_path="templates", encoding="utf-8"):253+ if package_path == os.path.curdir:254+ package_path = ""255+ elif package_path[:2] == os.path.curdir + os.path.sep:256+ package_path = package_path[2:]257+258+ package_path = os.path.normpath(package_path).rstrip(os.path.sep)259+ self.package_path = package_path260+ self.package_name = package_name261+ self.encoding = encoding262+263+ # Make sure the package exists. This also makes namespace264+ # packages work, otherwise get_loader returns None.265+ import_module(package_name)266+ self._loader = loader = pkgutil.get_loader(package_name)267+268+ # Zip loader's archive attribute points at the zip.269+ self._archive = getattr(loader, "archive", None)270+ self._template_root = None271+272+ if hasattr(loader, "get_filename"):273+ # A standard directory package, or a zip package.274+ self._template_root = os.path.join(275+ os.path.dirname(loader.get_filename(package_name)), package_path276+ )277+ elif hasattr(loader, "_path"):278+ # A namespace package, limited support. Find the first279+ # contributor with the template directory.280+ for root in loader._path:281+ root = os.path.join(root, package_path)282+283+ if os.path.isdir(root):284+ self._template_root = root285+ break286+287+ if self._template_root is None:288+ raise ValueError(289+ "The %r package was not installed in a way that"290+ " PackageLoader understands." % package_name291+ )292+293+ def get_source(self, environment, template):294+ p = os.path.join(self._template_root, *split_template_path(template))295+296+ if self._archive is None:297+ # Package is a directory.298+ if not os.path.isfile(p):299+ raise TemplateNotFound(template)300+301+ with open(p, "rb") as f:302+ source = f.read()303+304+ mtime = os.path.getmtime(p)305+306+ def up_to_date():307+ return os.path.isfile(p) and os.path.getmtime(p) == mtime308+309+ else:310+ # Package is a zip file.311+ try:312+ source = self._loader.get_data(p)313+ except OSError:314+ raise TemplateNotFound(template)315+316+ # Could use the zip's mtime for all template mtimes, but317+ # would need to safely reload the module if it's out of318+ # date, so just report it as always current.319+ up_to_date = None320+321+ return source.decode(self.encoding), p, up_to_date322+323+ def list_templates(self):324+ results = []325+326+ if self._archive is None:327+ # Package is a directory.328+ offset = len(self._template_root)329+330+ for dirpath, _, filenames in os.walk(self._template_root):331+ dirpath = dirpath[offset:].lstrip(os.path.sep)332+ results.extend(333+ os.path.join(dirpath, name).replace(os.path.sep, "/")334+ for name in filenames335+ )336+ else:337+ if not hasattr(self._loader, "_files"):338+ raise TypeError(339+ "This zip import does not have the required"340+ " metadata to list templates."341+ )342+343+ # Package is a zip file.344+ prefix = (345+ self._template_root[len(self._archive) :].lstrip(os.path.sep)346+ + os.path.sep347+ )348+ offset = len(prefix)349+350+ for name in self._loader._files.keys():351+ # Find names under the templates directory that aren't directories.352+ if name.startswith(prefix) and name[-1] != os.path.sep:353+ results.append(name[offset:].replace(os.path.sep, "/"))354+355+ results.sort()356+ return results357+358+359+class DictLoader(BaseLoader):360+ """Loads a template from a python dict. It's passed a dict of unicode361+ strings bound to template names. This loader is useful for unittesting:362+363+ >>> loader = DictLoader({'index.html': 'source here'})364+365+ Because auto reloading is rarely useful this is disabled per default.366+ """367+368+ def __init__(self, mapping):369+ self.mapping = mapping370+371+ def get_source(self, environment, template):372+ if template in self.mapping:373+ source = self.mapping[template]374+ return source, None, lambda: source == self.mapping.get(template)375+ raise TemplateNotFound(template)376+377+ def list_templates(self):378+ return sorted(self.mapping)379+380+381+class FunctionLoader(BaseLoader):382+ """A loader that is passed a function which does the loading. The383+ function receives the name of the template and has to return either384+ an unicode string with the template source, a tuple in the form ``(source,385+ filename, uptodatefunc)`` or `None` if the template does not exist.386+387+ >>> def load_template(name):388+ ... if name == 'index.html':389+ ... return '...'390+ ...391+ >>> loader = FunctionLoader(load_template)392+393+ The `uptodatefunc` is a function that is called if autoreload is enabled394+ and has to return `True` if the template is still up to date. For more395+ details have a look at :meth:`BaseLoader.get_source` which has the same396+ return value.397+ """398+399+ def __init__(self, load_func):400+ self.load_func = load_func401+402+ def get_source(self, environment, template):403+ rv = self.load_func(template)404+ if rv is None:405+ raise TemplateNotFound(template)406+ elif isinstance(rv, string_types):407+ return rv, None, None408+ return rv409+410+411+class PrefixLoader(BaseLoader):412+ """A loader that is passed a dict of loaders where each loader is bound413+ to a prefix. The prefix is delimited from the template by a slash per414+ default, which can be changed by setting the `delimiter` argument to415+ something else::416+417+ loader = PrefixLoader({418+ 'app1': PackageLoader('mypackage.app1'),419+ 'app2': PackageLoader('mypackage.app2')420+ })421+422+ By loading ``'app1/index.html'`` the file from the app1 package is loaded,423+ by loading ``'app2/index.html'`` the file from the second.424+ """425+426+ def __init__(self, mapping, delimiter="/"):427+ self.mapping = mapping428+ self.delimiter = delimiter429+430+ def get_loader(self, template):431+ try:432+ prefix, name = template.split(self.delimiter, 1)433+ loader = self.mapping[prefix]434+ except (ValueError, KeyError):435+ raise TemplateNotFound(template)436+ return loader, name437+438+ def get_source(self, environment, template):439+ loader, name = self.get_loader(template)440+ try:441+ return loader.get_source(environment, name)442+ except TemplateNotFound:443+ # re-raise the exception with the correct filename here.444+ # (the one that includes the prefix)445+ raise TemplateNotFound(template)446+447+ @internalcode448+ def load(self, environment, name, globals=None):449+ loader, local_name = self.get_loader(name)450+ try:451+ return loader.load(environment, local_name, globals)452+ except TemplateNotFound:453+ # re-raise the exception with the correct filename here.454+ # (the one that includes the prefix)455+ raise TemplateNotFound(name)456+457+ def list_templates(self):458+ result = []459+ for prefix, loader in iteritems(self.mapping):460+ for template in loader.list_templates():461+ result.append(prefix + self.delimiter + template)462+ return result463+464+465+class ChoiceLoader(BaseLoader):466+ """This loader works like the `PrefixLoader` just that no prefix is467+ specified. If a template could not be found by one loader the next one468+ is tried.469+470+ >>> loader = ChoiceLoader([471+ ... FileSystemLoader('/path/to/user/templates'),472+ ... FileSystemLoader('/path/to/system/templates')473+ ... ])474+475+ This is useful if you want to allow users to override builtin templates476+ from a different location.477+ """478+479+ def __init__(self, loaders):480+ self.loaders = loaders481+482+ def get_source(self, environment, template):483+ for loader in self.loaders:484+ try:485+ return loader.get_source(environment, template)486+ except TemplateNotFound:487+ pass488+ raise TemplateNotFound(template)489+490+ @internalcode491+ def load(self, environment, name, globals=None):492+ for loader in self.loaders:493+ try:494+ return loader.load(environment, name, globals)495+ except TemplateNotFound:496+ pass497+ raise TemplateNotFound(name)498+499+ def list_templates(self):500+ found = set()501+ for loader in self.loaders:502+ found.update(loader.list_templates())503+ return sorted(found)504+505+506+class _TemplateModule(ModuleType):507+ """Like a normal module but with support for weak references"""508+509+510+class ModuleLoader(BaseLoader):511+ """This loader loads templates from precompiled templates.512+513+ Example usage:514+515+ >>> loader = ChoiceLoader([516+ ... ModuleLoader('/path/to/compiled/templates'),517+ ... FileSystemLoader('/path/to/templates')518+ ... ])519+520+ Templates can be precompiled with :meth:`Environment.compile_templates`.521+ """522+523+ has_source_access = False524+525+ def __init__(self, path):526+ package_name = "_jinja2_module_templates_%x" % id(self)527+528+ # create a fake module that looks for the templates in the529+ # path given.530+ mod = _TemplateModule(package_name)531+532+ if not isinstance(path, abc.Iterable) or isinstance(path, string_types):533+ path = [path]534+535+ mod.__path__ = [fspath(p) for p in path]536+537+ sys.modules[package_name] = weakref.proxy(538+ mod, lambda x: sys.modules.pop(package_name, None)539+ )540+541+ # the only strong reference, the sys.modules entry is weak542+ # so that the garbage collector can remove it once the543+ # loader that created it goes out of business.544+ self.module = mod545+ self.package_name = package_name546+547+ @staticmethod548+ def get_template_key(name):549+ return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()550+551+ @staticmethod552+ def get_module_filename(name):553+ return ModuleLoader.get_template_key(name) + ".py"554+555+ @internalcode556+ def load(self, environment, name, globals=None):557+ key = self.get_template_key(name)558+ module = "%s.%s" % (self.package_name, key)559+ mod = getattr(self.module, module, None)560+ if mod is None:561+ try:562+ mod = __import__(module, None, None, ["root"])563+ except ImportError:564+ raise TemplateNotFound(name)565+566+ # remove the entry from sys.modules, we only want the attribute567+ # on the module object we have stored on the loader.568+ sys.modules.pop(module, None)569+570+ return environment.template_class.from_module_dict(571+ environment, mod.__dict__, globals572+ )added:src/jinja/meta.py+101 added
1+# -*- coding: utf-8 -*-2+"""Functions that expose information about templates that might be3+interesting for introspection.4+"""5+from . import nodes6+from ._compat import iteritems7+from ._compat import string_types8+from .compiler import CodeGenerator9+10+11+class TrackingCodeGenerator(CodeGenerator):12+ """We abuse the code generator for introspection."""13+14+ def __init__(self, environment):15+ CodeGenerator.__init__(self, environment, "<introspection>", "<introspection>")16+ self.undeclared_identifiers = set()17+18+ def write(self, x):19+ """Don't write."""20+21+ def enter_frame(self, frame):22+ """Remember all undeclared identifiers."""23+ CodeGenerator.enter_frame(self, frame)24+ for _, (action, param) in iteritems(frame.symbols.loads):25+ if action == "resolve" and param not in self.environment.globals:26+ self.undeclared_identifiers.add(param)27+28+29+def find_undeclared_variables(ast):30+ """Returns a set of all variables in the AST that will be looked up from31+ the context at runtime. Because at compile time it's not known which32+ variables will be used depending on the path the execution takes at33+ runtime, all variables are returned.34+35+ >>> from jinja2 import Environment, meta36+ >>> env = Environment()37+ >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')38+ >>> meta.find_undeclared_variables(ast) == set(['bar'])39+ True40+41+ .. admonition:: Implementation42+43+ Internally the code generator is used for finding undeclared variables.44+ This is good to know because the code generator might raise a45+ :exc:`TemplateAssertionError` during compilation and as a matter of46+ fact this function can currently raise that exception as well.47+ """48+ codegen = TrackingCodeGenerator(ast.environment)49+ codegen.visit(ast)50+ return codegen.undeclared_identifiers51+52+53+def find_referenced_templates(ast):54+ """Finds all the referenced templates from the AST. This will return an55+ iterator over all the hardcoded template extensions, inclusions and56+ imports. If dynamic inheritance or inclusion is used, `None` will be57+ yielded.58+59+ >>> from jinja2 import Environment, meta60+ >>> env = Environment()61+ >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')62+ >>> list(meta.find_referenced_templates(ast))63+ ['layout.html', None]64+65+ This function is useful for dependency tracking. For example if you want66+ to rebuild parts of the website after a layout template has changed.67+ """68+ for node in ast.find_all(69+ (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)70+ ):71+ if not isinstance(node.template, nodes.Const):72+ # a tuple with some non consts in there73+ if isinstance(node.template, (nodes.Tuple, nodes.List)):74+ for template_name in node.template.items:75+ # something const, only yield the strings and ignore76+ # non-string consts that really just make no sense77+ if isinstance(template_name, nodes.Const):78+ if isinstance(template_name.value, string_types):79+ yield template_name.value80+ # something dynamic in there81+ else:82+ yield None83+ # something dynamic we don't know about here84+ else:85+ yield None86+ continue87+ # constant is a basestring, direct template name88+ if isinstance(node.template.value, string_types):89+ yield node.template.value90+ # a tuple or list (latter *should* not happen) made of consts,91+ # yield the consts that are strings. We could warn here for92+ # non string values93+ elif isinstance(node, nodes.Include) and isinstance(94+ node.template.value, (tuple, list)95+ ):96+ for template_name in node.template.value:97+ if isinstance(template_name, string_types):98+ yield template_name99+ # something else we don't care about, we could warn here100+ else:101+ yield Noneadded:src/jinja/nativetypes.py+111 added
1+import types2+from ast import literal_eval3+from itertools import chain4+from itertools import islice5+6+from . import nodes7+from ._compat import text_type8+from .compiler import CodeGenerator9+from .compiler import has_safe_repr10+from .environment import Environment11+from .environment import Template12+13+14+def native_concat(nodes, preserve_quotes=True):15+ """Return a native Python type from the list of compiled nodes. If16+ the result is a single node, its value is returned. Otherwise, the17+ nodes are concatenated as strings. If the result can be parsed with18+ :func:`ast.literal_eval`, the parsed value is returned. Otherwise,19+ the string is returned.20+21+ :param nodes: Iterable of nodes to concatenate.22+ :param preserve_quotes: Whether to re-wrap literal strings with23+ quotes, to preserve quotes around expressions for later parsing.24+ Should be ``False`` in :meth:`NativeEnvironment.render`.25+ """26+ head = list(islice(nodes, 2))27+28+ if not head:29+ return None30+31+ if len(head) == 1:32+ raw = head[0]33+ else:34+ if isinstance(nodes, types.GeneratorType):35+ nodes = chain(head, nodes)36+ raw = u"".join([text_type(v) for v in nodes])37+38+ try:39+ literal = literal_eval(raw)40+ except (ValueError, SyntaxError, MemoryError):41+ return raw42+43+ # If literal_eval returned a string, re-wrap with the original44+ # quote character to avoid dropping quotes between expression nodes.45+ # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should46+ # be ('a', 'b').47+ if preserve_quotes and isinstance(literal, str):48+ return "{quote}{}{quote}".format(literal, quote=raw[0])49+50+ return literal51+52+53+class NativeCodeGenerator(CodeGenerator):54+ """A code generator which renders Python types by not adding55+ ``to_string()`` around output nodes, and using :func:`native_concat`56+ to convert complex strings back to Python types if possible.57+ """58+59+ @staticmethod60+ def _default_finalize(value):61+ return value62+63+ def _output_const_repr(self, group):64+ return repr(native_concat(group))65+66+ def _output_child_to_const(self, node, frame, finalize):67+ const = node.as_const(frame.eval_ctx)68+69+ if not has_safe_repr(const):70+ raise nodes.Impossible()71+72+ if isinstance(node, nodes.TemplateData):73+ return const74+75+ return finalize.const(const)76+77+ def _output_child_pre(self, node, frame, finalize):78+ if finalize.src is not None:79+ self.write(finalize.src)80+81+ def _output_child_post(self, node, frame, finalize):82+ if finalize.src is not None:83+ self.write(")")84+85+86+class NativeEnvironment(Environment):87+ """An environment that renders templates to native Python types."""88+89+ code_generator_class = NativeCodeGenerator90+91+92+class NativeTemplate(Template):93+ environment_class = NativeEnvironment94+95+ def render(self, *args, **kwargs):96+ """Render the template to produce a native Python type. If the97+ result is a single node, its value is returned. Otherwise, the98+ nodes are concatenated as strings. If the result can be parsed99+ with :func:`ast.literal_eval`, the parsed value is returned.100+ Otherwise, the string is returned.101+ """102+ vars = dict(*args, **kwargs)103+ try:104+ return native_concat(105+ self.root_render_func(self.new_context(vars)), preserve_quotes=False106+ )107+ except Exception:108+ return self.environment.handle_exception()109+110+111+NativeEnvironment.template_class = NativeTemplateadded:src/jinja/nodes.py+1087 added
1+# -*- coding: utf-8 -*-2+"""AST nodes generated by the parser for the compiler. Also provides3+some node tree helper functions used by the parser and compiler in order4+to normalize nodes.5+"""6+import operator7+from collections import deque8+9+from ._compat import izip10+from ._compat import PY211+from ._compat import text_type12+from ._compat import with_metaclass13+from .utils import Markup14+15+_binop_to_func = {16+ "*": operator.mul,17+ "/": operator.truediv,18+ "//": operator.floordiv,19+ "**": operator.pow,20+ "%": operator.mod,21+ "+": operator.add,22+ "-": operator.sub,23+}24+25+_uaop_to_func = {"not": operator.not_, "+": operator.pos, "-": operator.neg}26+27+_cmpop_to_func = {28+ "eq": operator.eq,29+ "ne": operator.ne,30+ "gt": operator.gt,31+ "gteq": operator.ge,32+ "lt": operator.lt,33+ "lteq": operator.le,34+ "in": lambda a, b: a in b,35+ "notin": lambda a, b: a not in b,36+}37+38+39+class Impossible(Exception):40+ """Raised if the node could not perform a requested action."""41+42+43+class NodeType(type):44+ """A metaclass for nodes that handles the field and attribute45+ inheritance. fields and attributes from the parent class are46+ automatically forwarded to the child."""47+48+ def __new__(mcs, name, bases, d):49+ for attr in "fields", "attributes":50+ storage = []51+ storage.extend(getattr(bases[0], attr, ()))52+ storage.extend(d.get(attr, ()))53+ assert len(bases) == 1, "multiple inheritance not allowed"54+ assert len(storage) == len(set(storage)), "layout conflict"55+ d[attr] = tuple(storage)56+ d.setdefault("abstract", False)57+ return type.__new__(mcs, name, bases, d)58+59+60+class EvalContext(object):61+ """Holds evaluation time information. Custom attributes can be attached62+ to it in extensions.63+ """64+65+ def __init__(self, environment, template_name=None):66+ self.environment = environment67+ if callable(environment.autoescape):68+ self.autoescape = environment.autoescape(template_name)69+ else:70+ self.autoescape = environment.autoescape71+ self.volatile = False72+73+ def save(self):74+ return self.__dict__.copy()75+76+ def revert(self, old):77+ self.__dict__.clear()78+ self.__dict__.update(old)79+80+81+def get_eval_context(node, ctx):82+ if ctx is None:83+ if node.environment is None:84+ raise RuntimeError(85+ "if no eval context is passed, the "86+ "node must have an attached "87+ "environment."88+ )89+ return EvalContext(node.environment)90+ return ctx91+92+93+class Node(with_metaclass(NodeType, object)):94+ """Baseclass for all Jinja nodes. There are a number of nodes available95+ of different types. There are four major types:96+97+ - :class:`Stmt`: statements98+ - :class:`Expr`: expressions99+ - :class:`Helper`: helper nodes100+ - :class:`Template`: the outermost wrapper node101+102+ All nodes have fields and attributes. Fields may be other nodes, lists,103+ or arbitrary values. Fields are passed to the constructor as regular104+ positional arguments, attributes as keyword arguments. Each node has105+ two attributes: `lineno` (the line number of the node) and `environment`.106+ The `environment` attribute is set at the end of the parsing process for107+ all nodes automatically.108+ """109+110+ fields = ()111+ attributes = ("lineno", "environment")112+ abstract = True113+114+ def __init__(self, *fields, **attributes):115+ if self.abstract:116+ raise TypeError("abstract nodes are not instantiable")117+ if fields:118+ if len(fields) != len(self.fields):119+ if not self.fields:120+ raise TypeError("%r takes 0 arguments" % self.__class__.__name__)121+ raise TypeError(122+ "%r takes 0 or %d argument%s"123+ % (124+ self.__class__.__name__,125+ len(self.fields),126+ len(self.fields) != 1 and "s" or "",127+ )128+ )129+ for name, arg in izip(self.fields, fields):130+ setattr(self, name, arg)131+ for attr in self.attributes:132+ setattr(self, attr, attributes.pop(attr, None))133+ if attributes:134+ raise TypeError("unknown attribute %r" % next(iter(attributes)))135+136+ def iter_fields(self, exclude=None, only=None):137+ """This method iterates over all fields that are defined and yields138+ ``(key, value)`` tuples. Per default all fields are returned, but139+ it's possible to limit that to some fields by providing the `only`140+ parameter or to exclude some using the `exclude` parameter. Both141+ should be sets or tuples of field names.142+ """143+ for name in self.fields:144+ if (145+ (exclude is only is None)146+ or (exclude is not None and name not in exclude)147+ or (only is not None and name in only)148+ ):149+ try:150+ yield name, getattr(self, name)151+ except AttributeError:152+ pass153+154+ def iter_child_nodes(self, exclude=None, only=None):155+ """Iterates over all direct child nodes of the node. This iterates156+ over all fields and yields the values of they are nodes. If the value157+ of a field is a list all the nodes in that list are returned.158+ """159+ for _, item in self.iter_fields(exclude, only):160+ if isinstance(item, list):161+ for n in item:162+ if isinstance(n, Node):163+ yield n164+ elif isinstance(item, Node):165+ yield item166+167+ def find(self, node_type):168+ """Find the first node of a given type. If no such node exists the169+ return value is `None`.170+ """171+ for result in self.find_all(node_type):172+ return result173+174+ def find_all(self, node_type):175+ """Find all the nodes of a given type. If the type is a tuple,176+ the check is performed for any of the tuple items.177+ """178+ for child in self.iter_child_nodes():179+ if isinstance(child, node_type):180+ yield child181+ for result in child.find_all(node_type):182+ yield result183+184+ def set_ctx(self, ctx):185+ """Reset the context of a node and all child nodes. Per default the186+ parser will all generate nodes that have a 'load' context as it's the187+ most common one. This method is used in the parser to set assignment188+ targets and other nodes to a store context.189+ """190+ todo = deque([self])191+ while todo:192+ node = todo.popleft()193+ if "ctx" in node.fields:194+ node.ctx = ctx195+ todo.extend(node.iter_child_nodes())196+ return self197+198+ def set_lineno(self, lineno, override=False):199+ """Set the line numbers of the node and children."""200+ todo = deque([self])201+ while todo:202+ node = todo.popleft()203+ if "lineno" in node.attributes:204+ if node.lineno is None or override:205+ node.lineno = lineno206+ todo.extend(node.iter_child_nodes())207+ return self208+209+ def set_environment(self, environment):210+ """Set the environment for all nodes."""211+ todo = deque([self])212+ while todo:213+ node = todo.popleft()214+ node.environment = environment215+ todo.extend(node.iter_child_nodes())216+ return self217+218+ def __eq__(self, other):219+ return type(self) is type(other) and tuple(self.iter_fields()) == tuple(220+ other.iter_fields()221+ )222+223+ def __ne__(self, other):224+ return not self.__eq__(other)225+226+ # Restore Python 2 hashing behavior on Python 3227+ __hash__ = object.__hash__228+229+ def __repr__(self):230+ return "%s(%s)" % (231+ self.__class__.__name__,232+ ", ".join("%s=%r" % (arg, getattr(self, arg, None)) for arg in self.fields),233+ )234+235+ def dump(self):236+ def _dump(node):237+ if not isinstance(node, Node):238+ buf.append(repr(node))239+ return240+241+ buf.append("nodes.%s(" % node.__class__.__name__)242+ if not node.fields:243+ buf.append(")")244+ return245+ for idx, field in enumerate(node.fields):246+ if idx:247+ buf.append(", ")248+ value = getattr(node, field)249+ if isinstance(value, list):250+ buf.append("[")251+ for idx, item in enumerate(value):252+ if idx:253+ buf.append(", ")254+ _dump(item)255+ buf.append("]")256+ else:257+ _dump(value)258+ buf.append(")")259+260+ buf = []261+ _dump(self)262+ return "".join(buf)263+264+265+class Stmt(Node):266+ """Base node for all statements."""267+268+ abstract = True269+270+271+class Helper(Node):272+ """Nodes that exist in a specific context only."""273+274+ abstract = True275+276+277+class Template(Node):278+ """Node that represents a template. This must be the outermost node that279+ is passed to the compiler.280+ """281+282+ fields = ("body",)283+284+285+class Output(Stmt):286+ """A node that holds multiple expressions which are then printed out.287+ This is used both for the `print` statement and the regular template data.288+ """289+290+ fields = ("nodes",)291+292+293+class Extends(Stmt):294+ """Represents an extends statement."""295+296+ fields = ("template",)297+298+299+class For(Stmt):300+ """The for loop. `target` is the target for the iteration (usually a301+ :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list302+ of nodes that are used as loop-body, and `else_` a list of nodes for the303+ `else` block. If no else node exists it has to be an empty list.304+305+ For filtered nodes an expression can be stored as `test`, otherwise `None`.306+ """307+308+ fields = ("target", "iter", "body", "else_", "test", "recursive")309+310+311+class If(Stmt):312+ """If `test` is true, `body` is rendered, else `else_`."""313+314+ fields = ("test", "body", "elif_", "else_")315+316+317+class Macro(Stmt):318+ """A macro definition. `name` is the name of the macro, `args` a list of319+ arguments and `defaults` a list of defaults if there are any. `body` is320+ a list of nodes for the macro body.321+ """322+323+ fields = ("name", "args", "defaults", "body")324+325+326+class CallBlock(Stmt):327+ """Like a macro without a name but a call instead. `call` is called with328+ the unnamed macro as `caller` argument this node holds.329+ """330+331+ fields = ("call", "args", "defaults", "body")332+333+334+class FilterBlock(Stmt):335+ """Node for filter sections."""336+337+ fields = ("body", "filter")338+339+340+class With(Stmt):341+ """Specific node for with statements. In older versions of Jinja the342+ with statement was implemented on the base of the `Scope` node instead.343+344+ .. versionadded:: 2.9.3345+ """346+347+ fields = ("targets", "values", "body")348+349+350+class Block(Stmt):351+ """A node that represents a block."""352+353+ fields = ("name", "body", "scoped")354+355+356+class Include(Stmt):357+ """A node that represents the include tag."""358+359+ fields = ("template", "with_context", "ignore_missing")360+361+362+class Import(Stmt):363+ """A node that represents the import tag."""364+365+ fields = ("template", "target", "with_context")366+367+368+class FromImport(Stmt):369+ """A node that represents the from import tag. It's important to not370+ pass unsafe names to the name attribute. The compiler translates the371+ attribute lookups directly into getattr calls and does *not* use the372+ subscript callback of the interface. As exported variables may not373+ start with double underscores (which the parser asserts) this is not a374+ problem for regular Jinja code, but if this node is used in an extension375+ extra care must be taken.376+377+ The list of names may contain tuples if aliases are wanted.378+ """379+380+ fields = ("template", "names", "with_context")381+382+383+class ExprStmt(Stmt):384+ """A statement that evaluates an expression and discards the result."""385+386+ fields = ("node",)387+388+389+class Assign(Stmt):390+ """Assigns an expression to a target."""391+392+ fields = ("target", "node")393+394+395+class AssignBlock(Stmt):396+ """Assigns a block to a target."""397+398+ fields = ("target", "filter", "body")399+400+401+class Expr(Node):402+ """Baseclass for all expressions."""403+404+ abstract = True405+406+ def as_const(self, eval_ctx=None):407+ """Return the value of the expression as constant or raise408+ :exc:`Impossible` if this was not possible.409+410+ An :class:`EvalContext` can be provided, if none is given411+ a default context is created which requires the nodes to have412+ an attached environment.413+414+ .. versionchanged:: 2.4415+ the `eval_ctx` parameter was added.416+ """417+ raise Impossible()418+419+ def can_assign(self):420+ """Check if it's possible to assign something to this node."""421+ return False422+423+424+class BinExpr(Expr):425+ """Baseclass for all binary expressions."""426+427+ fields = ("left", "right")428+ operator = None429+ abstract = True430+431+ def as_const(self, eval_ctx=None):432+ eval_ctx = get_eval_context(self, eval_ctx)433+ # intercepted operators cannot be folded at compile time434+ if (435+ self.environment.sandboxed436+ and self.operator in self.environment.intercepted_binops437+ ):438+ raise Impossible()439+ f = _binop_to_func[self.operator]440+ try:441+ return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))442+ except Exception:443+ raise Impossible()444+445+446+class UnaryExpr(Expr):447+ """Baseclass for all unary expressions."""448+449+ fields = ("node",)450+ operator = None451+ abstract = True452+453+ def as_const(self, eval_ctx=None):454+ eval_ctx = get_eval_context(self, eval_ctx)455+ # intercepted operators cannot be folded at compile time456+ if (457+ self.environment.sandboxed458+ and self.operator in self.environment.intercepted_unops459+ ):460+ raise Impossible()461+ f = _uaop_to_func[self.operator]462+ try:463+ return f(self.node.as_const(eval_ctx))464+ except Exception:465+ raise Impossible()466+467+468+class Name(Expr):469+ """Looks up a name or stores a value in a name.470+ The `ctx` of the node can be one of the following values:471+472+ - `store`: store a value in the name473+ - `load`: load that name474+ - `param`: like `store` but if the name was defined as function parameter.475+ """476+477+ fields = ("name", "ctx")478+479+ def can_assign(self):480+ return self.name not in ("true", "false", "none", "True", "False", "None")481+482+483+class NSRef(Expr):484+ """Reference to a namespace value assignment"""485+486+ fields = ("name", "attr")487+488+ def can_assign(self):489+ # We don't need any special checks here; NSRef assignments have a490+ # runtime check to ensure the target is a namespace object which will491+ # have been checked already as it is created using a normal assignment492+ # which goes through a `Name` node.493+ return True494+495+496+class Literal(Expr):497+ """Baseclass for literals."""498+499+ abstract = True500+501+502+class Const(Literal):503+ """All constant values. The parser will return this node for simple504+ constants such as ``42`` or ``"foo"`` but it can be used to store more505+ complex values such as lists too. Only constants with a safe506+ representation (objects where ``eval(repr(x)) == x`` is true).507+ """508+509+ fields = ("value",)510+511+ def as_const(self, eval_ctx=None):512+ rv = self.value513+ if (514+ PY2515+ and type(rv) is text_type516+ and self.environment.policies["compiler.ascii_str"]517+ ):518+ try:519+ rv = rv.encode("ascii")520+ except UnicodeError:521+ pass522+ return rv523+524+ @classmethod525+ def from_untrusted(cls, value, lineno=None, environment=None):526+ """Return a const object if the value is representable as527+ constant value in the generated code, otherwise it will raise528+ an `Impossible` exception.529+ """530+ from .compiler import has_safe_repr531+532+ if not has_safe_repr(value):533+ raise Impossible()534+ return cls(value, lineno=lineno, environment=environment)535+536+537+class TemplateData(Literal):538+ """A constant template string."""539+540+ fields = ("data",)541+542+ def as_const(self, eval_ctx=None):543+ eval_ctx = get_eval_context(self, eval_ctx)544+ if eval_ctx.volatile:545+ raise Impossible()546+ if eval_ctx.autoescape:547+ return Markup(self.data)548+ return self.data549+550+551+class Tuple(Literal):552+ """For loop unpacking and some other things like multiple arguments553+ for subscripts. Like for :class:`Name` `ctx` specifies if the tuple554+ is used for loading the names or storing.555+ """556+557+ fields = ("items", "ctx")558+559+ def as_const(self, eval_ctx=None):560+ eval_ctx = get_eval_context(self, eval_ctx)561+ return tuple(x.as_const(eval_ctx) for x in self.items)562+563+ def can_assign(self):564+ for item in self.items:565+ if not item.can_assign():566+ return False567+ return True568+569+570+class List(Literal):571+ """Any list literal such as ``[1, 2, 3]``"""572+573+ fields = ("items",)574+575+ def as_const(self, eval_ctx=None):576+ eval_ctx = get_eval_context(self, eval_ctx)577+ return [x.as_const(eval_ctx) for x in self.items]578+579+580+class Dict(Literal):581+ """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of582+ :class:`Pair` nodes.583+ """584+585+ fields = ("items",)586+587+ def as_const(self, eval_ctx=None):588+ eval_ctx = get_eval_context(self, eval_ctx)589+ return dict(x.as_const(eval_ctx) for x in self.items)590+591+592+class Pair(Helper):593+ """A key, value pair for dicts."""594+595+ fields = ("key", "value")596+597+ def as_const(self, eval_ctx=None):598+ eval_ctx = get_eval_context(self, eval_ctx)599+ return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)600+601+602+class Keyword(Helper):603+ """A key, value pair for keyword arguments where key is a string."""604+605+ fields = ("key", "value")606+607+ def as_const(self, eval_ctx=None):608+ eval_ctx = get_eval_context(self, eval_ctx)609+ return self.key, self.value.as_const(eval_ctx)610+611+612+class CondExpr(Expr):613+ """A conditional expression (inline if expression). (``{{614+ foo if bar else baz }}``)615+ """616+617+ fields = ("test", "expr1", "expr2")618+619+ def as_const(self, eval_ctx=None):620+ eval_ctx = get_eval_context(self, eval_ctx)621+ if self.test.as_const(eval_ctx):622+ return self.expr1.as_const(eval_ctx)623+624+ # if we evaluate to an undefined object, we better do that at runtime625+ if self.expr2 is None:626+ raise Impossible()627+628+ return self.expr2.as_const(eval_ctx)629+630+631+def args_as_const(node, eval_ctx):632+ args = [x.as_const(eval_ctx) for x in node.args]633+ kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)634+635+ if node.dyn_args is not None:636+ try:637+ args.extend(node.dyn_args.as_const(eval_ctx))638+ except Exception:639+ raise Impossible()640+641+ if node.dyn_kwargs is not None:642+ try:643+ kwargs.update(node.dyn_kwargs.as_const(eval_ctx))644+ except Exception:645+ raise Impossible()646+647+ return args, kwargs648+649+650+class Filter(Expr):651+ """This node applies a filter on an expression. `name` is the name of652+ the filter, the rest of the fields are the same as for :class:`Call`.653+654+ If the `node` of a filter is `None` the contents of the last buffer are655+ filtered. Buffers are created by macros and filter blocks.656+ """657+658+ fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")659+660+ def as_const(self, eval_ctx=None):661+ eval_ctx = get_eval_context(self, eval_ctx)662+663+ if eval_ctx.volatile or self.node is None:664+ raise Impossible()665+666+ # we have to be careful here because we call filter_ below.667+ # if this variable would be called filter, 2to3 would wrap the668+ # call in a list because it is assuming we are talking about the669+ # builtin filter function here which no longer returns a list in670+ # python 3. because of that, do not rename filter_ to filter!671+ filter_ = self.environment.filters.get(self.name)672+673+ if filter_ is None or getattr(filter_, "contextfilter", False):674+ raise Impossible()675+676+ # We cannot constant handle async filters, so we need to make sure677+ # to not go down this path.678+ if eval_ctx.environment.is_async and getattr(679+ filter_, "asyncfiltervariant", False680+ ):681+ raise Impossible()682+683+ args, kwargs = args_as_const(self, eval_ctx)684+ args.insert(0, self.node.as_const(eval_ctx))685+686+ if getattr(filter_, "evalcontextfilter", False):687+ args.insert(0, eval_ctx)688+ elif getattr(filter_, "environmentfilter", False):689+ args.insert(0, self.environment)690+691+ try:692+ return filter_(*args, **kwargs)693+ except Exception:694+ raise Impossible()695+696+697+class Test(Expr):698+ """Applies a test on an expression. `name` is the name of the test, the699+ rest of the fields are the same as for :class:`Call`.700+ """701+702+ fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")703+704+ def as_const(self, eval_ctx=None):705+ test = self.environment.tests.get(self.name)706+707+ if test is None:708+ raise Impossible()709+710+ eval_ctx = get_eval_context(self, eval_ctx)711+ args, kwargs = args_as_const(self, eval_ctx)712+ args.insert(0, self.node.as_const(eval_ctx))713+714+ try:715+ return test(*args, **kwargs)716+ except Exception:717+ raise Impossible()718+719+720+class Call(Expr):721+ """Calls an expression. `args` is a list of arguments, `kwargs` a list722+ of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`723+ and `dyn_kwargs` has to be either `None` or a node that is used as724+ node for dynamic positional (``*args``) or keyword (``**kwargs``)725+ arguments.726+ """727+728+ fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")729+730+731+class Getitem(Expr):732+ """Get an attribute or item from an expression and prefer the item."""733+734+ fields = ("node", "arg", "ctx")735+736+ def as_const(self, eval_ctx=None):737+ eval_ctx = get_eval_context(self, eval_ctx)738+ if self.ctx != "load":739+ raise Impossible()740+ try:741+ return self.environment.getitem(742+ self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)743+ )744+ except Exception:745+ raise Impossible()746+747+ def can_assign(self):748+ return False749+750+751+class Getattr(Expr):752+ """Get an attribute or item from an expression that is a ascii-only753+ bytestring and prefer the attribute.754+ """755+756+ fields = ("node", "attr", "ctx")757+758+ def as_const(self, eval_ctx=None):759+ if self.ctx != "load":760+ raise Impossible()761+ try:762+ eval_ctx = get_eval_context(self, eval_ctx)763+ return self.environment.getattr(self.node.as_const(eval_ctx), self.attr)764+ except Exception:765+ raise Impossible()766+767+ def can_assign(self):768+ return False769+770+771+class Slice(Expr):772+ """Represents a slice object. This must only be used as argument for773+ :class:`Subscript`.774+ """775+776+ fields = ("start", "stop", "step")777+778+ def as_const(self, eval_ctx=None):779+ eval_ctx = get_eval_context(self, eval_ctx)780+781+ def const(obj):782+ if obj is None:783+ return None784+ return obj.as_const(eval_ctx)785+786+ return slice(const(self.start), const(self.stop), const(self.step))787+788+789+class Concat(Expr):790+ """Concatenates the list of expressions provided after converting them to791+ unicode.792+ """793+794+ fields = ("nodes",)795+796+ def as_const(self, eval_ctx=None):797+ eval_ctx = get_eval_context(self, eval_ctx)798+ return "".join(text_type(x.as_const(eval_ctx)) for x in self.nodes)799+800+801+class Compare(Expr):802+ """Compares an expression with some other expressions. `ops` must be a803+ list of :class:`Operand`\\s.804+ """805+806+ fields = ("expr", "ops")807+808+ def as_const(self, eval_ctx=None):809+ eval_ctx = get_eval_context(self, eval_ctx)810+ result = value = self.expr.as_const(eval_ctx)811+812+ try:813+ for op in self.ops:814+ new_value = op.expr.as_const(eval_ctx)815+ result = _cmpop_to_func[op.op](value, new_value)816+817+ if not result:818+ return False819+820+ value = new_value821+ except Exception:822+ raise Impossible()823+824+ return result825+826+827+class Operand(Helper):828+ """Holds an operator and an expression."""829+830+ fields = ("op", "expr")831+832+833+if __debug__:834+ Operand.__doc__ += "\nThe following operators are available: " + ", ".join(835+ sorted(836+ "``%s``" % x837+ for x in set(_binop_to_func) | set(_uaop_to_func) | set(_cmpop_to_func)838+ )839+ )840+841+842+class Mul(BinExpr):843+ """Multiplies the left with the right node."""844+845+ operator = "*"846+847+848+class Div(BinExpr):849+ """Divides the left by the right node."""850+851+ operator = "/"852+853+854+class FloorDiv(BinExpr):855+ """Divides the left by the right node and truncates conver the856+ result into an integer by truncating.857+ """858+859+ operator = "//"860+861+862+class Add(BinExpr):863+ """Add the left to the right node."""864+865+ operator = "+"866+867+868+class Sub(BinExpr):869+ """Subtract the right from the left node."""870+871+ operator = "-"872+873+874+class Mod(BinExpr):875+ """Left modulo right."""876+877+ operator = "%"878+879+880+class Pow(BinExpr):881+ """Left to the power of right."""882+883+ operator = "**"884+885+886+class And(BinExpr):887+ """Short circuited AND."""888+889+ operator = "and"890+891+ def as_const(self, eval_ctx=None):892+ eval_ctx = get_eval_context(self, eval_ctx)893+ return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)894+895+896+class Or(BinExpr):897+ """Short circuited OR."""898+899+ operator = "or"900+901+ def as_const(self, eval_ctx=None):902+ eval_ctx = get_eval_context(self, eval_ctx)903+ return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)904+905+906+class Not(UnaryExpr):907+ """Negate the expression."""908+909+ operator = "not"910+911+912+class Neg(UnaryExpr):913+ """Make the expression negative."""914+915+ operator = "-"916+917+918+class Pos(UnaryExpr):919+ """Make the expression positive (noop for most expressions)"""920+921+ operator = "+"922+923+924+# Helpers for extensions925+926+927+class EnvironmentAttribute(Expr):928+ """Loads an attribute from the environment object. This is useful for929+ extensions that want to call a callback stored on the environment.930+ """931+932+ fields = ("name",)933+934+935+class ExtensionAttribute(Expr):936+ """Returns the attribute of an extension bound to the environment.937+ The identifier is the identifier of the :class:`Extension`.938+939+ This node is usually constructed by calling the940+ :meth:`~jinja2.ext.Extension.attr` method on an extension.941+ """942+943+ fields = ("identifier", "name")944+945+946+class ImportedName(Expr):947+ """If created with an import name the import name is returned on node948+ access. For example ``ImportedName('cgi.escape')`` returns the `escape`949+ function from the cgi module on evaluation. Imports are optimized by the950+ compiler so there is no need to assign them to local variables.951+ """952+953+ fields = ("importname",)954+955+956+class InternalName(Expr):957+ """An internal name in the compiler. You cannot create these nodes958+ yourself but the parser provides a959+ :meth:`~jinja2.parser.Parser.free_identifier` method that creates960+ a new identifier for you. This identifier is not available from the961+ template and is not threated specially by the compiler.962+ """963+964+ fields = ("name",)965+966+ def __init__(self):967+ raise TypeError(968+ "Can't create internal names. Use the "969+ "`free_identifier` method on a parser."970+ )971+972+973+class MarkSafe(Expr):974+ """Mark the wrapped expression as safe (wrap it as `Markup`)."""975+976+ fields = ("expr",)977+978+ def as_const(self, eval_ctx=None):979+ eval_ctx = get_eval_context(self, eval_ctx)980+ return Markup(self.expr.as_const(eval_ctx))981+982+983+class MarkSafeIfAutoescape(Expr):984+ """Mark the wrapped expression as safe (wrap it as `Markup`) but985+ only if autoescaping is active.986+987+ .. versionadded:: 2.5988+ """989+990+ fields = ("expr",)991+992+ def as_const(self, eval_ctx=None):993+ eval_ctx = get_eval_context(self, eval_ctx)994+ if eval_ctx.volatile:995+ raise Impossible()996+ expr = self.expr.as_const(eval_ctx)997+ if eval_ctx.autoescape:998+ return Markup(expr)999+ return expr1000+1001+1002+class ContextReference(Expr):1003+ """Returns the current template context. It can be used like a1004+ :class:`Name` node, with a ``'load'`` ctx and will return the1005+ current :class:`~jinja2.runtime.Context` object.1006+1007+ Here an example that assigns the current template name to a1008+ variable named `foo`::1009+1010+ Assign(Name('foo', ctx='store'),1011+ Getattr(ContextReference(), 'name'))1012+1013+ This is basically equivalent to using the1014+ :func:`~jinja2.contextfunction` decorator when using the1015+ high-level API, which causes a reference to the context to be passed1016+ as the first argument to a function.1017+ """1018+1019+1020+class DerivedContextReference(Expr):1021+ """Return the current template context including locals. Behaves1022+ exactly like :class:`ContextReference`, but includes local1023+ variables, such as from a ``for`` loop.1024+1025+ .. versionadded:: 2.111026+ """1027+1028+1029+class Continue(Stmt):1030+ """Continue a loop."""1031+1032+1033+class Break(Stmt):1034+ """Break a loop."""1035+1036+1037+class Scope(Stmt):1038+ """An artificial scope."""1039+1040+ fields = ("body",)1041+1042+1043+class OverlayScope(Stmt):1044+ """An overlay scope for extensions. This is a largely unoptimized scope1045+ that however can be used to introduce completely arbitrary variables into1046+ a sub scope from a dictionary or dictionary like object. The `context`1047+ field has to evaluate to a dictionary object.1048+1049+ Example usage::1050+1051+ OverlayScope(context=self.call_method('get_context'),1052+ body=[...])1053+1054+ .. versionadded:: 2.101055+ """1056+1057+ fields = ("context", "body")1058+1059+1060+class EvalContextModifier(Stmt):1061+ """Modifies the eval context. For each option that should be modified,1062+ a :class:`Keyword` has to be added to the :attr:`options` list.1063+1064+ Example to change the `autoescape` setting::1065+1066+ EvalContextModifier(options=[Keyword('autoescape', Const(True))])1067+ """1068+1069+ fields = ("options",)1070+1071+1072+class ScopedEvalContextModifier(EvalContextModifier):1073+ """Modifies the eval context and reverts it later. Works exactly like1074+ :class:`EvalContextModifier` but will only modify the1075+ :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.1076+ """1077+1078+ fields = ("body",)1079+1080+1081+# make sure nobody creates custom nodes1082+def _failing_new(*args, **kwargs):1083+ raise TypeError("can't create custom node types")1084+1085+1086+NodeType.__new__ = staticmethod(_failing_new)1087+del _failing_newadded:src/jinja/optimizer.py+41 added
1+# -*- coding: utf-8 -*-2+"""The optimizer tries to constant fold expressions and modify the AST3+in place so that it should be faster to evaluate.4+5+Because the AST does not contain all the scoping information and the6+compiler has to find that out, we cannot do all the optimizations we7+want. For example, loop unrolling doesn't work because unrolled loops8+would have a different scope. The solution would be a second syntax tree9+that stored the scoping rules.10+"""11+from . import nodes12+from .visitor import NodeTransformer13+14+15+def optimize(node, environment):16+ """The context hint can be used to perform an static optimization17+ based on the context given."""18+ optimizer = Optimizer(environment)19+ return optimizer.visit(node)20+21+22+class Optimizer(NodeTransformer):23+ def __init__(self, environment):24+ self.environment = environment25+26+ def generic_visit(self, node, *args, **kwargs):27+ node = super(Optimizer, self).generic_visit(node, *args, **kwargs)28+29+ # Do constant folding. Some other nodes besides Expr have30+ # as_const, but folding them causes errors later on.31+ if isinstance(node, nodes.Expr):32+ try:33+ return nodes.Const.from_untrusted(34+ node.as_const(args[0] if args else None),35+ lineno=node.lineno,36+ environment=self.environment,37+ )38+ except nodes.Impossible:39+ pass40+41+ return nodeadded:src/jinja/parser.py+939 added
1+# -*- coding: utf-8 -*-2+"""Parse tokens from the lexer into nodes for the compiler."""3+from . import nodes4+from ._compat import imap5+from .exceptions import TemplateAssertionError6+from .exceptions import TemplateSyntaxError7+from .lexer import describe_token8+from .lexer import describe_token_expr9+10+_statement_keywords = frozenset(11+ [12+ "for",13+ "if",14+ "block",15+ "extends",16+ "print",17+ "macro",18+ "include",19+ "from",20+ "import",21+ "set",22+ "with",23+ "autoescape",24+ ]25+)26+_compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])27+28+_math_nodes = {29+ "add": nodes.Add,30+ "sub": nodes.Sub,31+ "mul": nodes.Mul,32+ "div": nodes.Div,33+ "floordiv": nodes.FloorDiv,34+ "mod": nodes.Mod,35+}36+37+38+class Parser(object):39+ """This is the central parsing class Jinja uses. It's passed to40+ extensions and can be used to parse expressions or statements.41+ """42+43+ def __init__(self, environment, source, name=None, filename=None, state=None):44+ self.environment = environment45+ self.stream = environment._tokenize(source, name, filename, state)46+ self.name = name47+ self.filename = filename48+ self.closed = False49+ self.extensions = {}50+ for extension in environment.iter_extensions():51+ for tag in extension.tags:52+ self.extensions[tag] = extension.parse53+ self._last_identifier = 054+ self._tag_stack = []55+ self._end_token_stack = []56+57+ def fail(self, msg, lineno=None, exc=TemplateSyntaxError):58+ """Convenience method that raises `exc` with the message, passed59+ line number or last line number as well as the current name and60+ filename.61+ """62+ if lineno is None:63+ lineno = self.stream.current.lineno64+ raise exc(msg, lineno, self.name, self.filename)65+66+ def _fail_ut_eof(self, name, end_token_stack, lineno):67+ expected = []68+ for exprs in end_token_stack:69+ expected.extend(imap(describe_token_expr, exprs))70+ if end_token_stack:71+ currently_looking = " or ".join(72+ "'%s'" % describe_token_expr(expr) for expr in end_token_stack[-1]73+ )74+ else:75+ currently_looking = None76+77+ if name is None:78+ message = ["Unexpected end of template."]79+ else:80+ message = ["Encountered unknown tag '%s'." % name]81+82+ if currently_looking:83+ if name is not None and name in expected:84+ message.append(85+ "You probably made a nesting mistake. Jinja "86+ "is expecting this tag, but currently looking "87+ "for %s." % currently_looking88+ )89+ else:90+ message.append(91+ "Jinja was looking for the following tags: "92+ "%s." % currently_looking93+ )94+95+ if self._tag_stack:96+ message.append(97+ "The innermost block that needs to be "98+ "closed is '%s'." % self._tag_stack[-1]99+ )100+101+ self.fail(" ".join(message), lineno)102+103+ def fail_unknown_tag(self, name, lineno=None):104+ """Called if the parser encounters an unknown tag. Tries to fail105+ with a human readable error message that could help to identify106+ the problem.107+ """108+ return self._fail_ut_eof(name, self._end_token_stack, lineno)109+110+ def fail_eof(self, end_tokens=None, lineno=None):111+ """Like fail_unknown_tag but for end of template situations."""112+ stack = list(self._end_token_stack)113+ if end_tokens is not None:114+ stack.append(end_tokens)115+ return self._fail_ut_eof(None, stack, lineno)116+117+ def is_tuple_end(self, extra_end_rules=None):118+ """Are we at the end of a tuple?"""119+ if self.stream.current.type in ("variable_end", "block_end", "rparen"):120+ return True121+ elif extra_end_rules is not None:122+ return self.stream.current.test_any(extra_end_rules)123+ return False124+125+ def free_identifier(self, lineno=None):126+ """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""127+ self._last_identifier += 1128+ rv = object.__new__(nodes.InternalName)129+ nodes.Node.__init__(rv, "fi%d" % self._last_identifier, lineno=lineno)130+ return rv131+132+ def parse_statement(self):133+ """Parse a single statement."""134+ token = self.stream.current135+ if token.type != "name":136+ self.fail("tag name expected", token.lineno)137+ self._tag_stack.append(token.value)138+ pop_tag = True139+ try:140+ if token.value in _statement_keywords:141+ return getattr(self, "parse_" + self.stream.current.value)()142+ if token.value == "call":143+ return self.parse_call_block()144+ if token.value == "filter":145+ return self.parse_filter_block()146+ ext = self.extensions.get(token.value)147+ if ext is not None:148+ return ext(self)149+150+ # did not work out, remove the token we pushed by accident151+ # from the stack so that the unknown tag fail function can152+ # produce a proper error message.153+ self._tag_stack.pop()154+ pop_tag = False155+ self.fail_unknown_tag(token.value, token.lineno)156+ finally:157+ if pop_tag:158+ self._tag_stack.pop()159+160+ def parse_statements(self, end_tokens, drop_needle=False):161+ """Parse multiple statements into a list until one of the end tokens162+ is reached. This is used to parse the body of statements as it also163+ parses template data if appropriate. The parser checks first if the164+ current token is a colon and skips it if there is one. Then it checks165+ for the block end and parses until if one of the `end_tokens` is166+ reached. Per default the active token in the stream at the end of167+ the call is the matched end token. If this is not wanted `drop_needle`168+ can be set to `True` and the end token is removed.169+ """170+ # the first token may be a colon for python compatibility171+ self.stream.skip_if("colon")172+173+ # in the future it would be possible to add whole code sections174+ # by adding some sort of end of statement token and parsing those here.175+ self.stream.expect("block_end")176+ result = self.subparse(end_tokens)177+178+ # we reached the end of the template too early, the subparser179+ # does not check for this, so we do that now180+ if self.stream.current.type == "eof":181+ self.fail_eof(end_tokens)182+183+ if drop_needle:184+ next(self.stream)185+ return result186+187+ def parse_set(self):188+ """Parse an assign statement."""189+ lineno = next(self.stream).lineno190+ target = self.parse_assign_target(with_namespace=True)191+ if self.stream.skip_if("assign"):192+ expr = self.parse_tuple()193+ return nodes.Assign(target, expr, lineno=lineno)194+ filter_node = self.parse_filter(None)195+ body = self.parse_statements(("name:endset",), drop_needle=True)196+ return nodes.AssignBlock(target, filter_node, body, lineno=lineno)197+198+ def parse_for(self):199+ """Parse a for loop."""200+ lineno = self.stream.expect("name:for").lineno201+ target = self.parse_assign_target(extra_end_rules=("name:in",))202+ self.stream.expect("name:in")203+ iter = self.parse_tuple(204+ with_condexpr=False, extra_end_rules=("name:recursive",)205+ )206+ test = None207+ if self.stream.skip_if("name:if"):208+ test = self.parse_expression()209+ recursive = self.stream.skip_if("name:recursive")210+ body = self.parse_statements(("name:endfor", "name:else"))211+ if next(self.stream).value == "endfor":212+ else_ = []213+ else:214+ else_ = self.parse_statements(("name:endfor",), drop_needle=True)215+ return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)216+217+ def parse_if(self):218+ """Parse an if construct."""219+ node = result = nodes.If(lineno=self.stream.expect("name:if").lineno)220+ while 1:221+ node.test = self.parse_tuple(with_condexpr=False)222+ node.body = self.parse_statements(("name:elif", "name:else", "name:endif"))223+ node.elif_ = []224+ node.else_ = []225+ token = next(self.stream)226+ if token.test("name:elif"):227+ node = nodes.If(lineno=self.stream.current.lineno)228+ result.elif_.append(node)229+ continue230+ elif token.test("name:else"):231+ result.else_ = self.parse_statements(("name:endif",), drop_needle=True)232+ break233+ return result234+235+ def parse_with(self):236+ node = nodes.With(lineno=next(self.stream).lineno)237+ targets = []238+ values = []239+ while self.stream.current.type != "block_end":240+ if targets:241+ self.stream.expect("comma")242+ target = self.parse_assign_target()243+ target.set_ctx("param")244+ targets.append(target)245+ self.stream.expect("assign")246+ values.append(self.parse_expression())247+ node.targets = targets248+ node.values = values249+ node.body = self.parse_statements(("name:endwith",), drop_needle=True)250+ return node251+252+ def parse_autoescape(self):253+ node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)254+ node.options = [nodes.Keyword("autoescape", self.parse_expression())]255+ node.body = self.parse_statements(("name:endautoescape",), drop_needle=True)256+ return nodes.Scope([node])257+258+ def parse_block(self):259+ node = nodes.Block(lineno=next(self.stream).lineno)260+ node.name = self.stream.expect("name").value261+ node.scoped = self.stream.skip_if("name:scoped")262+263+ # common problem people encounter when switching from django264+ # to jinja. we do not support hyphens in block names, so let's265+ # raise a nicer error message in that case.266+ if self.stream.current.type == "sub":267+ self.fail(268+ "Block names in Jinja have to be valid Python "269+ "identifiers and may not contain hyphens, use an "270+ "underscore instead."271+ )272+273+ node.body = self.parse_statements(("name:endblock",), drop_needle=True)274+ self.stream.skip_if("name:" + node.name)275+ return node276+277+ def parse_extends(self):278+ node = nodes.Extends(lineno=next(self.stream).lineno)279+ node.template = self.parse_expression()280+ return node281+282+ def parse_import_context(self, node, default):283+ if self.stream.current.test_any(284+ "name:with", "name:without"285+ ) and self.stream.look().test("name:context"):286+ node.with_context = next(self.stream).value == "with"287+ self.stream.skip()288+ else:289+ node.with_context = default290+ return node291+292+ def parse_include(self):293+ node = nodes.Include(lineno=next(self.stream).lineno)294+ node.template = self.parse_expression()295+ if self.stream.current.test("name:ignore") and self.stream.look().test(296+ "name:missing"297+ ):298+ node.ignore_missing = True299+ self.stream.skip(2)300+ else:301+ node.ignore_missing = False302+ return self.parse_import_context(node, True)303+304+ def parse_import(self):305+ node = nodes.Import(lineno=next(self.stream).lineno)306+ node.template = self.parse_expression()307+ self.stream.expect("name:as")308+ node.target = self.parse_assign_target(name_only=True).name309+ return self.parse_import_context(node, False)310+311+ def parse_from(self):312+ node = nodes.FromImport(lineno=next(self.stream).lineno)313+ node.template = self.parse_expression()314+ self.stream.expect("name:import")315+ node.names = []316+317+ def parse_context():318+ if self.stream.current.value in (319+ "with",320+ "without",321+ ) and self.stream.look().test("name:context"):322+ node.with_context = next(self.stream).value == "with"323+ self.stream.skip()324+ return True325+ return False326+327+ while 1:328+ if node.names:329+ self.stream.expect("comma")330+ if self.stream.current.type == "name":331+ if parse_context():332+ break333+ target = self.parse_assign_target(name_only=True)334+ if target.name.startswith("_"):335+ self.fail(336+ "names starting with an underline can not be imported",337+ target.lineno,338+ exc=TemplateAssertionError,339+ )340+ if self.stream.skip_if("name:as"):341+ alias = self.parse_assign_target(name_only=True)342+ node.names.append((target.name, alias.name))343+ else:344+ node.names.append(target.name)345+ if parse_context() or self.stream.current.type != "comma":346+ break347+ else:348+ self.stream.expect("name")349+ if not hasattr(node, "with_context"):350+ node.with_context = False351+ return node352+353+ def parse_signature(self, node):354+ node.args = args = []355+ node.defaults = defaults = []356+ self.stream.expect("lparen")357+ while self.stream.current.type != "rparen":358+ if args:359+ self.stream.expect("comma")360+ arg = self.parse_assign_target(name_only=True)361+ arg.set_ctx("param")362+ if self.stream.skip_if("assign"):363+ defaults.append(self.parse_expression())364+ elif defaults:365+ self.fail("non-default argument follows default argument")366+ args.append(arg)367+ self.stream.expect("rparen")368+369+ def parse_call_block(self):370+ node = nodes.CallBlock(lineno=next(self.stream).lineno)371+ if self.stream.current.type == "lparen":372+ self.parse_signature(node)373+ else:374+ node.args = []375+ node.defaults = []376+377+ node.call = self.parse_expression()378+ if not isinstance(node.call, nodes.Call):379+ self.fail("expected call", node.lineno)380+ node.body = self.parse_statements(("name:endcall",), drop_needle=True)381+ return node382+383+ def parse_filter_block(self):384+ node = nodes.FilterBlock(lineno=next(self.stream).lineno)385+ node.filter = self.parse_filter(None, start_inline=True)386+ node.body = self.parse_statements(("name:endfilter",), drop_needle=True)387+ return node388+389+ def parse_macro(self):390+ node = nodes.Macro(lineno=next(self.stream).lineno)391+ node.name = self.parse_assign_target(name_only=True).name392+ self.parse_signature(node)393+ node.body = self.parse_statements(("name:endmacro",), drop_needle=True)394+ return node395+396+ def parse_print(self):397+ node = nodes.Output(lineno=next(self.stream).lineno)398+ node.nodes = []399+ while self.stream.current.type != "block_end":400+ if node.nodes:401+ self.stream.expect("comma")402+ node.nodes.append(self.parse_expression())403+ return node404+405+ def parse_assign_target(406+ self,407+ with_tuple=True,408+ name_only=False,409+ extra_end_rules=None,410+ with_namespace=False,411+ ):412+ """Parse an assignment target. As Jinja allows assignments to413+ tuples, this function can parse all allowed assignment targets. Per414+ default assignments to tuples are parsed, that can be disable however415+ by setting `with_tuple` to `False`. If only assignments to names are416+ wanted `name_only` can be set to `True`. The `extra_end_rules`417+ parameter is forwarded to the tuple parsing function. If418+ `with_namespace` is enabled, a namespace assignment may be parsed.419+ """420+ if with_namespace and self.stream.look().type == "dot":421+ token = self.stream.expect("name")422+ next(self.stream) # dot423+ attr = self.stream.expect("name")424+ target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)425+ elif name_only:426+ token = self.stream.expect("name")427+ target = nodes.Name(token.value, "store", lineno=token.lineno)428+ else:429+ if with_tuple:430+ target = self.parse_tuple(431+ simplified=True, extra_end_rules=extra_end_rules432+ )433+ else:434+ target = self.parse_primary()435+ target.set_ctx("store")436+ if not target.can_assign():437+ self.fail(438+ "can't assign to %r" % target.__class__.__name__.lower(), target.lineno439+ )440+ return target441+442+ def parse_expression(self, with_condexpr=True):443+ """Parse an expression. Per default all expressions are parsed, if444+ the optional `with_condexpr` parameter is set to `False` conditional445+ expressions are not parsed.446+ """447+ if with_condexpr:448+ return self.parse_condexpr()449+ return self.parse_or()450+451+ def parse_condexpr(self):452+ lineno = self.stream.current.lineno453+ expr1 = self.parse_or()454+ while self.stream.skip_if("name:if"):455+ expr2 = self.parse_or()456+ if self.stream.skip_if("name:else"):457+ expr3 = self.parse_condexpr()458+ else:459+ expr3 = None460+ expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)461+ lineno = self.stream.current.lineno462+ return expr1463+464+ def parse_or(self):465+ lineno = self.stream.current.lineno466+ left = self.parse_and()467+ while self.stream.skip_if("name:or"):468+ right = self.parse_and()469+ left = nodes.Or(left, right, lineno=lineno)470+ lineno = self.stream.current.lineno471+ return left472+473+ def parse_and(self):474+ lineno = self.stream.current.lineno475+ left = self.parse_not()476+ while self.stream.skip_if("name:and"):477+ right = self.parse_not()478+ left = nodes.And(left, right, lineno=lineno)479+ lineno = self.stream.current.lineno480+ return left481+482+ def parse_not(self):483+ if self.stream.current.test("name:not"):484+ lineno = next(self.stream).lineno485+ return nodes.Not(self.parse_not(), lineno=lineno)486+ return self.parse_compare()487+488+ def parse_compare(self):489+ lineno = self.stream.current.lineno490+ expr = self.parse_math1()491+ ops = []492+ while 1:493+ token_type = self.stream.current.type494+ if token_type in _compare_operators:495+ next(self.stream)496+ ops.append(nodes.Operand(token_type, self.parse_math1()))497+ elif self.stream.skip_if("name:in"):498+ ops.append(nodes.Operand("in", self.parse_math1()))499+ elif self.stream.current.test("name:not") and self.stream.look().test(500+ "name:in"501+ ):502+ self.stream.skip(2)503+ ops.append(nodes.Operand("notin", self.parse_math1()))504+ else:505+ break506+ lineno = self.stream.current.lineno507+ if not ops:508+ return expr509+ return nodes.Compare(expr, ops, lineno=lineno)510+511+ def parse_math1(self):512+ lineno = self.stream.current.lineno513+ left = self.parse_concat()514+ while self.stream.current.type in ("add", "sub"):515+ cls = _math_nodes[self.stream.current.type]516+ next(self.stream)517+ right = self.parse_concat()518+ left = cls(left, right, lineno=lineno)519+ lineno = self.stream.current.lineno520+ return left521+522+ def parse_concat(self):523+ lineno = self.stream.current.lineno524+ args = [self.parse_math2()]525+ while self.stream.current.type == "tilde":526+ next(self.stream)527+ args.append(self.parse_math2())528+ if len(args) == 1:529+ return args[0]530+ return nodes.Concat(args, lineno=lineno)531+532+ def parse_math2(self):533+ lineno = self.stream.current.lineno534+ left = self.parse_pow()535+ while self.stream.current.type in ("mul", "div", "floordiv", "mod"):536+ cls = _math_nodes[self.stream.current.type]537+ next(self.stream)538+ right = self.parse_pow()539+ left = cls(left, right, lineno=lineno)540+ lineno = self.stream.current.lineno541+ return left542+543+ def parse_pow(self):544+ lineno = self.stream.current.lineno545+ left = self.parse_unary()546+ while self.stream.current.type == "pow":547+ next(self.stream)548+ right = self.parse_unary()549+ left = nodes.Pow(left, right, lineno=lineno)550+ lineno = self.stream.current.lineno551+ return left552+553+ def parse_unary(self, with_filter=True):554+ token_type = self.stream.current.type555+ lineno = self.stream.current.lineno556+ if token_type == "sub":557+ next(self.stream)558+ node = nodes.Neg(self.parse_unary(False), lineno=lineno)559+ elif token_type == "add":560+ next(self.stream)561+ node = nodes.Pos(self.parse_unary(False), lineno=lineno)562+ else:563+ node = self.parse_primary()564+ node = self.parse_postfix(node)565+ if with_filter:566+ node = self.parse_filter_expr(node)567+ return node568+569+ def parse_primary(self):570+ token = self.stream.current571+ if token.type == "name":572+ if token.value in ("true", "false", "True", "False"):573+ node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)574+ elif token.value in ("none", "None"):575+ node = nodes.Const(None, lineno=token.lineno)576+ else:577+ node = nodes.Name(token.value, "load", lineno=token.lineno)578+ next(self.stream)579+ elif token.type == "string":580+ next(self.stream)581+ buf = [token.value]582+ lineno = token.lineno583+ while self.stream.current.type == "string":584+ buf.append(self.stream.current.value)585+ next(self.stream)586+ node = nodes.Const("".join(buf), lineno=lineno)587+ elif token.type in ("integer", "float"):588+ next(self.stream)589+ node = nodes.Const(token.value, lineno=token.lineno)590+ elif token.type == "lparen":591+ next(self.stream)592+ node = self.parse_tuple(explicit_parentheses=True)593+ self.stream.expect("rparen")594+ elif token.type == "lbracket":595+ node = self.parse_list()596+ elif token.type == "lbrace":597+ node = self.parse_dict()598+ else:599+ self.fail("unexpected '%s'" % describe_token(token), token.lineno)600+ return node601+602+ def parse_tuple(603+ self,604+ simplified=False,605+ with_condexpr=True,606+ extra_end_rules=None,607+ explicit_parentheses=False,608+ ):609+ """Works like `parse_expression` but if multiple expressions are610+ delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.611+ This method could also return a regular expression instead of a tuple612+ if no commas where found.613+614+ The default parsing mode is a full tuple. If `simplified` is `True`615+ only names and literals are parsed. The `no_condexpr` parameter is616+ forwarded to :meth:`parse_expression`.617+618+ Because tuples do not require delimiters and may end in a bogus comma619+ an extra hint is needed that marks the end of a tuple. For example620+ for loops support tuples between `for` and `in`. In that case the621+ `extra_end_rules` is set to ``['name:in']``.622+623+ `explicit_parentheses` is true if the parsing was triggered by an624+ expression in parentheses. This is used to figure out if an empty625+ tuple is a valid expression or not.626+ """627+ lineno = self.stream.current.lineno628+ if simplified:629+ parse = self.parse_primary630+ elif with_condexpr:631+ parse = self.parse_expression632+ else:633+634+ def parse():635+ return self.parse_expression(with_condexpr=False)636+637+ args = []638+ is_tuple = False639+ while 1:640+ if args:641+ self.stream.expect("comma")642+ if self.is_tuple_end(extra_end_rules):643+ break644+ args.append(parse())645+ if self.stream.current.type == "comma":646+ is_tuple = True647+ else:648+ break649+ lineno = self.stream.current.lineno650+651+ if not is_tuple:652+ if args:653+ return args[0]654+655+ # if we don't have explicit parentheses, an empty tuple is656+ # not a valid expression. This would mean nothing (literally657+ # nothing) in the spot of an expression would be an empty658+ # tuple.659+ if not explicit_parentheses:660+ self.fail(661+ "Expected an expression, got '%s'"662+ % describe_token(self.stream.current)663+ )664+665+ return nodes.Tuple(args, "load", lineno=lineno)666+667+ def parse_list(self):668+ token = self.stream.expect("lbracket")669+ items = []670+ while self.stream.current.type != "rbracket":671+ if items:672+ self.stream.expect("comma")673+ if self.stream.current.type == "rbracket":674+ break675+ items.append(self.parse_expression())676+ self.stream.expect("rbracket")677+ return nodes.List(items, lineno=token.lineno)678+679+ def parse_dict(self):680+ token = self.stream.expect("lbrace")681+ items = []682+ while self.stream.current.type != "rbrace":683+ if items:684+ self.stream.expect("comma")685+ if self.stream.current.type == "rbrace":686+ break687+ key = self.parse_expression()688+ self.stream.expect("colon")689+ value = self.parse_expression()690+ items.append(nodes.Pair(key, value, lineno=key.lineno))691+ self.stream.expect("rbrace")692+ return nodes.Dict(items, lineno=token.lineno)693+694+ def parse_postfix(self, node):695+ while 1:696+ token_type = self.stream.current.type697+ if token_type == "dot" or token_type == "lbracket":698+ node = self.parse_subscript(node)699+ # calls are valid both after postfix expressions (getattr700+ # and getitem) as well as filters and tests701+ elif token_type == "lparen":702+ node = self.parse_call(node)703+ else:704+ break705+ return node706+707+ def parse_filter_expr(self, node):708+ while 1:709+ token_type = self.stream.current.type710+ if token_type == "pipe":711+ node = self.parse_filter(node)712+ elif token_type == "name" and self.stream.current.value == "is":713+ node = self.parse_test(node)714+ # calls are valid both after postfix expressions (getattr715+ # and getitem) as well as filters and tests716+ elif token_type == "lparen":717+ node = self.parse_call(node)718+ else:719+ break720+ return node721+722+ def parse_subscript(self, node):723+ token = next(self.stream)724+ if token.type == "dot":725+ attr_token = self.stream.current726+ next(self.stream)727+ if attr_token.type == "name":728+ return nodes.Getattr(729+ node, attr_token.value, "load", lineno=token.lineno730+ )731+ elif attr_token.type != "integer":732+ self.fail("expected name or number", attr_token.lineno)733+ arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)734+ return nodes.Getitem(node, arg, "load", lineno=token.lineno)735+ if token.type == "lbracket":736+ args = []737+ while self.stream.current.type != "rbracket":738+ if args:739+ self.stream.expect("comma")740+ args.append(self.parse_subscribed())741+ self.stream.expect("rbracket")742+ if len(args) == 1:743+ arg = args[0]744+ else:745+ arg = nodes.Tuple(args, "load", lineno=token.lineno)746+ return nodes.Getitem(node, arg, "load", lineno=token.lineno)747+ self.fail("expected subscript expression", token.lineno)748+749+ def parse_subscribed(self):750+ lineno = self.stream.current.lineno751+752+ if self.stream.current.type == "colon":753+ next(self.stream)754+ args = [None]755+ else:756+ node = self.parse_expression()757+ if self.stream.current.type != "colon":758+ return node759+ next(self.stream)760+ args = [node]761+762+ if self.stream.current.type == "colon":763+ args.append(None)764+ elif self.stream.current.type not in ("rbracket", "comma"):765+ args.append(self.parse_expression())766+ else:767+ args.append(None)768+769+ if self.stream.current.type == "colon":770+ next(self.stream)771+ if self.stream.current.type not in ("rbracket", "comma"):772+ args.append(self.parse_expression())773+ else:774+ args.append(None)775+ else:776+ args.append(None)777+778+ return nodes.Slice(lineno=lineno, *args)779+780+ def parse_call(self, node):781+ token = self.stream.expect("lparen")782+ args = []783+ kwargs = []784+ dyn_args = dyn_kwargs = None785+ require_comma = False786+787+ def ensure(expr):788+ if not expr:789+ self.fail("invalid syntax for function call expression", token.lineno)790+791+ while self.stream.current.type != "rparen":792+ if require_comma:793+ self.stream.expect("comma")794+ # support for trailing comma795+ if self.stream.current.type == "rparen":796+ break797+ if self.stream.current.type == "mul":798+ ensure(dyn_args is None and dyn_kwargs is None)799+ next(self.stream)800+ dyn_args = self.parse_expression()801+ elif self.stream.current.type == "pow":802+ ensure(dyn_kwargs is None)803+ next(self.stream)804+ dyn_kwargs = self.parse_expression()805+ else:806+ if (807+ self.stream.current.type == "name"808+ and self.stream.look().type == "assign"809+ ):810+ # Parsing a kwarg811+ ensure(dyn_kwargs is None)812+ key = self.stream.current.value813+ self.stream.skip(2)814+ value = self.parse_expression()815+ kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))816+ else:817+ # Parsing an arg818+ ensure(dyn_args is None and dyn_kwargs is None and not kwargs)819+ args.append(self.parse_expression())820+821+ require_comma = True822+ self.stream.expect("rparen")823+824+ if node is None:825+ return args, kwargs, dyn_args, dyn_kwargs826+ return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)827+828+ def parse_filter(self, node, start_inline=False):829+ while self.stream.current.type == "pipe" or start_inline:830+ if not start_inline:831+ next(self.stream)832+ token = self.stream.expect("name")833+ name = token.value834+ while self.stream.current.type == "dot":835+ next(self.stream)836+ name += "." + self.stream.expect("name").value837+ if self.stream.current.type == "lparen":838+ args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)839+ else:840+ args = []841+ kwargs = []842+ dyn_args = dyn_kwargs = None843+ node = nodes.Filter(844+ node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno845+ )846+ start_inline = False847+ return node848+849+ def parse_test(self, node):850+ token = next(self.stream)851+ if self.stream.current.test("name:not"):852+ next(self.stream)853+ negated = True854+ else:855+ negated = False856+ name = self.stream.expect("name").value857+ while self.stream.current.type == "dot":858+ next(self.stream)859+ name += "." + self.stream.expect("name").value860+ dyn_args = dyn_kwargs = None861+ kwargs = []862+ if self.stream.current.type == "lparen":863+ args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)864+ elif self.stream.current.type in (865+ "name",866+ "string",867+ "integer",868+ "float",869+ "lparen",870+ "lbracket",871+ "lbrace",872+ ) and not self.stream.current.test_any("name:else", "name:or", "name:and"):873+ if self.stream.current.test("name:is"):874+ self.fail("You cannot chain multiple tests with is")875+ arg_node = self.parse_primary()876+ arg_node = self.parse_postfix(arg_node)877+ args = [arg_node]878+ else:879+ args = []880+ node = nodes.Test(881+ node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno882+ )883+ if negated:884+ node = nodes.Not(node, lineno=token.lineno)885+ return node886+887+ def subparse(self, end_tokens=None):888+ body = []889+ data_buffer = []890+ add_data = data_buffer.append891+892+ if end_tokens is not None:893+ self._end_token_stack.append(end_tokens)894+895+ def flush_data():896+ if data_buffer:897+ lineno = data_buffer[0].lineno898+ body.append(nodes.Output(data_buffer[:], lineno=lineno))899+ del data_buffer[:]900+901+ try:902+ while self.stream:903+ token = self.stream.current904+ if token.type == "data":905+ if token.value:906+ add_data(nodes.TemplateData(token.value, lineno=token.lineno))907+ next(self.stream)908+ elif token.type == "variable_begin":909+ next(self.stream)910+ add_data(self.parse_tuple(with_condexpr=True))911+ self.stream.expect("variable_end")912+ elif token.type == "block_begin":913+ flush_data()914+ next(self.stream)915+ if end_tokens is not None and self.stream.current.test_any(916+ *end_tokens917+ ):918+ return body919+ rv = self.parse_statement()920+ if isinstance(rv, list):921+ body.extend(rv)922+ else:923+ body.append(rv)924+ self.stream.expect("block_end")925+ else:926+ raise AssertionError("internal parsing error")927+928+ flush_data()929+ finally:930+ if end_tokens is not None:931+ self._end_token_stack.pop()932+933+ return body934+935+ def parse(self):936+ """Parse the whole template into a `Template` node."""937+ result = nodes.Template(self.subparse(), lineno=1)938+ result.set_environment(self.environment)939+ return resultadded:src/jinja/runtime.py+1011 added
1+# -*- coding: utf-8 -*-2+"""The runtime functions and state used by compiled templates."""3+import sys4+from itertools import chain5+from types import MethodType6+7+from markupsafe import escape8+from markupsafe import Markup9+from markupsafe import soft_unicode10+11+from ._compat import abc12+from ._compat import imap13+from ._compat import implements_iterator14+from ._compat import implements_to_string15+from ._compat import iteritems16+from ._compat import PY217+from ._compat import string_types18+from ._compat import text_type19+from ._compat import with_metaclass20+from .exceptions import TemplateNotFound21+from .exceptions import TemplateRuntimeError22+from .exceptions import UndefinedError23+from .nodes import EvalContext24+from .utils import concat25+from .utils import evalcontextfunction26+from .utils import internalcode27+from .utils import missing28+from .utils import Namespace29+from .utils import object_type_repr30+31+# these variables are exported to the template runtime32+__all__ = [33+ "LoopContext",34+ "TemplateReference",35+ "Macro",36+ "Markup",37+ "TemplateRuntimeError",38+ "missing",39+ "concat",40+ "escape",41+ "markup_join",42+ "unicode_join",43+ "to_string",44+ "identity",45+ "TemplateNotFound",46+ "Namespace",47+ "Undefined",48+]49+50+#: the name of the function that is used to convert something into51+#: a string. We can just use the text type here.52+to_string = text_type53+54+55+def identity(x):56+ """Returns its argument. Useful for certain things in the57+ environment.58+ """59+ return x60+61+62+def markup_join(seq):63+ """Concatenation that escapes if necessary and converts to unicode."""64+ buf = []65+ iterator = imap(soft_unicode, seq)66+ for arg in iterator:67+ buf.append(arg)68+ if hasattr(arg, "__html__"):69+ return Markup(u"").join(chain(buf, iterator))70+ return concat(buf)71+72+73+def unicode_join(seq):74+ """Simple args to unicode conversion and concatenation."""75+ return concat(imap(text_type, seq))76+77+78+def new_context(79+ environment,80+ template_name,81+ blocks,82+ vars=None,83+ shared=None,84+ globals=None,85+ locals=None,86+):87+ """Internal helper for context creation."""88+ if vars is None:89+ vars = {}90+ if shared:91+ parent = vars92+ else:93+ parent = dict(globals or (), **vars)94+ if locals:95+ # if the parent is shared a copy should be created because96+ # we don't want to modify the dict passed97+ if shared:98+ parent = dict(parent)99+ for key, value in iteritems(locals):100+ if value is not missing:101+ parent[key] = value102+ return environment.context_class(environment, parent, template_name, blocks)103+104+105+class TemplateReference(object):106+ """The `self` in templates."""107+108+ def __init__(self, context):109+ self.__context = context110+111+ def __getitem__(self, name):112+ blocks = self.__context.blocks[name]113+ return BlockReference(name, self.__context, blocks, 0)114+115+ def __repr__(self):116+ return "<%s %r>" % (self.__class__.__name__, self.__context.name)117+118+119+def _get_func(x):120+ return getattr(x, "__func__", x)121+122+123+class ContextMeta(type):124+ def __new__(mcs, name, bases, d):125+ rv = type.__new__(mcs, name, bases, d)126+ if bases == ():127+ return rv128+129+ resolve = _get_func(rv.resolve)130+ default_resolve = _get_func(Context.resolve)131+ resolve_or_missing = _get_func(rv.resolve_or_missing)132+ default_resolve_or_missing = _get_func(Context.resolve_or_missing)133+134+ # If we have a changed resolve but no changed default or missing135+ # resolve we invert the call logic.136+ if (137+ resolve is not default_resolve138+ and resolve_or_missing is default_resolve_or_missing139+ ):140+ rv._legacy_resolve_mode = True141+ elif (142+ resolve is default_resolve143+ and resolve_or_missing is default_resolve_or_missing144+ ):145+ rv._fast_resolve_mode = True146+147+ return rv148+149+150+def resolve_or_missing(context, key, missing=missing):151+ if key in context.vars:152+ return context.vars[key]153+ if key in context.parent:154+ return context.parent[key]155+ return missing156+157+158+class Context(with_metaclass(ContextMeta)):159+ """The template context holds the variables of a template. It stores the160+ values passed to the template and also the names the template exports.161+ Creating instances is neither supported nor useful as it's created162+ automatically at various stages of the template evaluation and should not163+ be created by hand.164+165+ The context is immutable. Modifications on :attr:`parent` **must not**166+ happen and modifications on :attr:`vars` are allowed from generated167+ template code only. Template filters and global functions marked as168+ :func:`contextfunction`\\s get the active context passed as first argument169+ and are allowed to access the context read-only.170+171+ The template context supports read only dict operations (`get`,172+ `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,173+ `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`174+ method that doesn't fail with a `KeyError` but returns an175+ :class:`Undefined` object for missing variables.176+ """177+178+ # XXX: we want to eventually make this be a deprecation warning and179+ # remove it.180+ _legacy_resolve_mode = False181+ _fast_resolve_mode = False182+183+ def __init__(self, environment, parent, name, blocks):184+ self.parent = parent185+ self.vars = {}186+ self.environment = environment187+ self.eval_ctx = EvalContext(self.environment, name)188+ self.exported_vars = set()189+ self.name = name190+191+ # create the initial mapping of blocks. Whenever template inheritance192+ # takes place the runtime will update this mapping with the new blocks193+ # from the template.194+ self.blocks = dict((k, [v]) for k, v in iteritems(blocks))195+196+ # In case we detect the fast resolve mode we can set up an alias197+ # here that bypasses the legacy code logic.198+ if self._fast_resolve_mode:199+ self.resolve_or_missing = MethodType(resolve_or_missing, self)200+201+ def super(self, name, current):202+ """Render a parent block."""203+ try:204+ blocks = self.blocks[name]205+ index = blocks.index(current) + 1206+ blocks[index]207+ except LookupError:208+ return self.environment.undefined(209+ "there is no parent block called %r." % name, name="super"210+ )211+ return BlockReference(name, self, blocks, index)212+213+ def get(self, key, default=None):214+ """Returns an item from the template context, if it doesn't exist215+ `default` is returned.216+ """217+ try:218+ return self[key]219+ except KeyError:220+ return default221+222+ def resolve(self, key):223+ """Looks up a variable like `__getitem__` or `get` but returns an224+ :class:`Undefined` object with the name of the name looked up.225+ """226+ if self._legacy_resolve_mode:227+ rv = resolve_or_missing(self, key)228+ else:229+ rv = self.resolve_or_missing(key)230+ if rv is missing:231+ return self.environment.undefined(name=key)232+ return rv233+234+ def resolve_or_missing(self, key):235+ """Resolves a variable like :meth:`resolve` but returns the236+ special `missing` value if it cannot be found.237+ """238+ if self._legacy_resolve_mode:239+ rv = self.resolve(key)240+ if isinstance(rv, Undefined):241+ rv = missing242+ return rv243+ return resolve_or_missing(self, key)244+245+ def get_exported(self):246+ """Get a new dict with the exported variables."""247+ return dict((k, self.vars[k]) for k in self.exported_vars)248+249+ def get_all(self):250+ """Return the complete context as dict including the exported251+ variables. For optimizations reasons this might not return an252+ actual copy so be careful with using it.253+ """254+ if not self.vars:255+ return self.parent256+ if not self.parent:257+ return self.vars258+ return dict(self.parent, **self.vars)259+260+ @internalcode261+ def call(__self, __obj, *args, **kwargs): # noqa: B902262+ """Call the callable with the arguments and keyword arguments263+ provided but inject the active context or environment as first264+ argument if the callable is a :func:`contextfunction` or265+ :func:`environmentfunction`.266+ """267+ if __debug__:268+ __traceback_hide__ = True # noqa269+270+ # Allow callable classes to take a context271+ if hasattr(__obj, "__call__"): # noqa: B004272+ fn = __obj.__call__273+ for fn_type in (274+ "contextfunction",275+ "evalcontextfunction",276+ "environmentfunction",277+ ):278+ if hasattr(fn, fn_type):279+ __obj = fn280+ break281+282+ if callable(__obj):283+ if getattr(__obj, "contextfunction", 0):284+ args = (__self,) + args285+ elif getattr(__obj, "evalcontextfunction", 0):286+ args = (__self.eval_ctx,) + args287+ elif getattr(__obj, "environmentfunction", 0):288+ args = (__self.environment,) + args289+ try:290+ return __obj(*args, **kwargs)291+ except StopIteration:292+ return __self.environment.undefined(293+ "value was undefined because "294+ "a callable raised a "295+ "StopIteration exception"296+ )297+298+ def derived(self, locals=None):299+ """Internal helper function to create a derived context. This is300+ used in situations where the system needs a new context in the same301+ template that is independent.302+ """303+ context = new_context(304+ self.environment, self.name, {}, self.get_all(), True, None, locals305+ )306+ context.eval_ctx = self.eval_ctx307+ context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))308+ return context309+310+ def _all(meth): # noqa: B902311+ def proxy(self):312+ return getattr(self.get_all(), meth)()313+314+ proxy.__doc__ = getattr(dict, meth).__doc__315+ proxy.__name__ = meth316+ return proxy317+318+ keys = _all("keys")319+ values = _all("values")320+ items = _all("items")321+322+ # not available on python 3323+ if PY2:324+ iterkeys = _all("iterkeys")325+ itervalues = _all("itervalues")326+ iteritems = _all("iteritems")327+ del _all328+329+ def __contains__(self, name):330+ return name in self.vars or name in self.parent331+332+ def __getitem__(self, key):333+ """Lookup a variable or raise `KeyError` if the variable is334+ undefined.335+ """336+ item = self.resolve_or_missing(key)337+ if item is missing:338+ raise KeyError(key)339+ return item340+341+ def __repr__(self):342+ return "<%s %s of %r>" % (343+ self.__class__.__name__,344+ repr(self.get_all()),345+ self.name,346+ )347+348+349+abc.Mapping.register(Context)350+351+352+class BlockReference(object):353+ """One block on a template reference."""354+355+ def __init__(self, name, context, stack, depth):356+ self.name = name357+ self._context = context358+ self._stack = stack359+ self._depth = depth360+361+ @property362+ def super(self):363+ """Super the block."""364+ if self._depth + 1 >= len(self._stack):365+ return self._context.environment.undefined(366+ "there is no parent block called %r." % self.name, name="super"367+ )368+ return BlockReference(self.name, self._context, self._stack, self._depth + 1)369+370+ @internalcode371+ def __call__(self):372+ rv = concat(self._stack[self._depth](self._context))373+ if self._context.eval_ctx.autoescape:374+ rv = Markup(rv)375+ return rv376+377+378+@implements_iterator379+class LoopContext:380+ """A wrapper iterable for dynamic ``for`` loops, with information381+ about the loop and iteration.382+ """383+384+ #: Current iteration of the loop, starting at 0.385+ index0 = -1386+387+ _length = None388+ _after = missing389+ _current = missing390+ _before = missing391+ _last_changed_value = missing392+393+ def __init__(self, iterable, undefined, recurse=None, depth0=0):394+ """395+ :param iterable: Iterable to wrap.396+ :param undefined: :class:`Undefined` class to use for next and397+ previous items.398+ :param recurse: The function to render the loop body when the399+ loop is marked recursive.400+ :param depth0: Incremented when looping recursively.401+ """402+ self._iterable = iterable403+ self._iterator = self._to_iterator(iterable)404+ self._undefined = undefined405+ self._recurse = recurse406+ #: How many levels deep a recursive loop currently is, starting at 0.407+ self.depth0 = depth0408+409+ @staticmethod410+ def _to_iterator(iterable):411+ return iter(iterable)412+413+ @property414+ def length(self):415+ """Length of the iterable.416+417+ If the iterable is a generator or otherwise does not have a418+ size, it is eagerly evaluated to get a size.419+ """420+ if self._length is not None:421+ return self._length422+423+ try:424+ self._length = len(self._iterable)425+ except TypeError:426+ iterable = list(self._iterator)427+ self._iterator = self._to_iterator(iterable)428+ self._length = len(iterable) + self.index + (self._after is not missing)429+430+ return self._length431+432+ def __len__(self):433+ return self.length434+435+ @property436+ def depth(self):437+ """How many levels deep a recursive loop currently is, starting at 1."""438+ return self.depth0 + 1439+440+ @property441+ def index(self):442+ """Current iteration of the loop, starting at 1."""443+ return self.index0 + 1444+445+ @property446+ def revindex0(self):447+ """Number of iterations from the end of the loop, ending at 0.448+449+ Requires calculating :attr:`length`.450+ """451+ return self.length - self.index452+453+ @property454+ def revindex(self):455+ """Number of iterations from the end of the loop, ending at 1.456+457+ Requires calculating :attr:`length`.458+ """459+ return self.length - self.index0460+461+ @property462+ def first(self):463+ """Whether this is the first iteration of the loop."""464+ return self.index0 == 0465+466+ def _peek_next(self):467+ """Return the next element in the iterable, or :data:`missing`468+ if the iterable is exhausted. Only peeks one item ahead, caching469+ the result in :attr:`_last` for use in subsequent checks. The470+ cache is reset when :meth:`__next__` is called.471+ """472+ if self._after is not missing:473+ return self._after474+475+ self._after = next(self._iterator, missing)476+ return self._after477+478+ @property479+ def last(self):480+ """Whether this is the last iteration of the loop.481+482+ Causes the iterable to advance early. See483+ :func:`itertools.groupby` for issues this can cause.484+ The :func:`groupby` filter avoids that issue.485+ """486+ return self._peek_next() is missing487+488+ @property489+ def previtem(self):490+ """The item in the previous iteration. Undefined during the491+ first iteration.492+ """493+ if self.first:494+ return self._undefined("there is no previous item")495+496+ return self._before497+498+ @property499+ def nextitem(self):500+ """The item in the next iteration. Undefined during the last501+ iteration.502+503+ Causes the iterable to advance early. See504+ :func:`itertools.groupby` for issues this can cause.505+ The :func:`groupby` filter avoids that issue.506+ """507+ rv = self._peek_next()508+509+ if rv is missing:510+ return self._undefined("there is no next item")511+512+ return rv513+514+ def cycle(self, *args):515+ """Return a value from the given args, cycling through based on516+ the current :attr:`index0`.517+518+ :param args: One or more values to cycle through.519+ """520+ if not args:521+ raise TypeError("no items for cycling given")522+523+ return args[self.index0 % len(args)]524+525+ def changed(self, *value):526+ """Return ``True`` if previously called with a different value527+ (including when called for the first time).528+529+ :param value: One or more values to compare to the last call.530+ """531+ if self._last_changed_value != value:532+ self._last_changed_value = value533+ return True534+535+ return False536+537+ def __iter__(self):538+ return self539+540+ def __next__(self):541+ if self._after is not missing:542+ rv = self._after543+ self._after = missing544+ else:545+ rv = next(self._iterator)546+547+ self.index0 += 1548+ self._before = self._current549+ self._current = rv550+ return rv, self551+552+ @internalcode553+ def __call__(self, iterable):554+ """When iterating over nested data, render the body of the loop555+ recursively with the given inner iterable data.556+557+ The loop must have the ``recursive`` marker for this to work.558+ """559+ if self._recurse is None:560+ raise TypeError(561+ "The loop must have the 'recursive' marker to be called recursively."562+ )563+564+ return self._recurse(iterable, self._recurse, depth=self.depth)565+566+ def __repr__(self):567+ return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)568+569+570+class Macro(object):571+ """Wraps a macro function."""572+573+ def __init__(574+ self,575+ environment,576+ func,577+ name,578+ arguments,579+ catch_kwargs,580+ catch_varargs,581+ caller,582+ default_autoescape=None,583+ ):584+ self._environment = environment585+ self._func = func586+ self._argument_count = len(arguments)587+ self.name = name588+ self.arguments = arguments589+ self.catch_kwargs = catch_kwargs590+ self.catch_varargs = catch_varargs591+ self.caller = caller592+ self.explicit_caller = "caller" in arguments593+ if default_autoescape is None:594+ default_autoescape = environment.autoescape595+ self._default_autoescape = default_autoescape596+597+ @internalcode598+ @evalcontextfunction599+ def __call__(self, *args, **kwargs):600+ # This requires a bit of explanation, In the past we used to601+ # decide largely based on compile-time information if a macro is602+ # safe or unsafe. While there was a volatile mode it was largely603+ # unused for deciding on escaping. This turns out to be604+ # problematic for macros because whether a macro is safe depends not605+ # on the escape mode when it was defined, but rather when it was used.606+ #607+ # Because however we export macros from the module system and608+ # there are historic callers that do not pass an eval context (and609+ # will continue to not pass one), we need to perform an instance610+ # check here.611+ #612+ # This is considered safe because an eval context is not a valid613+ # argument to callables otherwise anyway. Worst case here is614+ # that if no eval context is passed we fall back to the compile615+ # time autoescape flag.616+ if args and isinstance(args[0], EvalContext):617+ autoescape = args[0].autoescape618+ args = args[1:]619+ else:620+ autoescape = self._default_autoescape621+622+ # try to consume the positional arguments623+ arguments = list(args[: self._argument_count])624+ off = len(arguments)625+626+ # For information why this is necessary refer to the handling627+ # of caller in the `macro_body` handler in the compiler.628+ found_caller = False629+630+ # if the number of arguments consumed is not the number of631+ # arguments expected we start filling in keyword arguments632+ # and defaults.633+ if off != self._argument_count:634+ for name in self.arguments[len(arguments) :]:635+ try:636+ value = kwargs.pop(name)637+ except KeyError:638+ value = missing639+ if name == "caller":640+ found_caller = True641+ arguments.append(value)642+ else:643+ found_caller = self.explicit_caller644+645+ # it's important that the order of these arguments does not change646+ # if not also changed in the compiler's `function_scoping` method.647+ # the order is caller, keyword arguments, positional arguments!648+ if self.caller and not found_caller:649+ caller = kwargs.pop("caller", None)650+ if caller is None:651+ caller = self._environment.undefined("No caller defined", name="caller")652+ arguments.append(caller)653+654+ if self.catch_kwargs:655+ arguments.append(kwargs)656+ elif kwargs:657+ if "caller" in kwargs:658+ raise TypeError(659+ "macro %r was invoked with two values for "660+ "the special caller argument. This is "661+ "most likely a bug." % self.name662+ )663+ raise TypeError(664+ "macro %r takes no keyword argument %r"665+ % (self.name, next(iter(kwargs)))666+ )667+ if self.catch_varargs:668+ arguments.append(args[self._argument_count :])669+ elif len(args) > self._argument_count:670+ raise TypeError(671+ "macro %r takes not more than %d argument(s)"672+ % (self.name, len(self.arguments))673+ )674+675+ return self._invoke(arguments, autoescape)676+677+ def _invoke(self, arguments, autoescape):678+ """This method is being swapped out by the async implementation."""679+ rv = self._func(*arguments)680+ if autoescape:681+ rv = Markup(rv)682+ return rv683+684+ def __repr__(self):685+ return "<%s %s>" % (686+ self.__class__.__name__,687+ self.name is None and "anonymous" or repr(self.name),688+ )689+690+691+@implements_to_string692+class Undefined(object):693+ """The default undefined type. This undefined type can be printed and694+ iterated over, but every other access will raise an :exc:`UndefinedError`:695+696+ >>> foo = Undefined(name='foo')697+ >>> str(foo)698+ ''699+ >>> not foo700+ True701+ >>> foo + 42702+ Traceback (most recent call last):703+ ...704+ jinja2.exceptions.UndefinedError: 'foo' is undefined705+ """706+707+ __slots__ = (708+ "_undefined_hint",709+ "_undefined_obj",710+ "_undefined_name",711+ "_undefined_exception",712+ )713+714+ def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):715+ self._undefined_hint = hint716+ self._undefined_obj = obj717+ self._undefined_name = name718+ self._undefined_exception = exc719+720+ @property721+ def _undefined_message(self):722+ """Build a message about the undefined value based on how it was723+ accessed.724+ """725+ if self._undefined_hint:726+ return self._undefined_hint727+728+ if self._undefined_obj is missing:729+ return "%r is undefined" % self._undefined_name730+731+ if not isinstance(self._undefined_name, string_types):732+ return "%s has no element %r" % (733+ object_type_repr(self._undefined_obj),734+ self._undefined_name,735+ )736+737+ return "%r has no attribute %r" % (738+ object_type_repr(self._undefined_obj),739+ self._undefined_name,740+ )741+742+ @internalcode743+ def _fail_with_undefined_error(self, *args, **kwargs):744+ """Raise an :exc:`UndefinedError` when operations are performed745+ on the undefined value.746+ """747+ raise self._undefined_exception(self._undefined_message)748+749+ @internalcode750+ def __getattr__(self, name):751+ if name[:2] == "__":752+ raise AttributeError(name)753+ return self._fail_with_undefined_error()754+755+ __add__ = (756+ __radd__757+ ) = (758+ __mul__759+ ) = (760+ __rmul__761+ ) = (762+ __div__763+ ) = (764+ __rdiv__765+ ) = (766+ __truediv__767+ ) = (768+ __rtruediv__769+ ) = (770+ __floordiv__771+ ) = (772+ __rfloordiv__773+ ) = (774+ __mod__775+ ) = (776+ __rmod__777+ ) = (778+ __pos__779+ ) = (780+ __neg__781+ ) = (782+ __call__783+ ) = (784+ __getitem__785+ ) = (786+ __lt__787+ ) = (788+ __le__789+ ) = (790+ __gt__791+ ) = (792+ __ge__793+ ) = (794+ __int__795+ ) = (796+ __float__797+ ) = (798+ __complex__799+ ) = __pow__ = __rpow__ = __sub__ = __rsub__ = _fail_with_undefined_error800+801+ def __eq__(self, other):802+ return type(self) is type(other)803+804+ def __ne__(self, other):805+ return not self.__eq__(other)806+807+ def __hash__(self):808+ return id(type(self))809+810+ def __str__(self):811+ return u""812+813+ def __len__(self):814+ return 0815+816+ def __iter__(self):817+ if 0:818+ yield None819+820+ def __nonzero__(self):821+ return False822+823+ __bool__ = __nonzero__824+825+ def __repr__(self):826+ return "Undefined"827+828+829+def make_logging_undefined(logger=None, base=None):830+ """Given a logger object this returns a new undefined class that will831+ log certain failures. It will log iterations and printing. If no832+ logger is given a default logger is created.833+834+ Example::835+836+ logger = logging.getLogger(__name__)837+ LoggingUndefined = make_logging_undefined(838+ logger=logger,839+ base=Undefined840+ )841+842+ .. versionadded:: 2.8843+844+ :param logger: the logger to use. If not provided, a default logger845+ is created.846+ :param base: the base class to add logging functionality to. This847+ defaults to :class:`Undefined`.848+ """849+ if logger is None:850+ import logging851+852+ logger = logging.getLogger(__name__)853+ logger.addHandler(logging.StreamHandler(sys.stderr))854+ if base is None:855+ base = Undefined856+857+ def _log_message(undef):858+ if undef._undefined_hint is None:859+ if undef._undefined_obj is missing:860+ hint = "%s is undefined" % undef._undefined_name861+ elif not isinstance(undef._undefined_name, string_types):862+ hint = "%s has no element %s" % (863+ object_type_repr(undef._undefined_obj),864+ undef._undefined_name,865+ )866+ else:867+ hint = "%s has no attribute %s" % (868+ object_type_repr(undef._undefined_obj),869+ undef._undefined_name,870+ )871+ else:872+ hint = undef._undefined_hint873+ logger.warning("Template variable warning: %s", hint)874+875+ class LoggingUndefined(base):876+ def _fail_with_undefined_error(self, *args, **kwargs):877+ try:878+ return base._fail_with_undefined_error(self, *args, **kwargs)879+ except self._undefined_exception as e:880+ logger.error("Template variable error: %s", str(e))881+ raise e882+883+ def __str__(self):884+ rv = base.__str__(self)885+ _log_message(self)886+ return rv887+888+ def __iter__(self):889+ rv = base.__iter__(self)890+ _log_message(self)891+ return rv892+893+ if PY2:894+895+ def __nonzero__(self):896+ rv = base.__nonzero__(self)897+ _log_message(self)898+ return rv899+900+ def __unicode__(self):901+ rv = base.__unicode__(self)902+ _log_message(self)903+ return rv904+905+ else:906+907+ def __bool__(self):908+ rv = base.__bool__(self)909+ _log_message(self)910+ return rv911+912+ return LoggingUndefined913+914+915+# No @implements_to_string decorator here because __str__916+# is not overwritten from Undefined in this class.917+# This would cause a recursion error in Python 2.918+class ChainableUndefined(Undefined):919+ """An undefined that is chainable, where both ``__getattr__`` and920+ ``__getitem__`` return itself rather than raising an921+ :exc:`UndefinedError`.922+923+ >>> foo = ChainableUndefined(name='foo')924+ >>> str(foo.bar['baz'])925+ ''926+ >>> foo.bar['baz'] + 42927+ Traceback (most recent call last):928+ ...929+ jinja2.exceptions.UndefinedError: 'foo' is undefined930+931+ .. versionadded:: 2.11.0932+ """933+934+ __slots__ = ()935+936+ def __html__(self):937+ return self.__str__()938+939+ def __getattr__(self, _):940+ return self941+942+ __getitem__ = __getattr__943+944+945+@implements_to_string946+class DebugUndefined(Undefined):947+ """An undefined that returns the debug info when printed.948+949+ >>> foo = DebugUndefined(name='foo')950+ >>> str(foo)951+ '{{ foo }}'952+ >>> not foo953+ True954+ >>> foo + 42955+ Traceback (most recent call last):956+ ...957+ jinja2.exceptions.UndefinedError: 'foo' is undefined958+ """959+960+ __slots__ = ()961+962+ def __str__(self):963+ if self._undefined_hint is None:964+ if self._undefined_obj is missing:965+ return u"{{ %s }}" % self._undefined_name966+ return "{{ no such element: %s[%r] }}" % (967+ object_type_repr(self._undefined_obj),968+ self._undefined_name,969+ )970+ return u"{{ undefined value printed: %s }}" % self._undefined_hint971+972+973+@implements_to_string974+class StrictUndefined(Undefined):975+ """An undefined that barks on print and iteration as well as boolean976+ tests and all kinds of comparisons. In other words: you can do nothing977+ with it except checking if it's defined using the `defined` test.978+979+ >>> foo = StrictUndefined(name='foo')980+ >>> str(foo)981+ Traceback (most recent call last):982+ ...983+ jinja2.exceptions.UndefinedError: 'foo' is undefined984+ >>> not foo985+ Traceback (most recent call last):986+ ...987+ jinja2.exceptions.UndefinedError: 'foo' is undefined988+ >>> foo + 42989+ Traceback (most recent call last):990+ ...991+ jinja2.exceptions.UndefinedError: 'foo' is undefined992+ """993+994+ __slots__ = ()995+ __iter__ = (996+ __str__997+ ) = (998+ __len__999+ ) = (1000+ __nonzero__1001+ ) = __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error1002+1003+1004+# remove remaining slots attributes, after the metaclass did the magic they1005+# are unneeded and irritating as they contain wrong data for the subclasses.1006+del (1007+ Undefined.__slots__,1008+ ChainableUndefined.__slots__,1009+ DebugUndefined.__slots__,1010+ StrictUndefined.__slots__,1011+)added:src/jinja/sandbox.py+510 added
1+# -*- coding: utf-8 -*-2+"""A sandbox layer that ensures unsafe operations cannot be performed.3+Useful when the template itself comes from an untrusted source.4+"""5+import operator6+import types7+import warnings8+from collections import deque9+from string import Formatter10+11+from markupsafe import EscapeFormatter12+13+from ._compat import abc14+from ._compat import PY215+from ._compat import range_type16+from ._compat import string_types17+from .environment import Environment18+from .exceptions import SecurityError19+from .utils import Markup20+21+#: maximum number of items a range may produce22+MAX_RANGE = 10000023+24+#: attributes of function objects that are considered unsafe.25+if PY2:26+ UNSAFE_FUNCTION_ATTRIBUTES = {27+ "func_closure",28+ "func_code",29+ "func_dict",30+ "func_defaults",31+ "func_globals",32+ }33+else:34+ # On versions > python 2 the special attributes on functions are gone,35+ # but they remain on methods and generators for whatever reason.36+ UNSAFE_FUNCTION_ATTRIBUTES = set()37+38+#: unsafe method attributes. function attributes are unsafe for methods too39+UNSAFE_METHOD_ATTRIBUTES = {"im_class", "im_func", "im_self"}40+41+#: unsafe generator attributes.42+UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}43+44+#: unsafe attributes on coroutines45+UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}46+47+#: unsafe attributes on async generators48+UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}49+50+# make sure we don't warn in python 2.6 about stuff we don't care about51+warnings.filterwarnings(52+ "ignore", "the sets module", DeprecationWarning, module=__name__53+)54+55+_mutable_set_types = (set,)56+_mutable_mapping_types = (dict,)57+_mutable_sequence_types = (list,)58+59+# on python 2.x we can register the user collection types60+try:61+ from UserDict import UserDict, DictMixin62+ from UserList import UserList63+64+ _mutable_mapping_types += (UserDict, DictMixin)65+ _mutable_set_types += (UserList,)66+except ImportError:67+ pass68+69+# if sets is still available, register the mutable set from there as well70+try:71+ from sets import Set72+73+ _mutable_set_types += (Set,)74+except ImportError:75+ pass76+77+#: register Python 2.6 abstract base classes78+_mutable_set_types += (abc.MutableSet,)79+_mutable_mapping_types += (abc.MutableMapping,)80+_mutable_sequence_types += (abc.MutableSequence,)81+82+_mutable_spec = (83+ (84+ _mutable_set_types,85+ frozenset(86+ [87+ "add",88+ "clear",89+ "difference_update",90+ "discard",91+ "pop",92+ "remove",93+ "symmetric_difference_update",94+ "update",95+ ]96+ ),97+ ),98+ (99+ _mutable_mapping_types,100+ frozenset(["clear", "pop", "popitem", "setdefault", "update"]),101+ ),102+ (103+ _mutable_sequence_types,104+ frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),105+ ),106+ (107+ deque,108+ frozenset(109+ [110+ "append",111+ "appendleft",112+ "clear",113+ "extend",114+ "extendleft",115+ "pop",116+ "popleft",117+ "remove",118+ "rotate",119+ ]120+ ),121+ ),122+)123+124+125+class _MagicFormatMapping(abc.Mapping):126+ """This class implements a dummy wrapper to fix a bug in the Python127+ standard library for string formatting.128+129+ See https://bugs.python.org/issue13598 for information about why130+ this is necessary.131+ """132+133+ def __init__(self, args, kwargs):134+ self._args = args135+ self._kwargs = kwargs136+ self._last_index = 0137+138+ def __getitem__(self, key):139+ if key == "":140+ idx = self._last_index141+ self._last_index += 1142+ try:143+ return self._args[idx]144+ except LookupError:145+ pass146+ key = str(idx)147+ return self._kwargs[key]148+149+ def __iter__(self):150+ return iter(self._kwargs)151+152+ def __len__(self):153+ return len(self._kwargs)154+155+156+def inspect_format_method(callable):157+ if not isinstance(158+ callable, (types.MethodType, types.BuiltinMethodType)159+ ) or callable.__name__ not in ("format", "format_map"):160+ return None161+ obj = callable.__self__162+ if isinstance(obj, string_types):163+ return obj164+165+166+def safe_range(*args):167+ """A range that can't generate ranges with a length of more than168+ MAX_RANGE items.169+ """170+ rng = range_type(*args)171+172+ if len(rng) > MAX_RANGE:173+ raise OverflowError(174+ "Range too big. The sandbox blocks ranges larger than"175+ " MAX_RANGE (%d)." % MAX_RANGE176+ )177+178+ return rng179+180+181+def unsafe(f):182+ """Marks a function or method as unsafe.183+184+ ::185+186+ @unsafe187+ def delete(self):188+ pass189+ """190+ f.unsafe_callable = True191+ return f192+193+194+def is_internal_attribute(obj, attr):195+ """Test if the attribute given is an internal python attribute. For196+ example this function returns `True` for the `func_code` attribute of197+ python objects. This is useful if the environment method198+ :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.199+200+ >>> from jinja2.sandbox import is_internal_attribute201+ >>> is_internal_attribute(str, "mro")202+ True203+ >>> is_internal_attribute(str, "upper")204+ False205+ """206+ if isinstance(obj, types.FunctionType):207+ if attr in UNSAFE_FUNCTION_ATTRIBUTES:208+ return True209+ elif isinstance(obj, types.MethodType):210+ if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:211+ return True212+ elif isinstance(obj, type):213+ if attr == "mro":214+ return True215+ elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):216+ return True217+ elif isinstance(obj, types.GeneratorType):218+ if attr in UNSAFE_GENERATOR_ATTRIBUTES:219+ return True220+ elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):221+ if attr in UNSAFE_COROUTINE_ATTRIBUTES:222+ return True223+ elif hasattr(types, "AsyncGeneratorType") and isinstance(224+ obj, types.AsyncGeneratorType225+ ):226+ if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:227+ return True228+ return attr.startswith("__")229+230+231+def modifies_known_mutable(obj, attr):232+ """This function checks if an attribute on a builtin mutable object233+ (list, dict, set or deque) would modify it if called. It also supports234+ the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and235+ with Python 2.6 onwards the abstract base classes `MutableSet`,236+ `MutableMapping`, and `MutableSequence`.237+238+ >>> modifies_known_mutable({}, "clear")239+ True240+ >>> modifies_known_mutable({}, "keys")241+ False242+ >>> modifies_known_mutable([], "append")243+ True244+ >>> modifies_known_mutable([], "index")245+ False246+247+ If called with an unsupported object (such as unicode) `False` is248+ returned.249+250+ >>> modifies_known_mutable("foo", "upper")251+ False252+ """253+ for typespec, unsafe in _mutable_spec:254+ if isinstance(obj, typespec):255+ return attr in unsafe256+ return False257+258+259+class SandboxedEnvironment(Environment):260+ """The sandboxed environment. It works like the regular environment but261+ tells the compiler to generate sandboxed code. Additionally subclasses of262+ this environment may override the methods that tell the runtime what263+ attributes or functions are safe to access.264+265+ If the template tries to access insecure code a :exc:`SecurityError` is266+ raised. However also other exceptions may occur during the rendering so267+ the caller has to ensure that all exceptions are caught.268+ """269+270+ sandboxed = True271+272+ #: default callback table for the binary operators. A copy of this is273+ #: available on each instance of a sandboxed environment as274+ #: :attr:`binop_table`275+ default_binop_table = {276+ "+": operator.add,277+ "-": operator.sub,278+ "*": operator.mul,279+ "/": operator.truediv,280+ "//": operator.floordiv,281+ "**": operator.pow,282+ "%": operator.mod,283+ }284+285+ #: default callback table for the unary operators. A copy of this is286+ #: available on each instance of a sandboxed environment as287+ #: :attr:`unop_table`288+ default_unop_table = {"+": operator.pos, "-": operator.neg}289+290+ #: a set of binary operators that should be intercepted. Each operator291+ #: that is added to this set (empty by default) is delegated to the292+ #: :meth:`call_binop` method that will perform the operator. The default293+ #: operator callback is specified by :attr:`binop_table`.294+ #:295+ #: The following binary operators are interceptable:296+ #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``297+ #:298+ #: The default operation form the operator table corresponds to the299+ #: builtin function. Intercepted calls are always slower than the native300+ #: operator call, so make sure only to intercept the ones you are301+ #: interested in.302+ #:303+ #: .. versionadded:: 2.6304+ intercepted_binops = frozenset()305+306+ #: a set of unary operators that should be intercepted. Each operator307+ #: that is added to this set (empty by default) is delegated to the308+ #: :meth:`call_unop` method that will perform the operator. The default309+ #: operator callback is specified by :attr:`unop_table`.310+ #:311+ #: The following unary operators are interceptable: ``+``, ``-``312+ #:313+ #: The default operation form the operator table corresponds to the314+ #: builtin function. Intercepted calls are always slower than the native315+ #: operator call, so make sure only to intercept the ones you are316+ #: interested in.317+ #:318+ #: .. versionadded:: 2.6319+ intercepted_unops = frozenset()320+321+ def intercept_unop(self, operator):322+ """Called during template compilation with the name of a unary323+ operator to check if it should be intercepted at runtime. If this324+ method returns `True`, :meth:`call_unop` is executed for this unary325+ operator. The default implementation of :meth:`call_unop` will use326+ the :attr:`unop_table` dictionary to perform the operator with the327+ same logic as the builtin one.328+329+ The following unary operators are interceptable: ``+`` and ``-``330+331+ Intercepted calls are always slower than the native operator call,332+ so make sure only to intercept the ones you are interested in.333+334+ .. versionadded:: 2.6335+ """336+ return False337+338+ def __init__(self, *args, **kwargs):339+ Environment.__init__(self, *args, **kwargs)340+ self.globals["range"] = safe_range341+ self.binop_table = self.default_binop_table.copy()342+ self.unop_table = self.default_unop_table.copy()343+344+ def is_safe_attribute(self, obj, attr, value):345+ """The sandboxed environment will call this method to check if the346+ attribute of an object is safe to access. Per default all attributes347+ starting with an underscore are considered private as well as the348+ special attributes of internal python objects as returned by the349+ :func:`is_internal_attribute` function.350+ """351+ return not (attr.startswith("_") or is_internal_attribute(obj, attr))352+353+ def is_safe_callable(self, obj):354+ """Check if an object is safely callable. Per default a function is355+ considered safe unless the `unsafe_callable` attribute exists and is356+ True. Override this method to alter the behavior, but this won't357+ affect the `unsafe` decorator from this module.358+ """359+ return not (360+ getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)361+ )362+363+ def call_binop(self, context, operator, left, right):364+ """For intercepted binary operator calls (:meth:`intercepted_binops`)365+ this function is executed instead of the builtin operator. This can366+ be used to fine tune the behavior of certain operators.367+368+ .. versionadded:: 2.6369+ """370+ return self.binop_table[operator](left, right)371+372+ def call_unop(self, context, operator, arg):373+ """For intercepted unary operator calls (:meth:`intercepted_unops`)374+ this function is executed instead of the builtin operator. This can375+ be used to fine tune the behavior of certain operators.376+377+ .. versionadded:: 2.6378+ """379+ return self.unop_table[operator](arg)380+381+ def getitem(self, obj, argument):382+ """Subscribe an object from sandboxed code."""383+ try:384+ return obj[argument]385+ except (TypeError, LookupError):386+ if isinstance(argument, string_types):387+ try:388+ attr = str(argument)389+ except Exception:390+ pass391+ else:392+ try:393+ value = getattr(obj, attr)394+ except AttributeError:395+ pass396+ else:397+ if self.is_safe_attribute(obj, argument, value):398+ return value399+ return self.unsafe_undefined(obj, argument)400+ return self.undefined(obj=obj, name=argument)401+402+ def getattr(self, obj, attribute):403+ """Subscribe an object from sandboxed code and prefer the404+ attribute. The attribute passed *must* be a bytestring.405+ """406+ try:407+ value = getattr(obj, attribute)408+ except AttributeError:409+ try:410+ return obj[attribute]411+ except (TypeError, LookupError):412+ pass413+ else:414+ if self.is_safe_attribute(obj, attribute, value):415+ return value416+ return self.unsafe_undefined(obj, attribute)417+ return self.undefined(obj=obj, name=attribute)418+419+ def unsafe_undefined(self, obj, attribute):420+ """Return an undefined object for unsafe attributes."""421+ return self.undefined(422+ "access to attribute %r of %r "423+ "object is unsafe." % (attribute, obj.__class__.__name__),424+ name=attribute,425+ obj=obj,426+ exc=SecurityError,427+ )428+429+ def format_string(self, s, args, kwargs, format_func=None):430+ """If a format call is detected, then this is routed through this431+ method so that our safety sandbox can be used for it.432+ """433+ if isinstance(s, Markup):434+ formatter = SandboxedEscapeFormatter(self, s.escape)435+ else:436+ formatter = SandboxedFormatter(self)437+438+ if format_func is not None and format_func.__name__ == "format_map":439+ if len(args) != 1 or kwargs:440+ raise TypeError(441+ "format_map() takes exactly one argument %d given"442+ % (len(args) + (kwargs is not None))443+ )444+445+ kwargs = args[0]446+ args = None447+448+ kwargs = _MagicFormatMapping(args, kwargs)449+ rv = formatter.vformat(s, args, kwargs)450+ return type(s)(rv)451+452+ def call(__self, __context, __obj, *args, **kwargs): # noqa: B902453+ """Call an object from sandboxed code."""454+ fmt = inspect_format_method(__obj)455+ if fmt is not None:456+ return __self.format_string(fmt, args, kwargs, __obj)457+458+ # the double prefixes are to avoid double keyword argument459+ # errors when proxying the call.460+ if not __self.is_safe_callable(__obj):461+ raise SecurityError("%r is not safely callable" % (__obj,))462+ return __context.call(__obj, *args, **kwargs)463+464+465+class ImmutableSandboxedEnvironment(SandboxedEnvironment):466+ """Works exactly like the regular `SandboxedEnvironment` but does not467+ permit modifications on the builtin mutable objects `list`, `set`, and468+ `dict` by using the :func:`modifies_known_mutable` function.469+ """470+471+ def is_safe_attribute(self, obj, attr, value):472+ if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):473+ return False474+ return not modifies_known_mutable(obj, attr)475+476+477+# This really is not a public API apparently.478+try:479+ from _string import formatter_field_name_split480+except ImportError:481+482+ def formatter_field_name_split(field_name):483+ return field_name._formatter_field_name_split()484+485+486+class SandboxedFormatterMixin(object):487+ def __init__(self, env):488+ self._env = env489+490+ def get_field(self, field_name, args, kwargs):491+ first, rest = formatter_field_name_split(field_name)492+ obj = self.get_value(first, args, kwargs)493+ for is_attr, i in rest:494+ if is_attr:495+ obj = self._env.getattr(obj, i)496+ else:497+ obj = self._env.getitem(obj, i)498+ return obj, first499+500+501+class SandboxedFormatter(SandboxedFormatterMixin, Formatter):502+ def __init__(self, env):503+ SandboxedFormatterMixin.__init__(self, env)504+ Formatter.__init__(self)505+506+507+class SandboxedEscapeFormatter(SandboxedFormatterMixin, EscapeFormatter):508+ def __init__(self, env, escape):509+ SandboxedFormatterMixin.__init__(self, env)510+ EscapeFormatter.__init__(self, escape)added:src/jinja/tests.py+215 added
1+# -*- coding: utf-8 -*-2+"""Built-in template tests used with the ``is`` operator."""3+import decimal4+import operator5+import re6+7+from ._compat import abc8+from ._compat import integer_types9+from ._compat import string_types10+from ._compat import text_type11+from .runtime import Undefined12+13+number_re = re.compile(r"^-?\d+(\.\d+)?$")14+regex_type = type(number_re)15+test_callable = callable16+17+18+def test_odd(value):19+ """Return true if the variable is odd."""20+ return value % 2 == 121+22+23+def test_even(value):24+ """Return true if the variable is even."""25+ return value % 2 == 026+27+28+def test_divisibleby(value, num):29+ """Check if a variable is divisible by a number."""30+ return value % num == 031+32+33+def test_defined(value):34+ """Return true if the variable is defined:35+36+ .. sourcecode:: jinja37+38+ {% if variable is defined %}39+ value of variable: {{ variable }}40+ {% else %}41+ variable is not defined42+ {% endif %}43+44+ See the :func:`default` filter for a simple way to set undefined45+ variables.46+ """47+ return not isinstance(value, Undefined)48+49+50+def test_undefined(value):51+ """Like :func:`defined` but the other way round."""52+ return isinstance(value, Undefined)53+54+55+def test_none(value):56+ """Return true if the variable is none."""57+ return value is None58+59+60+def test_boolean(value):61+ """Return true if the object is a boolean value.62+63+ .. versionadded:: 2.1164+ """65+ return value is True or value is False66+67+68+def test_false(value):69+ """Return true if the object is False.70+71+ .. versionadded:: 2.1172+ """73+ return value is False74+75+76+def test_true(value):77+ """Return true if the object is True.78+79+ .. versionadded:: 2.1180+ """81+ return value is True82+83+84+# NOTE: The existing 'number' test matches booleans and floats85+def test_integer(value):86+ """Return true if the object is an integer.87+88+ .. versionadded:: 2.1189+ """90+ return isinstance(value, integer_types) and value is not True and value is not False91+92+93+# NOTE: The existing 'number' test matches booleans and integers94+def test_float(value):95+ """Return true if the object is a float.96+97+ .. versionadded:: 2.1198+ """99+ return isinstance(value, float)100+101+102+def test_lower(value):103+ """Return true if the variable is lowercased."""104+ return text_type(value).islower()105+106+107+def test_upper(value):108+ """Return true if the variable is uppercased."""109+ return text_type(value).isupper()110+111+112+def test_string(value):113+ """Return true if the object is a string."""114+ return isinstance(value, string_types)115+116+117+def test_mapping(value):118+ """Return true if the object is a mapping (dict etc.).119+120+ .. versionadded:: 2.6121+ """122+ return isinstance(value, abc.Mapping)123+124+125+def test_number(value):126+ """Return true if the variable is a number."""127+ return isinstance(value, integer_types + (float, complex, decimal.Decimal))128+129+130+def test_sequence(value):131+ """Return true if the variable is a sequence. Sequences are variables132+ that are iterable.133+ """134+ try:135+ len(value)136+ value.__getitem__137+ except Exception:138+ return False139+ return True140+141+142+def test_sameas(value, other):143+ """Check if an object points to the same memory address than another144+ object:145+146+ .. sourcecode:: jinja147+148+ {% if foo.attribute is sameas false %}149+ the foo attribute really is the `False` singleton150+ {% endif %}151+ """152+ return value is other153+154+155+def test_iterable(value):156+ """Check if it's possible to iterate over an object."""157+ try:158+ iter(value)159+ except TypeError:160+ return False161+ return True162+163+164+def test_escaped(value):165+ """Check if the value is escaped."""166+ return hasattr(value, "__html__")167+168+169+def test_in(value, seq):170+ """Check if value is in seq.171+172+ .. versionadded:: 2.10173+ """174+ return value in seq175+176+177+TESTS = {178+ "odd": test_odd,179+ "even": test_even,180+ "divisibleby": test_divisibleby,181+ "defined": test_defined,182+ "undefined": test_undefined,183+ "none": test_none,184+ "boolean": test_boolean,185+ "false": test_false,186+ "true": test_true,187+ "integer": test_integer,188+ "float": test_float,189+ "lower": test_lower,190+ "upper": test_upper,191+ "string": test_string,192+ "mapping": test_mapping,193+ "number": test_number,194+ "sequence": test_sequence,195+ "iterable": test_iterable,196+ "callable": test_callable,197+ "sameas": test_sameas,198+ "escaped": test_escaped,199+ "in": test_in,200+ "==": operator.eq,201+ "eq": operator.eq,202+ "equalto": operator.eq,203+ "!=": operator.ne,204+ "ne": operator.ne,205+ ">": operator.gt,206+ "gt": operator.gt,207+ "greaterthan": operator.gt,208+ "ge": operator.ge,209+ ">=": operator.ge,210+ "<": operator.lt,211+ "lt": operator.lt,212+ "lessthan": operator.lt,213+ "<=": operator.le,214+ "le": operator.le,215+}added:src/jinja/utils.py+727 added
1+# -*- coding: utf-8 -*-2+import json3+import os4+import re5+import warnings6+from collections import deque7+from random import choice8+from random import randrange9+from threading import Lock10+11+from markupsafe import escape12+from markupsafe import Markup13+14+from ._compat import abc15+from ._compat import string_types16+from ._compat import text_type17+from ._compat import url_quote18+19+_word_split_re = re.compile(r"(\s+)")20+_punctuation_re = re.compile(21+ "^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$"22+ % (23+ "|".join(map(re.escape, ("(", "<", "<"))),24+ "|".join(map(re.escape, (".", ",", ")", ">", "\n", ">"))),25+ )26+)27+_simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")28+_striptags_re = re.compile(r"(<!--.*?-->|<[^>]*>)")29+_entity_re = re.compile(r"&([^;]+);")30+_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"31+_digits = "0123456789"32+33+# special singleton representing missing values for the runtime34+missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()35+36+# internal code37+internal_code = set()38+39+concat = u"".join40+41+_slash_escape = "\\/" not in json.dumps("/")42+43+44+def contextfunction(f):45+ """This decorator can be used to mark a function or method context callable.46+ A context callable is passed the active :class:`Context` as first argument when47+ called from the template. This is useful if a function wants to get access48+ to the context or functions provided on the context object. For example49+ a function that returns a sorted list of template variables the current50+ template exports could look like this::51+52+ @contextfunction53+ def get_exported_names(context):54+ return sorted(context.exported_vars)55+ """56+ f.contextfunction = True57+ return f58+59+60+def evalcontextfunction(f):61+ """This decorator can be used to mark a function or method as an eval62+ context callable. This is similar to the :func:`contextfunction`63+ but instead of passing the context, an evaluation context object is64+ passed. For more information about the eval context, see65+ :ref:`eval-context`.66+67+ .. versionadded:: 2.468+ """69+ f.evalcontextfunction = True70+ return f71+72+73+def environmentfunction(f):74+ """This decorator can be used to mark a function or method as environment75+ callable. This decorator works exactly like the :func:`contextfunction`76+ decorator just that the first argument is the active :class:`Environment`77+ and not context.78+ """79+ f.environmentfunction = True80+ return f81+82+83+def internalcode(f):84+ """Marks the function as internally used"""85+ internal_code.add(f.__code__)86+ return f87+88+89+def is_undefined(obj):90+ """Check if the object passed is undefined. This does nothing more than91+ performing an instance check against :class:`Undefined` but looks nicer.92+ This can be used for custom filters or tests that want to react to93+ undefined variables. For example a custom default filter can look like94+ this::95+96+ def default(var, default=''):97+ if is_undefined(var):98+ return default99+ return var100+ """101+ from .runtime import Undefined102+103+ return isinstance(obj, Undefined)104+105+106+def consume(iterable):107+ """Consumes an iterable without doing anything with it."""108+ for _ in iterable:109+ pass110+111+112+def clear_caches():113+ """Jinja keeps internal caches for environments and lexers. These are114+ used so that Jinja doesn't have to recreate environments and lexers all115+ the time. Normally you don't have to care about that but if you are116+ measuring memory consumption you may want to clean the caches.117+ """118+ from .environment import _spontaneous_environments119+ from .lexer import _lexer_cache120+121+ _spontaneous_environments.clear()122+ _lexer_cache.clear()123+124+125+def import_string(import_name, silent=False):126+ """Imports an object based on a string. This is useful if you want to127+ use import paths as endpoints or something similar. An import path can128+ be specified either in dotted notation (``xml.sax.saxutils.escape``)129+ or with a colon as object delimiter (``xml.sax.saxutils:escape``).130+131+ If the `silent` is True the return value will be `None` if the import132+ fails.133+134+ :return: imported object135+ """136+ try:137+ if ":" in import_name:138+ module, obj = import_name.split(":", 1)139+ elif "." in import_name:140+ module, _, obj = import_name.rpartition(".")141+ else:142+ return __import__(import_name)143+ return getattr(__import__(module, None, None, [obj]), obj)144+ except (ImportError, AttributeError):145+ if not silent:146+ raise147+148+149+def open_if_exists(filename, mode="rb"):150+ """Returns a file descriptor for the filename if that file exists,151+ otherwise ``None``.152+ """153+ if not os.path.isfile(filename):154+ return None155+156+ return open(filename, mode)157+158+159+def object_type_repr(obj):160+ """Returns the name of the object's type. For some recognized161+ singletons the name of the object is returned instead. (For162+ example for `None` and `Ellipsis`).163+ """164+ if obj is None:165+ return "None"166+ elif obj is Ellipsis:167+ return "Ellipsis"168+ # __builtin__ in 2.x, builtins in 3.x169+ if obj.__class__.__module__ in ("__builtin__", "builtins"):170+ name = obj.__class__.__name__171+ else:172+ name = obj.__class__.__module__ + "." + obj.__class__.__name__173+ return "%s object" % name174+175+176+def pformat(obj, verbose=False):177+ """Prettyprint an object. Either use the `pretty` library or the178+ builtin `pprint`.179+ """180+ try:181+ from pretty import pretty182+183+ return pretty(obj, verbose=verbose)184+ except ImportError:185+ from pprint import pformat186+187+ return pformat(obj)188+189+190+def urlize(text, trim_url_limit=None, rel=None, target=None):191+ """Converts any URLs in text into clickable links. Works on http://,192+ https:// and www. links. Links can have trailing punctuation (periods,193+ commas, close-parens) and leading punctuation (opening parens) and194+ it'll still do the right thing.195+196+ If trim_url_limit is not None, the URLs in link text will be limited197+ to trim_url_limit characters.198+199+ If nofollow is True, the URLs in link text will get a rel="nofollow"200+ attribute.201+202+ If target is not None, a target attribute will be added to the link.203+ """204+ trim_url = (205+ lambda x, limit=trim_url_limit: limit is not None206+ and (x[:limit] + (len(x) >= limit and "..." or ""))207+ or x208+ )209+ words = _word_split_re.split(text_type(escape(text)))210+ rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ""211+ target_attr = target and ' target="%s"' % escape(target) or ""212+213+ for i, word in enumerate(words):214+ match = _punctuation_re.match(word)215+ if match:216+ lead, middle, trail = match.groups()217+ if middle.startswith("www.") or (218+ "@" not in middle219+ and not middle.startswith("http://")220+ and not middle.startswith("https://")221+ and len(middle) > 0222+ and middle[0] in _letters + _digits223+ and (224+ middle.endswith(".org")225+ or middle.endswith(".net")226+ or middle.endswith(".com")227+ )228+ ):229+ middle = '<a href="http://%s"%s%s>%s</a>' % (230+ middle,231+ rel_attr,232+ target_attr,233+ trim_url(middle),234+ )235+ if middle.startswith("http://") or middle.startswith("https://"):236+ middle = '<a href="%s"%s%s>%s</a>' % (237+ middle,238+ rel_attr,239+ target_attr,240+ trim_url(middle),241+ )242+ if (243+ "@" in middle244+ and not middle.startswith("www.")245+ and ":" not in middle246+ and _simple_email_re.match(middle)247+ ):248+ middle = '<a href="mailto:%s">%s</a>' % (middle, middle)249+ if lead + middle + trail != word:250+ words[i] = lead + middle + trail251+ return u"".join(words)252+253+254+def generate_lorem_ipsum(n=5, html=True, min=20, max=100):255+ """Generate some lorem ipsum for the template."""256+ from .constants import LOREM_IPSUM_WORDS257+258+ words = LOREM_IPSUM_WORDS.split()259+ result = []260+261+ for _ in range(n):262+ next_capitalized = True263+ last_comma = last_fullstop = 0264+ word = None265+ last = None266+ p = []267+268+ # each paragraph contains out of 20 to 100 words.269+ for idx, _ in enumerate(range(randrange(min, max))):270+ while True:271+ word = choice(words)272+ if word != last:273+ last = word274+ break275+ if next_capitalized:276+ word = word.capitalize()277+ next_capitalized = False278+ # add commas279+ if idx - randrange(3, 8) > last_comma:280+ last_comma = idx281+ last_fullstop += 2282+ word += ","283+ # add end of sentences284+ if idx - randrange(10, 20) > last_fullstop:285+ last_comma = last_fullstop = idx286+ word += "."287+ next_capitalized = True288+ p.append(word)289+290+ # ensure that the paragraph ends with a dot.291+ p = u" ".join(p)292+ if p.endswith(","):293+ p = p[:-1] + "."294+ elif not p.endswith("."):295+ p += "."296+ result.append(p)297+298+ if not html:299+ return u"\n\n".join(result)300+ return Markup(u"\n".join(u"<p>%s</p>" % escape(x) for x in result))301+302+303+def unicode_urlencode(obj, charset="utf-8", for_qs=False):304+ """Quote a string for use in a URL using the given charset.305+306+ This function is misnamed, it is a wrapper around307+ :func:`urllib.parse.quote`.308+309+ :param obj: String or bytes to quote. Other types are converted to310+ string then encoded to bytes using the given charset.311+ :param charset: Encode text to bytes using this charset.312+ :param for_qs: Quote "/" and use "+" for spaces.313+ """314+ if not isinstance(obj, string_types):315+ obj = text_type(obj)316+317+ if isinstance(obj, text_type):318+ obj = obj.encode(charset)319+320+ safe = b"" if for_qs else b"/"321+ rv = url_quote(obj, safe)322+323+ if not isinstance(rv, text_type):324+ rv = rv.decode("utf-8")325+326+ if for_qs:327+ rv = rv.replace("%20", "+")328+329+ return rv330+331+332+class LRUCache(object):333+ """A simple LRU Cache implementation."""334+335+ # this is fast for small capacities (something below 1000) but doesn't336+ # scale. But as long as it's only used as storage for templates this337+ # won't do any harm.338+339+ def __init__(self, capacity):340+ self.capacity = capacity341+ self._mapping = {}342+ self._queue = deque()343+ self._postinit()344+345+ def _postinit(self):346+ # alias all queue methods for faster lookup347+ self._popleft = self._queue.popleft348+ self._pop = self._queue.pop349+ self._remove = self._queue.remove350+ self._wlock = Lock()351+ self._append = self._queue.append352+353+ def __getstate__(self):354+ return {355+ "capacity": self.capacity,356+ "_mapping": self._mapping,357+ "_queue": self._queue,358+ }359+360+ def __setstate__(self, d):361+ self.__dict__.update(d)362+ self._postinit()363+364+ def __getnewargs__(self):365+ return (self.capacity,)366+367+ def copy(self):368+ """Return a shallow copy of the instance."""369+ rv = self.__class__(self.capacity)370+ rv._mapping.update(self._mapping)371+ rv._queue.extend(self._queue)372+ return rv373+374+ def get(self, key, default=None):375+ """Return an item from the cache dict or `default`"""376+ try:377+ return self[key]378+ except KeyError:379+ return default380+381+ def setdefault(self, key, default=None):382+ """Set `default` if the key is not in the cache otherwise383+ leave unchanged. Return the value of this key.384+ """385+ try:386+ return self[key]387+ except KeyError:388+ self[key] = default389+ return default390+391+ def clear(self):392+ """Clear the cache."""393+ self._wlock.acquire()394+ try:395+ self._mapping.clear()396+ self._queue.clear()397+ finally:398+ self._wlock.release()399+400+ def __contains__(self, key):401+ """Check if a key exists in this cache."""402+ return key in self._mapping403+404+ def __len__(self):405+ """Return the current size of the cache."""406+ return len(self._mapping)407+408+ def __repr__(self):409+ return "<%s %r>" % (self.__class__.__name__, self._mapping)410+411+ def __getitem__(self, key):412+ """Get an item from the cache. Moves the item up so that it has the413+ highest priority then.414+415+ Raise a `KeyError` if it does not exist.416+ """417+ self._wlock.acquire()418+ try:419+ rv = self._mapping[key]420+ if self._queue[-1] != key:421+ try:422+ self._remove(key)423+ except ValueError:424+ # if something removed the key from the container425+ # when we read, ignore the ValueError that we would426+ # get otherwise.427+ pass428+ self._append(key)429+ return rv430+ finally:431+ self._wlock.release()432+433+ def __setitem__(self, key, value):434+ """Sets the value for an item. Moves the item up so that it435+ has the highest priority then.436+ """437+ self._wlock.acquire()438+ try:439+ if key in self._mapping:440+ self._remove(key)441+ elif len(self._mapping) == self.capacity:442+ del self._mapping[self._popleft()]443+ self._append(key)444+ self._mapping[key] = value445+ finally:446+ self._wlock.release()447+448+ def __delitem__(self, key):449+ """Remove an item from the cache dict.450+ Raise a `KeyError` if it does not exist.451+ """452+ self._wlock.acquire()453+ try:454+ del self._mapping[key]455+ try:456+ self._remove(key)457+ except ValueError:458+ pass459+ finally:460+ self._wlock.release()461+462+ def items(self):463+ """Return a list of items."""464+ result = [(key, self._mapping[key]) for key in list(self._queue)]465+ result.reverse()466+ return result467+468+ def iteritems(self):469+ """Iterate over all items."""470+ warnings.warn(471+ "'iteritems()' will be removed in version 3.0. Use"472+ " 'iter(cache.items())' instead.",473+ DeprecationWarning,474+ stacklevel=2,475+ )476+ return iter(self.items())477+478+ def values(self):479+ """Return a list of all values."""480+ return [x[1] for x in self.items()]481+482+ def itervalue(self):483+ """Iterate over all values."""484+ warnings.warn(485+ "'itervalue()' will be removed in version 3.0. Use"486+ " 'iter(cache.values())' instead.",487+ DeprecationWarning,488+ stacklevel=2,489+ )490+ return iter(self.values())491+492+ def itervalues(self):493+ """Iterate over all values."""494+ warnings.warn(495+ "'itervalues()' will be removed in version 3.0. Use"496+ " 'iter(cache.values())' instead.",497+ DeprecationWarning,498+ stacklevel=2,499+ )500+ return iter(self.values())501+502+ def keys(self):503+ """Return a list of all keys ordered by most recent usage."""504+ return list(self)505+506+ def iterkeys(self):507+ """Iterate over all keys in the cache dict, ordered by508+ the most recent usage.509+ """510+ warnings.warn(511+ "'iterkeys()' will be removed in version 3.0. Use"512+ " 'iter(cache.keys())' instead.",513+ DeprecationWarning,514+ stacklevel=2,515+ )516+ return iter(self)517+518+ def __iter__(self):519+ return reversed(tuple(self._queue))520+521+ def __reversed__(self):522+ """Iterate over the keys in the cache dict, oldest items523+ coming first.524+ """525+ return iter(tuple(self._queue))526+527+ __copy__ = copy528+529+530+abc.MutableMapping.register(LRUCache)531+532+533+def select_autoescape(534+ enabled_extensions=("html", "htm", "xml"),535+ disabled_extensions=(),536+ default_for_string=True,537+ default=False,538+):539+ """Intelligently sets the initial value of autoescaping based on the540+ filename of the template. This is the recommended way to configure541+ autoescaping if you do not want to write a custom function yourself.542+543+ If you want to enable it for all templates created from strings or544+ for all templates with `.html` and `.xml` extensions::545+546+ from jinja2 import Environment, select_autoescape547+ env = Environment(autoescape=select_autoescape(548+ enabled_extensions=('html', 'xml'),549+ default_for_string=True,550+ ))551+552+ Example configuration to turn it on at all times except if the template553+ ends with `.txt`::554+555+ from jinja2 import Environment, select_autoescape556+ env = Environment(autoescape=select_autoescape(557+ disabled_extensions=('txt',),558+ default_for_string=True,559+ default=True,560+ ))561+562+ The `enabled_extensions` is an iterable of all the extensions that563+ autoescaping should be enabled for. Likewise `disabled_extensions` is564+ a list of all templates it should be disabled for. If a template is565+ loaded from a string then the default from `default_for_string` is used.566+ If nothing matches then the initial value of autoescaping is set to the567+ value of `default`.568+569+ For security reasons this function operates case insensitive.570+571+ .. versionadded:: 2.9572+ """573+ enabled_patterns = tuple("." + x.lstrip(".").lower() for x in enabled_extensions)574+ disabled_patterns = tuple("." + x.lstrip(".").lower() for x in disabled_extensions)575+576+ def autoescape(template_name):577+ if template_name is None:578+ return default_for_string579+ template_name = template_name.lower()580+ if template_name.endswith(enabled_patterns):581+ return True582+ if template_name.endswith(disabled_patterns):583+ return False584+ return default585+586+ return autoescape587+588+589+def htmlsafe_json_dumps(obj, dumper=None, **kwargs):590+ """Works exactly like :func:`dumps` but is safe for use in ``<script>``591+ tags. It accepts the same arguments and returns a JSON string. Note that592+ this is available in templates through the ``|tojson`` filter which will593+ also mark the result as safe. Due to how this function escapes certain594+ characters this is safe even if used outside of ``<script>`` tags.595+596+ The following characters are escaped in strings:597+598+ - ``<``599+ - ``>``600+ - ``&``601+ - ``'``602+603+ This makes it safe to embed such strings in any place in HTML with the604+ notable exception of double quoted attributes. In that case single605+ quote your attributes or HTML escape it in addition.606+ """607+ if dumper is None:608+ dumper = json.dumps609+ rv = (610+ dumper(obj, **kwargs)611+ .replace(u"<", u"\\u003c")612+ .replace(u">", u"\\u003e")613+ .replace(u"&", u"\\u0026")614+ .replace(u"'", u"\\u0027")615+ )616+ return Markup(rv)617+618+619+class Cycler(object):620+ """Cycle through values by yield them one at a time, then restarting621+ once the end is reached. Available as ``cycler`` in templates.622+623+ Similar to ``loop.cycle``, but can be used outside loops or across624+ multiple loops. For example, render a list of folders and files in a625+ list, alternating giving them "odd" and "even" classes.626+627+ .. code-block:: html+jinja628+629+ {% set row_class = cycler("odd", "even") %}630+ <ul class="browser">631+ {% for folder in folders %}632+ <li class="folder {{ row_class.next() }}">{{ folder }}633+ {% endfor %}634+ {% for file in files %}635+ <li class="file {{ row_class.next() }}">{{ file }}636+ {% endfor %}637+ </ul>638+639+ :param items: Each positional argument will be yielded in the order640+ given for each cycle.641+642+ .. versionadded:: 2.1643+ """644+645+ def __init__(self, *items):646+ if not items:647+ raise RuntimeError("at least one item has to be provided")648+ self.items = items649+ self.pos = 0650+651+ def reset(self):652+ """Resets the current item to the first item."""653+ self.pos = 0654+655+ @property656+ def current(self):657+ """Return the current item. Equivalent to the item that will be658+ returned next time :meth:`next` is called.659+ """660+ return self.items[self.pos]661+662+ def next(self):663+ """Return the current item, then advance :attr:`current` to the664+ next item.665+ """666+ rv = self.current667+ self.pos = (self.pos + 1) % len(self.items)668+ return rv669+670+ __next__ = next671+672+673+class Joiner(object):674+ """A joining helper for templates."""675+676+ def __init__(self, sep=u", "):677+ self.sep = sep678+ self.used = False679+680+ def __call__(self):681+ if not self.used:682+ self.used = True683+ return u""684+ return self.sep685+686+687+class Namespace(object):688+ """A namespace object that can hold arbitrary attributes. It may be689+ initialized from a dictionary or with keyword arguments."""690+691+ def __init__(*args, **kwargs): # noqa: B902692+ self, args = args[0], args[1:]693+ self.__attrs = dict(*args, **kwargs)694+695+ def __getattribute__(self, name):696+ if name == "_Namespace__attrs":697+ return object.__getattribute__(self, name)698+ try:699+ return self.__attrs[name]700+ except KeyError:701+ raise AttributeError(name)702+703+ def __setitem__(self, name, value):704+ self.__attrs[name] = value705+706+ def __repr__(self):707+ return "<Namespace %r>" % self.__attrs708+709+710+# does this python version support async for in and async generators?711+try:712+ exec("async def _():\n async for _ in ():\n yield _")713+ have_async_gen = True714+except SyntaxError:715+ have_async_gen = False716+717+718+def soft_unicode(s):719+ from markupsafe import soft_unicode720+721+ warnings.warn(722+ "'jinja2.utils.soft_unicode' will be removed in version 3.0."723+ " Use 'markupsafe.soft_unicode' instead.",724+ DeprecationWarning,725+ stacklevel=2,726+ )727+ return soft_unicode(s)added:src/jinja/visitor.py+81 added
1+# -*- coding: utf-8 -*-2+"""API for traversing the AST nodes. Implemented by the compiler and3+meta introspection.4+"""5+from .nodes import Node6+7+8+class NodeVisitor(object):9+ """Walks the abstract syntax tree and call visitor functions for every10+ node found. The visitor functions may return values which will be11+ forwarded by the `visit` method.12+13+ Per default the visitor functions for the nodes are ``'visit_'`` +14+ class name of the node. So a `TryFinally` node visit function would15+ be `visit_TryFinally`. This behavior can be changed by overriding16+ the `get_visitor` function. If no visitor function exists for a node17+ (return value `None`) the `generic_visit` visitor is used instead.18+ """19+20+ def get_visitor(self, node):21+ """Return the visitor function for this node or `None` if no visitor22+ exists for this node. In that case the generic visit function is23+ used instead.24+ """25+ method = "visit_" + node.__class__.__name__26+ return getattr(self, method, None)27+28+ def visit(self, node, *args, **kwargs):29+ """Visit a node."""30+ f = self.get_visitor(node)31+ if f is not None:32+ return f(node, *args, **kwargs)33+ return self.generic_visit(node, *args, **kwargs)34+35+ def generic_visit(self, node, *args, **kwargs):36+ """Called if no explicit visitor function exists for a node."""37+ for node in node.iter_child_nodes():38+ self.visit(node, *args, **kwargs)39+40+41+class NodeTransformer(NodeVisitor):42+ """Walks the abstract syntax tree and allows modifications of nodes.43+44+ The `NodeTransformer` will walk the AST and use the return value of the45+ visitor functions to replace or remove the old node. If the return46+ value of the visitor function is `None` the node will be removed47+ from the previous location otherwise it's replaced with the return48+ value. The return value may be the original node in which case no49+ replacement takes place.50+ """51+52+ def generic_visit(self, node, *args, **kwargs):53+ for field, old_value in node.iter_fields():54+ if isinstance(old_value, list):55+ new_values = []56+ for value in old_value:57+ if isinstance(value, Node):58+ value = self.visit(value, *args, **kwargs)59+ if value is None:60+ continue61+ elif not isinstance(value, Node):62+ new_values.extend(value)63+ continue64+ new_values.append(value)65+ old_value[:] = new_values66+ elif isinstance(old_value, Node):67+ new_node = self.visit(old_value, *args, **kwargs)68+ if new_node is None:69+ delattr(node, field)70+ else:71+ setattr(node, field, new_node)72+ return node73+74+ def visit_list(self, node, *args, **kwargs):75+ """As transformers may return lists in some places this method76+ can be used to enforce a list as return value.77+ """78+ rv = self.visit(node, *args, **kwargs)79+ if not isinstance(rv, list):80+ rv = [rv]81+ return rvdeleted:src/jinja2/__init__.py-43 removed
1-# -*- coding: utf-8 -*-2-"""Jinja is a template engine written in pure Python. It provides a3-non-XML syntax that supports inline expressions and an optional4-sandboxed environment.5-"""6-from .bccache import BytecodeCache7-from .bccache import FileSystemBytecodeCache8-from .bccache import MemcachedBytecodeCache9-from .environment import Environment10-from .environment import Template11-from .exceptions import TemplateAssertionError12-from .exceptions import TemplateError13-from .exceptions import TemplateNotFound14-from .exceptions import TemplateRuntimeError15-from .exceptions import TemplatesNotFound16-from .exceptions import TemplateSyntaxError17-from .exceptions import UndefinedError18-from .filters import contextfilter19-from .filters import environmentfilter20-from .filters import evalcontextfilter21-from .loaders import BaseLoader22-from .loaders import ChoiceLoader23-from .loaders import DictLoader24-from .loaders import FileSystemLoader25-from .loaders import FunctionLoader26-from .loaders import ModuleLoader27-from .loaders import PackageLoader28-from .loaders import PrefixLoader29-from .runtime import ChainableUndefined30-from .runtime import DebugUndefined31-from .runtime import make_logging_undefined32-from .runtime import StrictUndefined33-from .runtime import Undefined34-from .utils import clear_caches35-from .utils import contextfunction36-from .utils import environmentfunction37-from .utils import escape38-from .utils import evalcontextfunction39-from .utils import is_undefined40-from .utils import Markup41-from .utils import select_autoescape42-43-__version__ = "2.11.0.dev0"deleted:src/jinja2/_compat.py-132 removed
1-# -*- coding: utf-8 -*-2-# flake8: noqa3-import marshal4-import sys5-6-PY2 = sys.version_info[0] == 27-PYPY = hasattr(sys, "pypy_translation_info")8-_identity = lambda x: x9-10-if not PY2:11- unichr = chr12- range_type = range13- text_type = str14- string_types = (str,)15- integer_types = (int,)16-17- iterkeys = lambda d: iter(d.keys())18- itervalues = lambda d: iter(d.values())19- iteritems = lambda d: iter(d.items())20-21- import pickle22- from io import BytesIO, StringIO23-24- NativeStringIO = StringIO25-26- def reraise(tp, value, tb=None):27- if value.__traceback__ is not tb:28- raise value.with_traceback(tb)29- raise value30-31- ifilter = filter32- imap = map33- izip = zip34- intern = sys.intern35-36- implements_iterator = _identity37- implements_to_string = _identity38- encode_filename = _identity39-40- marshal_dump = marshal.dump41- marshal_load = marshal.load42-43-else:44- unichr = unichr45- text_type = unicode46- range_type = xrange47- string_types = (str, unicode)48- integer_types = (int, long)49-50- iterkeys = lambda d: d.iterkeys()51- itervalues = lambda d: d.itervalues()52- iteritems = lambda d: d.iteritems()53-54- import cPickle as pickle55- from cStringIO import StringIO as BytesIO, StringIO56-57- NativeStringIO = BytesIO58-59- exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")60-61- from itertools import imap, izip, ifilter62-63- intern = intern64-65- def implements_iterator(cls):66- cls.next = cls.__next__67- del cls.__next__68- return cls69-70- def implements_to_string(cls):71- cls.__unicode__ = cls.__str__72- cls.__str__ = lambda x: x.__unicode__().encode("utf-8")73- return cls74-75- def encode_filename(filename):76- if isinstance(filename, unicode):77- return filename.encode("utf-8")78- return filename79-80- def marshal_dump(code, f):81- if isinstance(f, file):82- marshal.dump(code, f)83- else:84- f.write(marshal.dumps(code))85-86- def marshal_load(f):87- if isinstance(f, file):88- return marshal.load(f)89- return marshal.loads(f.read())90-91-92-def with_metaclass(meta, *bases):93- """Create a base class with a metaclass."""94- # This requires a bit of explanation: the basic idea is to make a95- # dummy metaclass for one level of class instantiation that replaces96- # itself with the actual metaclass.97- class metaclass(type):98- def __new__(cls, name, this_bases, d):99- return meta(name, bases, d)100-101- return type.__new__(metaclass, "temporary_class", (), {})102-103-104-try:105- from urllib.parse import quote_from_bytes as url_quote106-except ImportError:107- from urllib import quote as url_quote108-109-110-try:111- from collections import abc112-except ImportError:113- import collections as abc114-115-116-try:117- from os import fspath118-except ImportError:119- try:120- from pathlib import PurePath121- except ImportError:122- PurePath = None123-124- def fspath(path):125- if hasattr(path, "__fspath__"):126- return path.__fspath__()127-128- # Python 3.5 doesn't have __fspath__ yet, use str.129- if PurePath is not None and isinstance(path, PurePath):130- return str(path)131-132- return pathdeleted:src/jinja2/_identifier.py-6 removed
1-import re2-3-# generated by scripts/generate_identifier_pattern.py4-pattern = re.compile(5- r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఃా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑅳𑄴𑆀-𑆂𑆳-𑇊𑇀-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B9506-)deleted:src/jinja2/asyncfilters.py-159 removed
1-from functools import wraps2-3-from . import filters4-from .asyncsupport import auto_aiter5-from .asyncsupport import auto_await6-7-8-async def auto_to_seq(value):9- seq = []10- if hasattr(value, "__aiter__"):11- async for item in value:12- seq.append(item)13- else:14- for item in value:15- seq.append(item)16- return seq17-18-19-async def async_select_or_reject(args, kwargs, modfunc, lookup_attr):20- seq, func = filters.prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)21- if seq:22- async for item in auto_aiter(seq):23- if func(item):24- yield item25-26-27-def dualfilter(normal_filter, async_filter):28- wrap_evalctx = False29- if getattr(normal_filter, "environmentfilter", False):30-31- def is_async(args):32- return args[0].is_async33-34- wrap_evalctx = False35- else:36- if not getattr(normal_filter, "evalcontextfilter", False) and not getattr(37- normal_filter, "contextfilter", False38- ):39- wrap_evalctx = True40-41- def is_async(args):42- return args[0].environment.is_async43-44- @wraps(normal_filter)45- def wrapper(*args, **kwargs):46- b = is_async(args)47- if wrap_evalctx:48- args = args[1:]49- if b:50- return async_filter(*args, **kwargs)51- return normal_filter(*args, **kwargs)52-53- if wrap_evalctx:54- wrapper.evalcontextfilter = True55-56- wrapper.asyncfiltervariant = True57-58- return wrapper59-60-61-def asyncfiltervariant(original):62- def decorator(f):63- return dualfilter(original, f)64-65- return decorator66-67-68-@asyncfiltervariant(filters.do_first)69-async def do_first(environment, seq):70- try:71- return await auto_aiter(seq).__anext__()72- except StopAsyncIteration:73- return environment.undefined("No first item, sequence was empty.")74-75-76-@asyncfiltervariant(filters.do_groupby)77-async def do_groupby(environment, value, attribute):78- expr = filters.make_attrgetter(environment, attribute)79- return [80- filters._GroupTuple(key, await auto_to_seq(values))81- for key, values in filters.groupby(82- sorted(await auto_to_seq(value), key=expr), expr83- )84- ]85-86-87-@asyncfiltervariant(filters.do_join)88-async def do_join(eval_ctx, value, d=u"", attribute=None):89- return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)90-91-92-@asyncfiltervariant(filters.do_list)93-async def do_list(value):94- return await auto_to_seq(value)95-96-97-@asyncfiltervariant(filters.do_reject)98-async def do_reject(*args, **kwargs):99- return async_select_or_reject(args, kwargs, lambda x: not x, False)100-101-102-@asyncfiltervariant(filters.do_rejectattr)103-async def do_rejectattr(*args, **kwargs):104- return async_select_or_reject(args, kwargs, lambda x: not x, True)105-106-107-@asyncfiltervariant(filters.do_select)108-async def do_select(*args, **kwargs):109- return async_select_or_reject(args, kwargs, lambda x: x, False)110-111-112-@asyncfiltervariant(filters.do_selectattr)113-async def do_selectattr(*args, **kwargs):114- return async_select_or_reject(args, kwargs, lambda x: x, True)115-116-117-@asyncfiltervariant(filters.do_map)118-async def do_map(*args, **kwargs):119- seq, func = filters.prepare_map(args, kwargs)120- if seq:121- async for item in auto_aiter(seq):122- yield await auto_await(func(item))123-124-125-@asyncfiltervariant(filters.do_sum)126-async def do_sum(environment, iterable, attribute=None, start=0):127- rv = start128- if attribute is not None:129- func = filters.make_attrgetter(environment, attribute)130- else:131-132- def func(x):133- return x134-135- async for item in auto_aiter(iterable):136- rv += func(item)137- return rv138-139-140-@asyncfiltervariant(filters.do_slice)141-async def do_slice(value, slices, fill_with=None):142- return filters.do_slice(await auto_to_seq(value), slices, fill_with)143-144-145-ASYNC_FILTERS = {146- "first": do_first,147- "groupby": do_groupby,148- "join": do_join,149- "list": do_list,150- # we intentionally do not support do_last because that would be151- # ridiculous152- "reject": do_reject,153- "rejectattr": do_rejectattr,154- "map": do_map,155- "select": do_select,156- "selectattr": do_selectattr,157- "sum": do_sum,158- "slice": do_slice,159-}deleted:src/jinja2/asyncsupport.py-263 removed
1-# -*- coding: utf-8 -*-2-"""The code for async support. Importing this patches Jinja on supported3-Python versions.4-"""5-import asyncio6-import inspect7-from functools import update_wrapper8-9-from .environment import TemplateModule10-from .runtime import LoopContext11-from .utils import concat12-from .utils import internalcode13-from .utils import Markup14-from .utils import missing15-16-17-async def concat_async(async_gen):18- rv = []19-20- async def collect():21- async for event in async_gen:22- rv.append(event)23-24- await collect()25- return concat(rv)26-27-28-async def generate_async(self, *args, **kwargs):29- vars = dict(*args, **kwargs)30- try:31- async for event in self.root_render_func(self.new_context(vars)):32- yield event33- except Exception:34- yield self.environment.handle_exception()35-36-37-def wrap_generate_func(original_generate):38- def _convert_generator(self, loop, args, kwargs):39- async_gen = self.generate_async(*args, **kwargs)40- try:41- while 1:42- yield loop.run_until_complete(async_gen.__anext__())43- except StopAsyncIteration:44- pass45-46- def generate(self, *args, **kwargs):47- if not self.environment.is_async:48- return original_generate(self, *args, **kwargs)49- return _convert_generator(self, asyncio.get_event_loop(), args, kwargs)50-51- return update_wrapper(generate, original_generate)52-53-54-async def render_async(self, *args, **kwargs):55- if not self.environment.is_async:56- raise RuntimeError("The environment was not created with async mode enabled.")57-58- vars = dict(*args, **kwargs)59- ctx = self.new_context(vars)60-61- try:62- return await concat_async(self.root_render_func(ctx))63- except Exception:64- return self.environment.handle_exception()65-66-67-def wrap_render_func(original_render):68- def render(self, *args, **kwargs):69- if not self.environment.is_async:70- return original_render(self, *args, **kwargs)71- loop = asyncio.get_event_loop()72- return loop.run_until_complete(self.render_async(*args, **kwargs))73-74- return update_wrapper(render, original_render)75-76-77-def wrap_block_reference_call(original_call):78- @internalcode79- async def async_call(self):80- rv = await concat_async(self._stack[self._depth](self._context))81- if self._context.eval_ctx.autoescape:82- rv = Markup(rv)83- return rv84-85- @internalcode86- def __call__(self):87- if not self._context.environment.is_async:88- return original_call(self)89- return async_call(self)90-91- return update_wrapper(__call__, original_call)92-93-94-def wrap_macro_invoke(original_invoke):95- @internalcode96- async def async_invoke(self, arguments, autoescape):97- rv = await self._func(*arguments)98- if autoescape:99- rv = Markup(rv)100- return rv101-102- @internalcode103- def _invoke(self, arguments, autoescape):104- if not self._environment.is_async:105- return original_invoke(self, arguments, autoescape)106- return async_invoke(self, arguments, autoescape)107-108- return update_wrapper(_invoke, original_invoke)109-110-111-@internalcode112-async def get_default_module_async(self):113- if self._module is not None:114- return self._module115- self._module = rv = await self.make_module_async()116- return rv117-118-119-def wrap_default_module(original_default_module):120- @internalcode121- def _get_default_module(self):122- if self.environment.is_async:123- raise RuntimeError("Template module attribute is unavailable in async mode")124- return original_default_module(self)125-126- return _get_default_module127-128-129-async def make_module_async(self, vars=None, shared=False, locals=None):130- context = self.new_context(vars, shared, locals)131- body_stream = []132- async for item in self.root_render_func(context):133- body_stream.append(item)134- return TemplateModule(self, context, body_stream)135-136-137-def patch_template():138- from . import Template139-140- Template.generate = wrap_generate_func(Template.generate)141- Template.generate_async = update_wrapper(generate_async, Template.generate_async)142- Template.render_async = update_wrapper(render_async, Template.render_async)143- Template.render = wrap_render_func(Template.render)144- Template._get_default_module = wrap_default_module(Template._get_default_module)145- Template._get_default_module_async = get_default_module_async146- Template.make_module_async = update_wrapper(147- make_module_async, Template.make_module_async148- )149-150-151-def patch_runtime():152- from .runtime import BlockReference, Macro153-154- BlockReference.__call__ = wrap_block_reference_call(BlockReference.__call__)155- Macro._invoke = wrap_macro_invoke(Macro._invoke)156-157-158-def patch_filters():159- from .filters import FILTERS160- from .asyncfilters import ASYNC_FILTERS161-162- FILTERS.update(ASYNC_FILTERS)163-164-165-def patch_all():166- patch_template()167- patch_runtime()168- patch_filters()169-170-171-async def auto_await(value):172- if inspect.isawaitable(value):173- return await value174- return value175-176-177-async def auto_aiter(iterable):178- if hasattr(iterable, "__aiter__"):179- async for item in iterable:180- yield item181- return182- for item in iterable:183- yield item184-185-186-class AsyncLoopContext(LoopContext):187- _to_iterator = staticmethod(auto_aiter)188-189- @property190- async def length(self):191- if self._length is not None:192- return self._length193-194- try:195- self._length = len(self._iterable)196- except TypeError:197- iterable = [x async for x in self._iterator]198- self._iterator = self._to_iterator(iterable)199- self._length = len(iterable) + self.index + (self._after is not missing)200-201- return self._length202-203- @property204- async def revindex0(self):205- return await self.length - self.index206-207- @property208- async def revindex(self):209- return await self.length - self.index0210-211- async def _peek_next(self):212- if self._after is not missing:213- return self._after214-215- try:216- self._after = await self._iterator.__anext__()217- except StopAsyncIteration:218- self._after = missing219-220- return self._after221-222- @property223- async def last(self):224- return await self._peek_next() is missing225-226- @property227- async def nextitem(self):228- rv = await self._peek_next()229-230- if rv is missing:231- return self._undefined("there is no next item")232-233- return rv234-235- def __aiter__(self):236- return self237-238- async def __anext__(self):239- if self._after is not missing:240- rv = self._after241- self._after = missing242- else:243- rv = await self._iterator.__anext__()244-245- self.index0 += 1246- self._before = self._current247- self._current = rv248- return rv, self249-250-251-async def make_async_loop_context(iterable, undefined, recurse=None, depth0=0):252- import warnings253-254- warnings.warn(255- "This template must be recompiled with at least Jinja 2.11, or"256- " it will fail in 3.0.",257- DeprecationWarning,258- stacklevel=2,259- )260- return AsyncLoopContext(iterable, undefined, recurse, depth0)261-262-263-patch_all()deleted:src/jinja2/bccache.py-353 removed
1-# -*- coding: utf-8 -*-2-"""The optional bytecode cache system. This is useful if you have very3-complex template situations and the compilation of all those templates4-slows down your application too much.5-6-Situations where this is useful are often forking web applications that7-are initialized on the first request.8-"""9-import errno10-import fnmatch11-import os12-import stat13-import sys14-import tempfile15-from hashlib import sha116-from os import listdir17-from os import path18-19-from ._compat import BytesIO20-from ._compat import marshal_dump21-from ._compat import marshal_load22-from ._compat import pickle23-from ._compat import text_type24-from .utils import open_if_exists25-26-bc_version = 327-28-# magic version used to only change with new jinja versions. With 2.629-# we change this to also take Python version changes into account. The30-# reason for this is that Python tends to segfault if fed earlier bytecode31-# versions because someone thought it would be a good idea to reuse opcodes32-# or make Python incompatible with earlier versions.33-bc_magic = (34- "j2".encode("ascii")35- + pickle.dumps(bc_version, 2)36- + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1])37-)38-39-40-class Bucket(object):41- """Buckets are used to store the bytecode for one template. It's created42- and initialized by the bytecode cache and passed to the loading functions.43-44- The buckets get an internal checksum from the cache assigned and use this45- to automatically reject outdated cache material. Individual bytecode46- cache subclasses don't have to care about cache invalidation.47- """48-49- def __init__(self, environment, key, checksum):50- self.environment = environment51- self.key = key52- self.checksum = checksum53- self.reset()54-55- def reset(self):56- """Resets the bucket (unloads the bytecode)."""57- self.code = None58-59- def load_bytecode(self, f):60- """Loads bytecode from a file or file like object."""61- # make sure the magic header is correct62- magic = f.read(len(bc_magic))63- if magic != bc_magic:64- self.reset()65- return66- # the source code of the file changed, we need to reload67- checksum = pickle.load(f)68- if self.checksum != checksum:69- self.reset()70- return71- # if marshal_load fails then we need to reload72- try:73- self.code = marshal_load(f)74- except (EOFError, ValueError, TypeError):75- self.reset()76- return77-78- def write_bytecode(self, f):79- """Dump the bytecode into the file or file like object passed."""80- if self.code is None:81- raise TypeError("can't write empty bucket")82- f.write(bc_magic)83- pickle.dump(self.checksum, f, 2)84- marshal_dump(self.code, f)85-86- def bytecode_from_string(self, string):87- """Load bytecode from a string."""88- self.load_bytecode(BytesIO(string))89-90- def bytecode_to_string(self):91- """Return the bytecode as string."""92- out = BytesIO()93- self.write_bytecode(out)94- return out.getvalue()95-96-97-class BytecodeCache(object):98- """To implement your own bytecode cache you have to subclass this class99- and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of100- these methods are passed a :class:`~jinja2.bccache.Bucket`.101-102- A very basic bytecode cache that saves the bytecode on the file system::103-104- from os import path105-106- class MyCache(BytecodeCache):107-108- def __init__(self, directory):109- self.directory = directory110-111- def load_bytecode(self, bucket):112- filename = path.join(self.directory, bucket.key)113- if path.exists(filename):114- with open(filename, 'rb') as f:115- bucket.load_bytecode(f)116-117- def dump_bytecode(self, bucket):118- filename = path.join(self.directory, bucket.key)119- with open(filename, 'wb') as f:120- bucket.write_bytecode(f)121-122- A more advanced version of a filesystem based bytecode cache is part of123- Jinja.124- """125-126- def load_bytecode(self, bucket):127- """Subclasses have to override this method to load bytecode into a128- bucket. If they are not able to find code in the cache for the129- bucket, it must not do anything.130- """131- raise NotImplementedError()132-133- def dump_bytecode(self, bucket):134- """Subclasses have to override this method to write the bytecode135- from a bucket back to the cache. If it unable to do so it must not136- fail silently but raise an exception.137- """138- raise NotImplementedError()139-140- def clear(self):141- """Clears the cache. This method is not used by Jinja but should be142- implemented to allow applications to clear the bytecode cache used143- by a particular environment.144- """145-146- def get_cache_key(self, name, filename=None):147- """Returns the unique hash key for this template name."""148- hash = sha1(name.encode("utf-8"))149- if filename is not None:150- filename = "|" + filename151- if isinstance(filename, text_type):152- filename = filename.encode("utf-8")153- hash.update(filename)154- return hash.hexdigest()155-156- def get_source_checksum(self, source):157- """Returns a checksum for the source."""158- return sha1(source.encode("utf-8")).hexdigest()159-160- def get_bucket(self, environment, name, filename, source):161- """Return a cache bucket for the given template. All arguments are162- mandatory but filename may be `None`.163- """164- key = self.get_cache_key(name, filename)165- checksum = self.get_source_checksum(source)166- bucket = Bucket(environment, key, checksum)167- self.load_bytecode(bucket)168- return bucket169-170- def set_bucket(self, bucket):171- """Put the bucket into the cache."""172- self.dump_bytecode(bucket)173-174-175-class FileSystemBytecodeCache(BytecodeCache):176- """A bytecode cache that stores bytecode on the filesystem. It accepts177- two arguments: The directory where the cache items are stored and a178- pattern string that is used to build the filename.179-180- If no directory is specified a default cache directory is selected. On181- Windows the user's temp directory is used, on UNIX systems a directory182- is created for the user in the system temp directory.183-184- The pattern can be used to have multiple separate caches operate on the185- same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``186- is replaced with the cache key.187-188- >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')189-190- This bytecode cache supports clearing of the cache using the clear method.191- """192-193- def __init__(self, directory=None, pattern="__jinja2_%s.cache"):194- if directory is None:195- directory = self._get_default_cache_dir()196- self.directory = directory197- self.pattern = pattern198-199- def _get_default_cache_dir(self):200- def _unsafe_dir():201- raise RuntimeError(202- "Cannot determine safe temp directory. You "203- "need to explicitly provide one."204- )205-206- tmpdir = tempfile.gettempdir()207-208- # On windows the temporary directory is used specific unless209- # explicitly forced otherwise. We can just use that.210- if os.name == "nt":211- return tmpdir212- if not hasattr(os, "getuid"):213- _unsafe_dir()214-215- dirname = "_jinja2-cache-%d" % os.getuid()216- actual_dir = os.path.join(tmpdir, dirname)217-218- try:219- os.mkdir(actual_dir, stat.S_IRWXU)220- except OSError as e:221- if e.errno != errno.EEXIST:222- raise223- try:224- os.chmod(actual_dir, stat.S_IRWXU)225- actual_dir_stat = os.lstat(actual_dir)226- if (227- actual_dir_stat.st_uid != os.getuid()228- or not stat.S_ISDIR(actual_dir_stat.st_mode)229- or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU230- ):231- _unsafe_dir()232- except OSError as e:233- if e.errno != errno.EEXIST:234- raise235-236- actual_dir_stat = os.lstat(actual_dir)237- if (238- actual_dir_stat.st_uid != os.getuid()239- or not stat.S_ISDIR(actual_dir_stat.st_mode)240- or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU241- ):242- _unsafe_dir()243-244- return actual_dir245-246- def _get_cache_filename(self, bucket):247- return path.join(self.directory, self.pattern % bucket.key)248-249- def load_bytecode(self, bucket):250- f = open_if_exists(self._get_cache_filename(bucket), "rb")251- if f is not None:252- try:253- bucket.load_bytecode(f)254- finally:255- f.close()256-257- def dump_bytecode(self, bucket):258- f = open(self._get_cache_filename(bucket), "wb")259- try:260- bucket.write_bytecode(f)261- finally:262- f.close()263-264- def clear(self):265- # imported lazily here because google app-engine doesn't support266- # write access on the file system and the function does not exist267- # normally.268- from os import remove269-270- files = fnmatch.filter(listdir(self.directory), self.pattern % "*")271- for filename in files:272- try:273- remove(path.join(self.directory, filename))274- except OSError:275- pass276-277-278-class MemcachedBytecodeCache(BytecodeCache):279- """This class implements a bytecode cache that uses a memcache cache for280- storing the information. It does not enforce a specific memcache library281- (tummy's memcache or cmemcache) but will accept any class that provides282- the minimal interface required.283-284- Libraries compatible with this class:285-286- - `cachelib <https://github.com/pallets/cachelib>`_287- - `python-memcached <https://pypi.org/project/python-memcached/>`_288-289- (Unfortunately the django cache interface is not compatible because it290- does not support storing binary data, only unicode. You can however pass291- the underlying cache client to the bytecode cache which is available292- as `django.core.cache.cache._client`.)293-294- The minimal interface for the client passed to the constructor is this:295-296- .. class:: MinimalClientInterface297-298- .. method:: set(key, value[, timeout])299-300- Stores the bytecode in the cache. `value` is a string and301- `timeout` the timeout of the key. If timeout is not provided302- a default timeout or no timeout should be assumed, if it's303- provided it's an integer with the number of seconds the cache304- item should exist.305-306- .. method:: get(key)307-308- Returns the value for the cache key. If the item does not309- exist in the cache the return value must be `None`.310-311- The other arguments to the constructor are the prefix for all keys that312- is added before the actual cache key and the timeout for the bytecode in313- the cache system. We recommend a high (or no) timeout.314-315- This bytecode cache does not support clearing of used items in the cache.316- The clear method is a no-operation function.317-318- .. versionadded:: 2.7319- Added support for ignoring memcache errors through the320- `ignore_memcache_errors` parameter.321- """322-323- def __init__(324- self,325- client,326- prefix="jinja2/bytecode/",327- timeout=None,328- ignore_memcache_errors=True,329- ):330- self.client = client331- self.prefix = prefix332- self.timeout = timeout333- self.ignore_memcache_errors = ignore_memcache_errors334-335- def load_bytecode(self, bucket):336- try:337- code = self.client.get(self.prefix + bucket.key)338- except Exception:339- if not self.ignore_memcache_errors:340- raise341- code = None342- if code is not None:343- bucket.bytecode_from_string(code)344-345- def dump_bytecode(self, bucket):346- args = (self.prefix + bucket.key, bucket.bytecode_to_string())347- if self.timeout is not None:348- args += (self.timeout,)349- try:350- self.client.set(*args)351- except Exception:352- if not self.ignore_memcache_errors:353- raisedeleted:src/jinja2/compiler.py-1842 removed
1-# -*- coding: utf-8 -*-2-"""Compiles nodes from the parser into Python code."""3-from collections import namedtuple4-from functools import update_wrapper5-from itertools import chain6-from keyword import iskeyword as is_python_keyword7-8-from . import nodes9-from ._compat import imap10-from ._compat import iteritems11-from ._compat import izip12-from ._compat import NativeStringIO13-from ._compat import range_type14-from ._compat import string_types15-from ._compat import text_type16-from .exceptions import TemplateAssertionError17-from .idtracking import Symbols18-from .idtracking import VAR_LOAD_ALIAS19-from .idtracking import VAR_LOAD_PARAMETER20-from .idtracking import VAR_LOAD_RESOLVE21-from .idtracking import VAR_LOAD_UNDEFINED22-from .nodes import EvalContext23-from .optimizer import Optimizer24-from .utils import concat25-from .utils import escape26-from .utils import Markup27-from .visitor import NodeVisitor28-29-operators = {30- "eq": "==",31- "ne": "!=",32- "gt": ">",33- "gteq": ">=",34- "lt": "<",35- "lteq": "<=",36- "in": "in",37- "notin": "not in",38-}39-40-# what method to iterate over items do we want to use for dict iteration41-# in generated code? on 2.x let's go with iteritems, on 3.x with items42-if hasattr(dict, "iteritems"):43- dict_item_iter = "iteritems"44-else:45- dict_item_iter = "items"46-47-code_features = ["division"]48-49-# does this python version support generator stops? (PEP 0479)50-try:51- exec("from __future__ import generator_stop")52- code_features.append("generator_stop")53-except SyntaxError:54- pass55-56-# does this python version support yield from?57-try:58- exec("def f(): yield from x()")59-except SyntaxError:60- supports_yield_from = False61-else:62- supports_yield_from = True63-64-65-def optimizeconst(f):66- def new_func(self, node, frame, **kwargs):67- # Only optimize if the frame is not volatile68- if self.optimized and not frame.eval_ctx.volatile:69- new_node = self.optimizer.visit(node, frame.eval_ctx)70- if new_node != node:71- return self.visit(new_node, frame)72- return f(self, node, frame, **kwargs)73-74- return update_wrapper(new_func, f)75-76-77-def generate(78- node, environment, name, filename, stream=None, defer_init=False, optimized=True79-):80- """Generate the python source for a node tree."""81- if not isinstance(node, nodes.Template):82- raise TypeError("Can't compile non template nodes")83- generator = environment.code_generator_class(84- environment, name, filename, stream, defer_init, optimized85- )86- generator.visit(node)87- if stream is None:88- return generator.stream.getvalue()89-90-91-def has_safe_repr(value):92- """Does the node have a safe representation?"""93- if value is None or value is NotImplemented or value is Ellipsis:94- return True95- if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:96- return True97- if type(value) in (tuple, list, set, frozenset):98- for item in value:99- if not has_safe_repr(item):100- return False101- return True102- elif type(value) is dict:103- for key, value in iteritems(value):104- if not has_safe_repr(key):105- return False106- if not has_safe_repr(value):107- return False108- return True109- return False110-111-112-def find_undeclared(nodes, names):113- """Check if the names passed are accessed undeclared. The return value114- is a set of all the undeclared names from the sequence of names found.115- """116- visitor = UndeclaredNameVisitor(names)117- try:118- for node in nodes:119- visitor.visit(node)120- except VisitorExit:121- pass122- return visitor.undeclared123-124-125-class MacroRef(object):126- def __init__(self, node):127- self.node = node128- self.accesses_caller = False129- self.accesses_kwargs = False130- self.accesses_varargs = False131-132-133-class Frame(object):134- """Holds compile time information for us."""135-136- def __init__(self, eval_ctx, parent=None, level=None):137- self.eval_ctx = eval_ctx138- self.symbols = Symbols(parent and parent.symbols or None, level=level)139-140- # a toplevel frame is the root + soft frames such as if conditions.141- self.toplevel = False142-143- # the root frame is basically just the outermost frame, so no if144- # conditions. This information is used to optimize inheritance145- # situations.146- self.rootlevel = False147-148- # in some dynamic inheritance situations the compiler needs to add149- # write tests around output statements.150- self.require_output_check = parent and parent.require_output_check151-152- # inside some tags we are using a buffer rather than yield statements.153- # this for example affects {% filter %} or {% macro %}. If a frame154- # is buffered this variable points to the name of the list used as155- # buffer.156- self.buffer = None157-158- # the name of the block we're in, otherwise None.159- self.block = parent and parent.block or None160-161- # the parent of this frame162- self.parent = parent163-164- if parent is not None:165- self.buffer = parent.buffer166-167- def copy(self):168- """Create a copy of the current one."""169- rv = object.__new__(self.__class__)170- rv.__dict__.update(self.__dict__)171- rv.symbols = self.symbols.copy()172- return rv173-174- def inner(self, isolated=False):175- """Return an inner frame."""176- if isolated:177- return Frame(self.eval_ctx, level=self.symbols.level + 1)178- return Frame(self.eval_ctx, self)179-180- def soft(self):181- """Return a soft frame. A soft frame may not be modified as182- standalone thing as it shares the resources with the frame it183- was created of, but it's not a rootlevel frame any longer.184-185- This is only used to implement if-statements.186- """187- rv = self.copy()188- rv.rootlevel = False189- return rv190-191- __copy__ = copy192-193-194-class VisitorExit(RuntimeError):195- """Exception used by the `UndeclaredNameVisitor` to signal a stop."""196-197-198-class DependencyFinderVisitor(NodeVisitor):199- """A visitor that collects filter and test calls."""200-201- def __init__(self):202- self.filters = set()203- self.tests = set()204-205- def visit_Filter(self, node):206- self.generic_visit(node)207- self.filters.add(node.name)208-209- def visit_Test(self, node):210- self.generic_visit(node)211- self.tests.add(node.name)212-213- def visit_Block(self, node):214- """Stop visiting at blocks."""215-216-217-class UndeclaredNameVisitor(NodeVisitor):218- """A visitor that checks if a name is accessed without being219- declared. This is different from the frame visitor as it will220- not stop at closure frames.221- """222-223- def __init__(self, names):224- self.names = set(names)225- self.undeclared = set()226-227- def visit_Name(self, node):228- if node.ctx == "load" and node.name in self.names:229- self.undeclared.add(node.name)230- if self.undeclared == self.names:231- raise VisitorExit()232- else:233- self.names.discard(node.name)234-235- def visit_Block(self, node):236- """Stop visiting a blocks."""237-238-239-class CompilerExit(Exception):240- """Raised if the compiler encountered a situation where it just241- doesn't make sense to further process the code. Any block that242- raises such an exception is not further processed.243- """244-245-246-class CodeGenerator(NodeVisitor):247- def __init__(248- self, environment, name, filename, stream=None, defer_init=False, optimized=True249- ):250- if stream is None:251- stream = NativeStringIO()252- self.environment = environment253- self.name = name254- self.filename = filename255- self.stream = stream256- self.created_block_context = False257- self.defer_init = defer_init258- self.optimized = optimized259- if optimized:260- self.optimizer = Optimizer(environment)261-262- # aliases for imports263- self.import_aliases = {}264-265- # a registry for all blocks. Because blocks are moved out266- # into the global python scope they are registered here267- self.blocks = {}268-269- # the number of extends statements so far270- self.extends_so_far = 0271-272- # some templates have a rootlevel extends. In this case we273- # can safely assume that we're a child template and do some274- # more optimizations.275- self.has_known_extends = False276-277- # the current line number278- self.code_lineno = 1279-280- # registry of all filters and tests (global, not block local)281- self.tests = {}282- self.filters = {}283-284- # the debug information285- self.debug_info = []286- self._write_debug_info = None287-288- # the number of new lines before the next write()289- self._new_lines = 0290-291- # the line number of the last written statement292- self._last_line = 0293-294- # true if nothing was written so far.295- self._first_write = True296-297- # used by the `temporary_identifier` method to get new298- # unique, temporary identifier299- self._last_identifier = 0300-301- # the current indentation302- self._indentation = 0303-304- # Tracks toplevel assignments305- self._assign_stack = []306-307- # Tracks parameter definition blocks308- self._param_def_block = []309-310- # Tracks the current context.311- self._context_reference_stack = ["context"]312-313- # -- Various compilation helpers314-315- def fail(self, msg, lineno):316- """Fail with a :exc:`TemplateAssertionError`."""317- raise TemplateAssertionError(msg, lineno, self.name, self.filename)318-319- def temporary_identifier(self):320- """Get a new unique identifier."""321- self._last_identifier += 1322- return "t_%d" % self._last_identifier323-324- def buffer(self, frame):325- """Enable buffering for the frame from that point onwards."""326- frame.buffer = self.temporary_identifier()327- self.writeline("%s = []" % frame.buffer)328-329- def return_buffer_contents(self, frame, force_unescaped=False):330- """Return the buffer contents of the frame."""331- if not force_unescaped:332- if frame.eval_ctx.volatile:333- self.writeline("if context.eval_ctx.autoescape:")334- self.indent()335- self.writeline("return Markup(concat(%s))" % frame.buffer)336- self.outdent()337- self.writeline("else:")338- self.indent()339- self.writeline("return concat(%s)" % frame.buffer)340- self.outdent()341- return342- elif frame.eval_ctx.autoescape:343- self.writeline("return Markup(concat(%s))" % frame.buffer)344- return345- self.writeline("return concat(%s)" % frame.buffer)346-347- def indent(self):348- """Indent by one."""349- self._indentation += 1350-351- def outdent(self, step=1):352- """Outdent by step."""353- self._indentation -= step354-355- def start_write(self, frame, node=None):356- """Yield or write into the frame buffer."""357- if frame.buffer is None:358- self.writeline("yield ", node)359- else:360- self.writeline("%s.append(" % frame.buffer, node)361-362- def end_write(self, frame):363- """End the writing process started by `start_write`."""364- if frame.buffer is not None:365- self.write(")")366-367- def simple_write(self, s, frame, node=None):368- """Simple shortcut for start_write + write + end_write."""369- self.start_write(frame, node)370- self.write(s)371- self.end_write(frame)372-373- def blockvisit(self, nodes, frame):374- """Visit a list of nodes as block in a frame. If the current frame375- is no buffer a dummy ``if 0: yield None`` is written automatically.376- """377- try:378- self.writeline("pass")379- for node in nodes:380- self.visit(node, frame)381- except CompilerExit:382- pass383-384- def write(self, x):385- """Write a string into the output stream."""386- if self._new_lines:387- if not self._first_write:388- self.stream.write("\n" * self._new_lines)389- self.code_lineno += self._new_lines390- if self._write_debug_info is not None:391- self.debug_info.append((self._write_debug_info, self.code_lineno))392- self._write_debug_info = None393- self._first_write = False394- self.stream.write(" " * self._indentation)395- self._new_lines = 0396- self.stream.write(x)397-398- def writeline(self, x, node=None, extra=0):399- """Combination of newline and write."""400- self.newline(node, extra)401- self.write(x)402-403- def newline(self, node=None, extra=0):404- """Add one or more newlines before the next write."""405- self._new_lines = max(self._new_lines, 1 + extra)406- if node is not None and node.lineno != self._last_line:407- self._write_debug_info = node.lineno408- self._last_line = node.lineno409-410- def signature(self, node, frame, extra_kwargs=None):411- """Writes a function call to the stream for the current node.412- A leading comma is added automatically. The extra keyword413- arguments may not include python keywords otherwise a syntax414- error could occur. The extra keyword arguments should be given415- as python dict.416- """417- # if any of the given keyword arguments is a python keyword418- # we have to make sure that no invalid call is created.419- kwarg_workaround = False420- for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):421- if is_python_keyword(kwarg):422- kwarg_workaround = True423- break424-425- for arg in node.args:426- self.write(", ")427- self.visit(arg, frame)428-429- if not kwarg_workaround:430- for kwarg in node.kwargs:431- self.write(", ")432- self.visit(kwarg, frame)433- if extra_kwargs is not None:434- for key, value in iteritems(extra_kwargs):435- self.write(", %s=%s" % (key, value))436- if node.dyn_args:437- self.write(", *")438- self.visit(node.dyn_args, frame)439-440- if kwarg_workaround:441- if node.dyn_kwargs is not None:442- self.write(", **dict({")443- else:444- self.write(", **{")445- for kwarg in node.kwargs:446- self.write("%r: " % kwarg.key)447- self.visit(kwarg.value, frame)448- self.write(", ")449- if extra_kwargs is not None:450- for key, value in iteritems(extra_kwargs):451- self.write("%r: %s, " % (key, value))452- if node.dyn_kwargs is not None:453- self.write("}, **")454- self.visit(node.dyn_kwargs, frame)455- self.write(")")456- else:457- self.write("}")458-459- elif node.dyn_kwargs is not None:460- self.write(", **")461- self.visit(node.dyn_kwargs, frame)462-463- def pull_dependencies(self, nodes):464- """Pull all the dependencies."""465- visitor = DependencyFinderVisitor()466- for node in nodes:467- visitor.visit(node)468- for dependency in "filters", "tests":469- mapping = getattr(self, dependency)470- for name in getattr(visitor, dependency):471- if name not in mapping:472- mapping[name] = self.temporary_identifier()473- self.writeline(474- "%s = environment.%s[%r]" % (mapping[name], dependency, name)475- )476-477- def enter_frame(self, frame):478- undefs = []479- for target, (action, param) in iteritems(frame.symbols.loads):480- if action == VAR_LOAD_PARAMETER:481- pass482- elif action == VAR_LOAD_RESOLVE:483- self.writeline("%s = %s(%r)" % (target, self.get_resolve_func(), param))484- elif action == VAR_LOAD_ALIAS:485- self.writeline("%s = %s" % (target, param))486- elif action == VAR_LOAD_UNDEFINED:487- undefs.append(target)488- else:489- raise NotImplementedError("unknown load instruction")490- if undefs:491- self.writeline("%s = missing" % " = ".join(undefs))492-493- def leave_frame(self, frame, with_python_scope=False):494- if not with_python_scope:495- undefs = []496- for target, _ in iteritems(frame.symbols.loads):497- undefs.append(target)498- if undefs:499- self.writeline("%s = missing" % " = ".join(undefs))500-501- def func(self, name):502- if self.environment.is_async:503- return "async def %s" % name504- return "def %s" % name505-506- def macro_body(self, node, frame):507- """Dump the function def of a macro or call block."""508- frame = frame.inner()509- frame.symbols.analyze_node(node)510- macro_ref = MacroRef(node)511-512- explicit_caller = None513- skip_special_params = set()514- args = []515- for idx, arg in enumerate(node.args):516- if arg.name == "caller":517- explicit_caller = idx518- if arg.name in ("kwargs", "varargs"):519- skip_special_params.add(arg.name)520- args.append(frame.symbols.ref(arg.name))521-522- undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs"))523-524- if "caller" in undeclared:525- # In older Jinja versions there was a bug that allowed caller526- # to retain the special behavior even if it was mentioned in527- # the argument list. However thankfully this was only really528- # working if it was the last argument. So we are explicitly529- # checking this now and error out if it is anywhere else in530- # the argument list.531- if explicit_caller is not None:532- try:533- node.defaults[explicit_caller - len(node.args)]534- except IndexError:535- self.fail(536- "When defining macros or call blocks the "537- 'special "caller" argument must be omitted '538- "or be given a default.",539- node.lineno,540- )541- else:542- args.append(frame.symbols.declare_parameter("caller"))543- macro_ref.accesses_caller = True544- if "kwargs" in undeclared and "kwargs" not in skip_special_params:545- args.append(frame.symbols.declare_parameter("kwargs"))546- macro_ref.accesses_kwargs = True547- if "varargs" in undeclared and "varargs" not in skip_special_params:548- args.append(frame.symbols.declare_parameter("varargs"))549- macro_ref.accesses_varargs = True550-551- # macros are delayed, they never require output checks552- frame.require_output_check = False553- frame.symbols.analyze_node(node)554- self.writeline("%s(%s):" % (self.func("macro"), ", ".join(args)), node)555- self.indent()556-557- self.buffer(frame)558- self.enter_frame(frame)559-560- self.push_parameter_definitions(frame)561- for idx, arg in enumerate(node.args):562- ref = frame.symbols.ref(arg.name)563- self.writeline("if %s is missing:" % ref)564- self.indent()565- try:566- default = node.defaults[idx - len(node.args)]567- except IndexError:568- self.writeline(569- "%s = undefined(%r, name=%r)"570- % (ref, "parameter %r was not provided" % arg.name, arg.name)571- )572- else:573- self.writeline("%s = " % ref)574- self.visit(default, frame)575- self.mark_parameter_stored(ref)576- self.outdent()577- self.pop_parameter_definitions()578-579- self.blockvisit(node.body, frame)580- self.return_buffer_contents(frame, force_unescaped=True)581- self.leave_frame(frame, with_python_scope=True)582- self.outdent()583-584- return frame, macro_ref585-586- def macro_def(self, macro_ref, frame):587- """Dump the macro definition for the def created by macro_body."""588- arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args)589- name = getattr(macro_ref.node, "name", None)590- if len(macro_ref.node.args) == 1:591- arg_tuple += ","592- self.write(593- "Macro(environment, macro, %r, (%s), %r, %r, %r, "594- "context.eval_ctx.autoescape)"595- % (596- name,597- arg_tuple,598- macro_ref.accesses_kwargs,599- macro_ref.accesses_varargs,600- macro_ref.accesses_caller,601- )602- )603-604- def position(self, node):605- """Return a human readable position for the node."""606- rv = "line %d" % node.lineno607- if self.name is not None:608- rv += " in " + repr(self.name)609- return rv610-611- def dump_local_context(self, frame):612- return "{%s}" % ", ".join(613- "%r: %s" % (name, target)614- for name, target in iteritems(frame.symbols.dump_stores())615- )616-617- def write_commons(self):618- """Writes a common preamble that is used by root and block functions.619- Primarily this sets up common local helpers and enforces a generator620- through a dead branch.621- """622- self.writeline("resolve = context.resolve_or_missing")623- self.writeline("undefined = environment.undefined")624- # always use the standard Undefined class for the implicit else of625- # conditional expressions626- self.writeline("cond_expr_undefined = Undefined")627- self.writeline("if 0: yield None")628-629- def push_parameter_definitions(self, frame):630- """Pushes all parameter targets from the given frame into a local631- stack that permits tracking of yet to be assigned parameters. In632- particular this enables the optimization from `visit_Name` to skip633- undefined expressions for parameters in macros as macros can reference634- otherwise unbound parameters.635- """636- self._param_def_block.append(frame.symbols.dump_param_targets())637-638- def pop_parameter_definitions(self):639- """Pops the current parameter definitions set."""640- self._param_def_block.pop()641-642- def mark_parameter_stored(self, target):643- """Marks a parameter in the current parameter definitions as stored.644- This will skip the enforced undefined checks.645- """646- if self._param_def_block:647- self._param_def_block[-1].discard(target)648-649- def push_context_reference(self, target):650- self._context_reference_stack.append(target)651-652- def pop_context_reference(self):653- self._context_reference_stack.pop()654-655- def get_context_ref(self):656- return self._context_reference_stack[-1]657-658- def get_resolve_func(self):659- target = self._context_reference_stack[-1]660- if target == "context":661- return "resolve"662- return "%s.resolve" % target663-664- def derive_context(self, frame):665- return "%s.derived(%s)" % (666- self.get_context_ref(),667- self.dump_local_context(frame),668- )669-670- def parameter_is_undeclared(self, target):671- """Checks if a given target is an undeclared parameter."""672- if not self._param_def_block:673- return False674- return target in self._param_def_block[-1]675-676- def push_assign_tracking(self):677- """Pushes a new layer for assignment tracking."""678- self._assign_stack.append(set())679-680- def pop_assign_tracking(self, frame):681- """Pops the topmost level for assignment tracking and updates the682- context variables if necessary.683- """684- vars = self._assign_stack.pop()685- if not frame.toplevel or not vars:686- return687- public_names = [x for x in vars if x[:1] != "_"]688- if len(vars) == 1:689- name = next(iter(vars))690- ref = frame.symbols.ref(name)691- self.writeline("context.vars[%r] = %s" % (name, ref))692- else:693- self.writeline("context.vars.update({")694- for idx, name in enumerate(vars):695- if idx:696- self.write(", ")697- ref = frame.symbols.ref(name)698- self.write("%r: %s" % (name, ref))699- self.write("})")700- if public_names:701- if len(public_names) == 1:702- self.writeline("context.exported_vars.add(%r)" % public_names[0])703- else:704- self.writeline(705- "context.exported_vars.update((%s))"706- % ", ".join(imap(repr, public_names))707- )708-709- # -- Statement Visitors710-711- def visit_Template(self, node, frame=None):712- assert frame is None, "no root frame allowed"713- eval_ctx = EvalContext(self.environment, self.name)714-715- from .runtime import __all__ as exported716-717- self.writeline("from __future__ import %s" % ", ".join(code_features))718- self.writeline("from jinja2.runtime import " + ", ".join(exported))719-720- if self.environment.is_async:721- self.writeline(722- "from jinja2.asyncsupport import auto_await, "723- "auto_aiter, AsyncLoopContext"724- )725-726- # if we want a deferred initialization we cannot move the727- # environment into a local name728- envenv = not self.defer_init and ", environment=environment" or ""729-730- # do we have an extends tag at all? If not, we can save some731- # overhead by just not processing any inheritance code.732- have_extends = node.find(nodes.Extends) is not None733-734- # find all blocks735- for block in node.find_all(nodes.Block):736- if block.name in self.blocks:737- self.fail("block %r defined twice" % block.name, block.lineno)738- self.blocks[block.name] = block739-740- # find all imports and import them741- for import_ in node.find_all(nodes.ImportedName):742- if import_.importname not in self.import_aliases:743- imp = import_.importname744- self.import_aliases[imp] = alias = self.temporary_identifier()745- if "." in imp:746- module, obj = imp.rsplit(".", 1)747- self.writeline("from %s import %s as %s" % (module, obj, alias))748- else:749- self.writeline("import %s as %s" % (imp, alias))750-751- # add the load name752- self.writeline("name = %r" % self.name)753-754- # generate the root render function.755- self.writeline(756- "%s(context, missing=missing%s):" % (self.func("root"), envenv), extra=1757- )758- self.indent()759- self.write_commons()760-761- # process the root762- frame = Frame(eval_ctx)763- if "self" in find_undeclared(node.body, ("self",)):764- ref = frame.symbols.declare_parameter("self")765- self.writeline("%s = TemplateReference(context)" % ref)766- frame.symbols.analyze_node(node)767- frame.toplevel = frame.rootlevel = True768- frame.require_output_check = have_extends and not self.has_known_extends769- if have_extends:770- self.writeline("parent_template = None")771- self.enter_frame(frame)772- self.pull_dependencies(node.body)773- self.blockvisit(node.body, frame)774- self.leave_frame(frame, with_python_scope=True)775- self.outdent()776-777- # make sure that the parent root is called.778- if have_extends:779- if not self.has_known_extends:780- self.indent()781- self.writeline("if parent_template is not None:")782- self.indent()783- if supports_yield_from and not self.environment.is_async:784- self.writeline("yield from parent_template.root_render_func(context)")785- else:786- self.writeline(787- "%sfor event in parent_template."788- "root_render_func(context):"789- % (self.environment.is_async and "async " or "")790- )791- self.indent()792- self.writeline("yield event")793- self.outdent()794- self.outdent(1 + (not self.has_known_extends))795-796- # at this point we now have the blocks collected and can visit them too.797- for name, block in iteritems(self.blocks):798- self.writeline(799- "%s(context, missing=missing%s):"800- % (self.func("block_" + name), envenv),801- block,802- 1,803- )804- self.indent()805- self.write_commons()806- # It's important that we do not make this frame a child of the807- # toplevel template. This would cause a variety of808- # interesting issues with identifier tracking.809- block_frame = Frame(eval_ctx)810- undeclared = find_undeclared(block.body, ("self", "super"))811- if "self" in undeclared:812- ref = block_frame.symbols.declare_parameter("self")813- self.writeline("%s = TemplateReference(context)" % ref)814- if "super" in undeclared:815- ref = block_frame.symbols.declare_parameter("super")816- self.writeline("%s = context.super(%r, block_%s)" % (ref, name, name))817- block_frame.symbols.analyze_node(block)818- block_frame.block = name819- self.enter_frame(block_frame)820- self.pull_dependencies(block.body)821- self.blockvisit(block.body, block_frame)822- self.leave_frame(block_frame, with_python_scope=True)823- self.outdent()824-825- self.writeline(826- "blocks = {%s}" % ", ".join("%r: block_%s" % (x, x) for x in self.blocks),827- extra=1,828- )829-830- # add a function that returns the debug info831- self.writeline(832- "debug_info = %r" % "&".join("%s=%s" % x for x in self.debug_info)833- )834-835- def visit_Block(self, node, frame):836- """Call a block and register it for the template."""837- level = 0838- if frame.toplevel:839- # if we know that we are a child template, there is no need to840- # check if we are one841- if self.has_known_extends:842- return843- if self.extends_so_far > 0:844- self.writeline("if parent_template is None:")845- self.indent()846- level += 1847-848- if node.scoped:849- context = self.derive_context(frame)850- else:851- context = self.get_context_ref()852-853- if (854- supports_yield_from855- and not self.environment.is_async856- and frame.buffer is None857- ):858- self.writeline(859- "yield from context.blocks[%r][0](%s)" % (node.name, context), node860- )861- else:862- loop = self.environment.is_async and "async for" or "for"863- self.writeline(864- "%s event in context.blocks[%r][0](%s):" % (loop, node.name, context),865- node,866- )867- self.indent()868- self.simple_write("event", frame)869- self.outdent()870-871- self.outdent(level)872-873- def visit_Extends(self, node, frame):874- """Calls the extender."""875- if not frame.toplevel:876- self.fail("cannot use extend from a non top-level scope", node.lineno)877-878- # if the number of extends statements in general is zero so879- # far, we don't have to add a check if something extended880- # the template before this one.881- if self.extends_so_far > 0:882-883- # if we have a known extends we just add a template runtime884- # error into the generated code. We could catch that at compile885- # time too, but i welcome it not to confuse users by throwing the886- # same error at different times just "because we can".887- if not self.has_known_extends:888- self.writeline("if parent_template is not None:")889- self.indent()890- self.writeline("raise TemplateRuntimeError(%r)" % "extended multiple times")891-892- # if we have a known extends already we don't need that code here893- # as we know that the template execution will end here.894- if self.has_known_extends:895- raise CompilerExit()896- else:897- self.outdent()898-899- self.writeline("parent_template = environment.get_template(", node)900- self.visit(node.template, frame)901- self.write(", %r)" % self.name)902- self.writeline(903- "for name, parent_block in parent_template.blocks.%s():" % dict_item_iter904- )905- self.indent()906- self.writeline("context.blocks.setdefault(name, []).append(parent_block)")907- self.outdent()908-909- # if this extends statement was in the root level we can take910- # advantage of that information and simplify the generated code911- # in the top level from this point onwards912- if frame.rootlevel:913- self.has_known_extends = True914-915- # and now we have one more916- self.extends_so_far += 1917-918- def visit_Include(self, node, frame):919- """Handles includes."""920- if node.ignore_missing:921- self.writeline("try:")922- self.indent()923-924- func_name = "get_or_select_template"925- if isinstance(node.template, nodes.Const):926- if isinstance(node.template.value, string_types):927- func_name = "get_template"928- elif isinstance(node.template.value, (tuple, list)):929- func_name = "select_template"930- elif isinstance(node.template, (nodes.Tuple, nodes.List)):931- func_name = "select_template"932-933- self.writeline("template = environment.%s(" % func_name, node)934- self.visit(node.template, frame)935- self.write(", %r)" % self.name)936- if node.ignore_missing:937- self.outdent()938- self.writeline("except TemplateNotFound:")939- self.indent()940- self.writeline("pass")941- self.outdent()942- self.writeline("else:")943- self.indent()944-945- skip_event_yield = False946- if node.with_context:947- loop = self.environment.is_async and "async for" or "for"948- self.writeline(949- "%s event in template.root_render_func("950- "template.new_context(context.get_all(), True, "951- "%s)):" % (loop, self.dump_local_context(frame))952- )953- elif self.environment.is_async:954- self.writeline(955- "for event in (await "956- "template._get_default_module_async())"957- "._body_stream:"958- )959- else:960- if supports_yield_from:961- self.writeline("yield from template._get_default_module()._body_stream")962- skip_event_yield = True963- else:964- self.writeline(965- "for event in template._get_default_module()._body_stream:"966- )967-968- if not skip_event_yield:969- self.indent()970- self.simple_write("event", frame)971- self.outdent()972-973- if node.ignore_missing:974- self.outdent()975-976- def visit_Import(self, node, frame):977- """Visit regular imports."""978- self.writeline("%s = " % frame.symbols.ref(node.target), node)979- if frame.toplevel:980- self.write("context.vars[%r] = " % node.target)981- if self.environment.is_async:982- self.write("await ")983- self.write("environment.get_template(")984- self.visit(node.template, frame)985- self.write(", %r)." % self.name)986- if node.with_context:987- self.write(988- "make_module%s(context.get_all(), True, %s)"989- % (990- self.environment.is_async and "_async" or "",991- self.dump_local_context(frame),992- )993- )994- elif self.environment.is_async:995- self.write("_get_default_module_async()")996- else:997- self.write("_get_default_module()")998- if frame.toplevel and not node.target.startswith("_"):999- self.writeline("context.exported_vars.discard(%r)" % node.target)1000-1001- def visit_FromImport(self, node, frame):1002- """Visit named imports."""1003- self.newline(node)1004- self.write(1005- "included_template = %senvironment.get_template("1006- % (self.environment.is_async and "await " or "")1007- )1008- self.visit(node.template, frame)1009- self.write(", %r)." % self.name)1010- if node.with_context:1011- self.write(1012- "make_module%s(context.get_all(), True, %s)"1013- % (1014- self.environment.is_async and "_async" or "",1015- self.dump_local_context(frame),1016- )1017- )1018- elif self.environment.is_async:1019- self.write("_get_default_module_async()")1020- else:1021- self.write("_get_default_module()")1022-1023- var_names = []1024- discarded_names = []1025- for name in node.names:1026- if isinstance(name, tuple):1027- name, alias = name1028- else:1029- alias = name1030- self.writeline(1031- "%s = getattr(included_template, "1032- "%r, missing)" % (frame.symbols.ref(alias), name)1033- )1034- self.writeline("if %s is missing:" % frame.symbols.ref(alias))1035- self.indent()1036- self.writeline(1037- "%s = undefined(%r %% "1038- "included_template.__name__, "1039- "name=%r)"1040- % (1041- frame.symbols.ref(alias),1042- "the template %%r (imported on %s) does "1043- "not export the requested name %s"1044- % (self.position(node), repr(name)),1045- name,1046- )1047- )1048- self.outdent()1049- if frame.toplevel:1050- var_names.append(alias)1051- if not alias.startswith("_"):1052- discarded_names.append(alias)1053-1054- if var_names:1055- if len(var_names) == 1:1056- name = var_names[0]1057- self.writeline(1058- "context.vars[%r] = %s" % (name, frame.symbols.ref(name))1059- )1060- else:1061- self.writeline(1062- "context.vars.update({%s})"1063- % ", ".join(1064- "%r: %s" % (name, frame.symbols.ref(name)) for name in var_names1065- )1066- )1067- if discarded_names:1068- if len(discarded_names) == 1:1069- self.writeline("context.exported_vars.discard(%r)" % discarded_names[0])1070- else:1071- self.writeline(1072- "context.exported_vars.difference_"1073- "update((%s))" % ", ".join(imap(repr, discarded_names))1074- )1075-1076- def visit_For(self, node, frame):1077- loop_frame = frame.inner()1078- test_frame = frame.inner()1079- else_frame = frame.inner()1080-1081- # try to figure out if we have an extended loop. An extended loop1082- # is necessary if the loop is in recursive mode if the special loop1083- # variable is accessed in the body.1084- extended_loop = node.recursive or "loop" in find_undeclared(1085- node.iter_child_nodes(only=("body",)), ("loop",)1086- )1087-1088- loop_ref = None1089- if extended_loop:1090- loop_ref = loop_frame.symbols.declare_parameter("loop")1091-1092- loop_frame.symbols.analyze_node(node, for_branch="body")1093- if node.else_:1094- else_frame.symbols.analyze_node(node, for_branch="else")1095-1096- if node.test:1097- loop_filter_func = self.temporary_identifier()1098- test_frame.symbols.analyze_node(node, for_branch="test")1099- self.writeline("%s(fiter):" % self.func(loop_filter_func), node.test)1100- self.indent()1101- self.enter_frame(test_frame)1102- self.writeline(self.environment.is_async and "async for " or "for ")1103- self.visit(node.target, loop_frame)1104- self.write(" in ")1105- self.write(self.environment.is_async and "auto_aiter(fiter)" or "fiter")1106- self.write(":")1107- self.indent()1108- self.writeline("if ", node.test)1109- self.visit(node.test, test_frame)1110- self.write(":")1111- self.indent()1112- self.writeline("yield ")1113- self.visit(node.target, loop_frame)1114- self.outdent(3)1115- self.leave_frame(test_frame, with_python_scope=True)1116-1117- # if we don't have an recursive loop we have to find the shadowed1118- # variables at that point. Because loops can be nested but the loop1119- # variable is a special one we have to enforce aliasing for it.1120- if node.recursive:1121- self.writeline(1122- "%s(reciter, loop_render_func, depth=0):" % self.func("loop"), node1123- )1124- self.indent()1125- self.buffer(loop_frame)1126-1127- # Use the same buffer for the else frame1128- else_frame.buffer = loop_frame.buffer1129-1130- # make sure the loop variable is a special one and raise a template1131- # assertion error if a loop tries to write to loop1132- if extended_loop:1133- self.writeline("%s = missing" % loop_ref)1134-1135- for name in node.find_all(nodes.Name):1136- if name.ctx == "store" and name.name == "loop":1137- self.fail(1138- "Can't assign to special loop variable in for-loop target",1139- name.lineno,1140- )1141-1142- if node.else_:1143- iteration_indicator = self.temporary_identifier()1144- self.writeline("%s = 1" % iteration_indicator)1145-1146- self.writeline(self.environment.is_async and "async for " or "for ", node)1147- self.visit(node.target, loop_frame)1148- if extended_loop:1149- if self.environment.is_async:1150- self.write(", %s in AsyncLoopContext(" % loop_ref)1151- else:1152- self.write(", %s in LoopContext(" % loop_ref)1153- else:1154- self.write(" in ")1155-1156- if node.test:1157- self.write("%s(" % loop_filter_func)1158- if node.recursive:1159- self.write("reciter")1160- else:1161- if self.environment.is_async and not extended_loop:1162- self.write("auto_aiter(")1163- self.visit(node.iter, frame)1164- if self.environment.is_async and not extended_loop:1165- self.write(")")1166- if node.test:1167- self.write(")")1168-1169- if node.recursive:1170- self.write(", undefined, loop_render_func, depth):")1171- else:1172- self.write(extended_loop and ", undefined):" or ":")1173-1174- self.indent()1175- self.enter_frame(loop_frame)1176-1177- self.blockvisit(node.body, loop_frame)1178- if node.else_:1179- self.writeline("%s = 0" % iteration_indicator)1180- self.outdent()1181- self.leave_frame(1182- loop_frame, with_python_scope=node.recursive and not node.else_1183- )1184-1185- if node.else_:1186- self.writeline("if %s:" % iteration_indicator)1187- self.indent()1188- self.enter_frame(else_frame)1189- self.blockvisit(node.else_, else_frame)1190- self.leave_frame(else_frame)1191- self.outdent()1192-1193- # if the node was recursive we have to return the buffer contents1194- # and start the iteration code1195- if node.recursive:1196- self.return_buffer_contents(loop_frame)1197- self.outdent()1198- self.start_write(frame, node)1199- if self.environment.is_async:1200- self.write("await ")1201- self.write("loop(")1202- if self.environment.is_async:1203- self.write("auto_aiter(")1204- self.visit(node.iter, frame)1205- if self.environment.is_async:1206- self.write(")")1207- self.write(", loop)")1208- self.end_write(frame)1209-1210- def visit_If(self, node, frame):1211- if_frame = frame.soft()1212- self.writeline("if ", node)1213- self.visit(node.test, if_frame)1214- self.write(":")1215- self.indent()1216- self.blockvisit(node.body, if_frame)1217- self.outdent()1218- for elif_ in node.elif_:1219- self.writeline("elif ", elif_)1220- self.visit(elif_.test, if_frame)1221- self.write(":")1222- self.indent()1223- self.blockvisit(elif_.body, if_frame)1224- self.outdent()1225- if node.else_:1226- self.writeline("else:")1227- self.indent()1228- self.blockvisit(node.else_, if_frame)1229- self.outdent()1230-1231- def visit_Macro(self, node, frame):1232- macro_frame, macro_ref = self.macro_body(node, frame)1233- self.newline()1234- if frame.toplevel:1235- if not node.name.startswith("_"):1236- self.write("context.exported_vars.add(%r)" % node.name)1237- self.writeline("context.vars[%r] = " % node.name)1238- self.write("%s = " % frame.symbols.ref(node.name))1239- self.macro_def(macro_ref, macro_frame)1240-1241- def visit_CallBlock(self, node, frame):1242- call_frame, macro_ref = self.macro_body(node, frame)1243- self.writeline("caller = ")1244- self.macro_def(macro_ref, call_frame)1245- self.start_write(frame, node)1246- self.visit_Call(node.call, frame, forward_caller=True)1247- self.end_write(frame)1248-1249- def visit_FilterBlock(self, node, frame):1250- filter_frame = frame.inner()1251- filter_frame.symbols.analyze_node(node)1252- self.enter_frame(filter_frame)1253- self.buffer(filter_frame)1254- self.blockvisit(node.body, filter_frame)1255- self.start_write(frame, node)1256- self.visit_Filter(node.filter, filter_frame)1257- self.end_write(frame)1258- self.leave_frame(filter_frame)1259-1260- def visit_With(self, node, frame):1261- with_frame = frame.inner()1262- with_frame.symbols.analyze_node(node)1263- self.enter_frame(with_frame)1264- for target, expr in izip(node.targets, node.values):1265- self.newline()1266- self.visit(target, with_frame)1267- self.write(" = ")1268- self.visit(expr, frame)1269- self.blockvisit(node.body, with_frame)1270- self.leave_frame(with_frame)1271-1272- def visit_ExprStmt(self, node, frame):1273- self.newline(node)1274- self.visit(node.node, frame)1275-1276- _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1277- #: The default finalize function if the environment isn't configured1278- #: with one. Or if the environment has one, this is called on that1279- #: function's output for constants.1280- _default_finalize = text_type1281- _finalize = None1282-1283- def _make_finalize(self):1284- """Build the finalize function to be used on constants and at1285- runtime. Cached so it's only created once for all output nodes.1286-1287- Returns a ``namedtuple`` with the following attributes:1288-1289- ``const``1290- A function to finalize constant data at compile time.1291-1292- ``src``1293- Source code to output around nodes to be evaluated at1294- runtime.1295- """1296- if self._finalize is not None:1297- return self._finalize1298-1299- finalize = default = self._default_finalize1300- src = None1301-1302- if self.environment.finalize:1303- src = "environment.finalize("1304- env_finalize = self.environment.finalize1305-1306- def finalize(value):1307- return default(env_finalize(value))1308-1309- if getattr(env_finalize, "contextfunction", False):1310- src += "context, "1311- finalize = None # noqa: F8111312- elif getattr(env_finalize, "evalcontextfunction", False):1313- src += "context.eval_ctx, "1314- finalize = None1315- elif getattr(env_finalize, "environmentfunction", False):1316- src += "environment, "1317-1318- def finalize(value):1319- return default(env_finalize(self.environment, value))1320-1321- self._finalize = self._FinalizeInfo(finalize, src)1322- return self._finalize1323-1324- def _output_const_repr(self, group):1325- """Given a group of constant values converted from ``Output``1326- child nodes, produce a string to write to the template module1327- source.1328- """1329- return repr(concat(group))1330-1331- def _output_child_to_const(self, node, frame, finalize):1332- """Try to optimize a child of an ``Output`` node by trying to1333- convert it to constant, finalized data at compile time.1334-1335- If :exc:`Impossible` is raised, the node is not constant and1336- will be evaluated at runtime. Any other exception will also be1337- evaluated at runtime for easier debugging.1338- """1339- const = node.as_const(frame.eval_ctx)1340-1341- if frame.eval_ctx.autoescape:1342- const = escape(const)1343-1344- # Template data doesn't go through finalize.1345- if isinstance(node, nodes.TemplateData):1346- return text_type(const)1347-1348- return finalize.const(const)1349-1350- def _output_child_pre(self, node, frame, finalize):1351- """Output extra source code before visiting a child of an1352- ``Output`` node.1353- """1354- if frame.eval_ctx.volatile:1355- self.write("(escape if context.eval_ctx.autoescape else to_string)(")1356- elif frame.eval_ctx.autoescape:1357- self.write("escape(")1358- else:1359- self.write("to_string(")1360-1361- if finalize.src is not None:1362- self.write(finalize.src)1363-1364- def _output_child_post(self, node, frame, finalize):1365- """Output extra source code after visiting a child of an1366- ``Output`` node.1367- """1368- self.write(")")1369-1370- if finalize.src is not None:1371- self.write(")")1372-1373- def visit_Output(self, node, frame):1374- # If an extends is active, don't render outside a block.1375- if frame.require_output_check:1376- # A top-level extends is known to exist at compile time.1377- if self.has_known_extends:1378- return1379-1380- self.writeline("if parent_template is None:")1381- self.indent()1382-1383- finalize = self._make_finalize()1384- body = []1385-1386- # Evaluate constants at compile time if possible. Each item in1387- # body will be either a list of static data or a node to be1388- # evaluated at runtime.1389- for child in node.nodes:1390- try:1391- if not (1392- # If the finalize function requires runtime context,1393- # constants can't be evaluated at compile time.1394- finalize.const1395- # Unless it's basic template data that won't be1396- # finalized anyway.1397- or isinstance(child, nodes.TemplateData)1398- ):1399- raise nodes.Impossible()1400-1401- const = self._output_child_to_const(child, frame, finalize)1402- except (nodes.Impossible, Exception):1403- # The node was not constant and needs to be evaluated at1404- # runtime. Or another error was raised, which is easier1405- # to debug at runtime.1406- body.append(child)1407- continue1408-1409- if body and isinstance(body[-1], list):1410- body[-1].append(const)1411- else:1412- body.append([const])1413-1414- if frame.buffer is not None:1415- if len(body) == 1:1416- self.writeline("%s.append(" % frame.buffer)1417- else:1418- self.writeline("%s.extend((" % frame.buffer)1419-1420- self.indent()1421-1422- for item in body:1423- if isinstance(item, list):1424- # A group of constant data to join and output.1425- val = self._output_const_repr(item)1426-1427- if frame.buffer is None:1428- self.writeline("yield " + val)1429- else:1430- self.writeline(val + ",")1431- else:1432- if frame.buffer is None:1433- self.writeline("yield ", item)1434- else:1435- self.newline(item)1436-1437- # A node to be evaluated at runtime.1438- self._output_child_pre(item, frame, finalize)1439- self.visit(item, frame)1440- self._output_child_post(item, frame, finalize)1441-1442- if frame.buffer is not None:1443- self.write(",")1444-1445- if frame.buffer is not None:1446- self.outdent()1447- self.writeline(")" if len(body) == 1 else "))")1448-1449- if frame.require_output_check:1450- self.outdent()1451-1452- def visit_Assign(self, node, frame):1453- self.push_assign_tracking()1454- self.newline(node)1455- self.visit(node.target, frame)1456- self.write(" = ")1457- self.visit(node.node, frame)1458- self.pop_assign_tracking(frame)1459-1460- def visit_AssignBlock(self, node, frame):1461- self.push_assign_tracking()1462- block_frame = frame.inner()1463- # This is a special case. Since a set block always captures we1464- # will disable output checks. This way one can use set blocks1465- # toplevel even in extended templates.1466- block_frame.require_output_check = False1467- block_frame.symbols.analyze_node(node)1468- self.enter_frame(block_frame)1469- self.buffer(block_frame)1470- self.blockvisit(node.body, block_frame)1471- self.newline(node)1472- self.visit(node.target, frame)1473- self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")1474- if node.filter is not None:1475- self.visit_Filter(node.filter, block_frame)1476- else:1477- self.write("concat(%s)" % block_frame.buffer)1478- self.write(")")1479- self.pop_assign_tracking(frame)1480- self.leave_frame(block_frame)1481-1482- # -- Expression Visitors1483-1484- def visit_Name(self, node, frame):1485- if node.ctx == "store" and frame.toplevel:1486- if self._assign_stack:1487- self._assign_stack[-1].add(node.name)1488- ref = frame.symbols.ref(node.name)1489-1490- # If we are looking up a variable we might have to deal with the1491- # case where it's undefined. We can skip that case if the load1492- # instruction indicates a parameter which are always defined.1493- if node.ctx == "load":1494- load = frame.symbols.find_load(ref)1495- if not (1496- load is not None1497- and load[0] == VAR_LOAD_PARAMETER1498- and not self.parameter_is_undeclared(ref)1499- ):1500- self.write(1501- "(undefined(name=%r) if %s is missing else %s)"1502- % (node.name, ref, ref)1503- )1504- return1505-1506- self.write(ref)1507-1508- def visit_NSRef(self, node, frame):1509- # NSRefs can only be used to store values; since they use the normal1510- # `foo.bar` notation they will be parsed as a normal attribute access1511- # when used anywhere but in a `set` context1512- ref = frame.symbols.ref(node.name)1513- self.writeline("if not isinstance(%s, Namespace):" % ref)1514- self.indent()1515- self.writeline(1516- "raise TemplateRuntimeError(%r)"1517- % "cannot assign attribute on non-namespace object"1518- )1519- self.outdent()1520- self.writeline("%s[%r]" % (ref, node.attr))1521-1522- def visit_Const(self, node, frame):1523- val = node.as_const(frame.eval_ctx)1524- if isinstance(val, float):1525- self.write(str(val))1526- else:1527- self.write(repr(val))1528-1529- def visit_TemplateData(self, node, frame):1530- try:1531- self.write(repr(node.as_const(frame.eval_ctx)))1532- except nodes.Impossible:1533- self.write(1534- "(Markup if context.eval_ctx.autoescape else identity)(%r)" % node.data1535- )1536-1537- def visit_Tuple(self, node, frame):1538- self.write("(")1539- idx = -11540- for idx, item in enumerate(node.items):1541- if idx:1542- self.write(", ")1543- self.visit(item, frame)1544- self.write(idx == 0 and ",)" or ")")1545-1546- def visit_List(self, node, frame):1547- self.write("[")1548- for idx, item in enumerate(node.items):1549- if idx:1550- self.write(", ")1551- self.visit(item, frame)1552- self.write("]")1553-1554- def visit_Dict(self, node, frame):1555- self.write("{")1556- for idx, item in enumerate(node.items):1557- if idx:1558- self.write(", ")1559- self.visit(item.key, frame)1560- self.write(": ")1561- self.visit(item.value, frame)1562- self.write("}")1563-1564- def binop(operator, interceptable=True): # noqa: B9021565- @optimizeconst1566- def visitor(self, node, frame):1567- if (1568- self.environment.sandboxed1569- and operator in self.environment.intercepted_binops1570- ):1571- self.write("environment.call_binop(context, %r, " % operator)1572- self.visit(node.left, frame)1573- self.write(", ")1574- self.visit(node.right, frame)1575- else:1576- self.write("(")1577- self.visit(node.left, frame)1578- self.write(" %s " % operator)1579- self.visit(node.right, frame)1580- self.write(")")1581-1582- return visitor1583-1584- def uaop(operator, interceptable=True): # noqa: B9021585- @optimizeconst1586- def visitor(self, node, frame):1587- if (1588- self.environment.sandboxed1589- and operator in self.environment.intercepted_unops1590- ):1591- self.write("environment.call_unop(context, %r, " % operator)1592- self.visit(node.node, frame)1593- else:1594- self.write("(" + operator)1595- self.visit(node.node, frame)1596- self.write(")")1597-1598- return visitor1599-1600- visit_Add = binop("+")1601- visit_Sub = binop("-")1602- visit_Mul = binop("*")1603- visit_Div = binop("/")1604- visit_FloorDiv = binop("//")1605- visit_Pow = binop("**")1606- visit_Mod = binop("%")1607- visit_And = binop("and", interceptable=False)1608- visit_Or = binop("or", interceptable=False)1609- visit_Pos = uaop("+")1610- visit_Neg = uaop("-")1611- visit_Not = uaop("not ", interceptable=False)1612- del binop, uaop1613-1614- @optimizeconst1615- def visit_Concat(self, node, frame):1616- if frame.eval_ctx.volatile:1617- func_name = "(context.eval_ctx.volatile and markup_join or unicode_join)"1618- elif frame.eval_ctx.autoescape:1619- func_name = "markup_join"1620- else:1621- func_name = "unicode_join"1622- self.write("%s((" % func_name)1623- for arg in node.nodes:1624- self.visit(arg, frame)1625- self.write(", ")1626- self.write("))")1627-1628- @optimizeconst1629- def visit_Compare(self, node, frame):1630- self.write("(")1631- self.visit(node.expr, frame)1632- for op in node.ops:1633- self.visit(op, frame)1634- self.write(")")1635-1636- def visit_Operand(self, node, frame):1637- self.write(" %s " % operators[node.op])1638- self.visit(node.expr, frame)1639-1640- @optimizeconst1641- def visit_Getattr(self, node, frame):1642- if self.environment.is_async:1643- self.write("await auto_await(")1644-1645- self.write("environment.getattr(")1646- self.visit(node.node, frame)1647- self.write(", %r)" % node.attr)1648-1649- if self.environment.is_async:1650- self.write(")")1651-1652- @optimizeconst1653- def visit_Getitem(self, node, frame):1654- # slices bypass the environment getitem method.1655- if isinstance(node.arg, nodes.Slice):1656- self.visit(node.node, frame)1657- self.write("[")1658- self.visit(node.arg, frame)1659- self.write("]")1660- else:1661- if self.environment.is_async:1662- self.write("await auto_await(")1663-1664- self.write("environment.getitem(")1665- self.visit(node.node, frame)1666- self.write(", ")1667- self.visit(node.arg, frame)1668- self.write(")")1669-1670- if self.environment.is_async:1671- self.write(")")1672-1673- def visit_Slice(self, node, frame):1674- if node.start is not None:1675- self.visit(node.start, frame)1676- self.write(":")1677- if node.stop is not None:1678- self.visit(node.stop, frame)1679- if node.step is not None:1680- self.write(":")1681- self.visit(node.step, frame)1682-1683- @optimizeconst1684- def visit_Filter(self, node, frame):1685- if self.environment.is_async:1686- self.write("await auto_await(")1687- self.write(self.filters[node.name] + "(")1688- func = self.environment.filters.get(node.name)1689- if func is None:1690- self.fail("no filter named %r" % node.name, node.lineno)1691- if getattr(func, "contextfilter", False):1692- self.write("context, ")1693- elif getattr(func, "evalcontextfilter", False):1694- self.write("context.eval_ctx, ")1695- elif getattr(func, "environmentfilter", False):1696- self.write("environment, ")1697-1698- # if the filter node is None we are inside a filter block1699- # and want to write to the current buffer1700- if node.node is not None:1701- self.visit(node.node, frame)1702- elif frame.eval_ctx.volatile:1703- self.write(1704- "(context.eval_ctx.autoescape and"1705- " Markup(concat(%s)) or concat(%s))" % (frame.buffer, frame.buffer)1706- )1707- elif frame.eval_ctx.autoescape:1708- self.write("Markup(concat(%s))" % frame.buffer)1709- else:1710- self.write("concat(%s)" % frame.buffer)1711- self.signature(node, frame)1712- self.write(")")1713- if self.environment.is_async:1714- self.write(")")1715-1716- @optimizeconst1717- def visit_Test(self, node, frame):1718- self.write(self.tests[node.name] + "(")1719- if node.name not in self.environment.tests:1720- self.fail("no test named %r" % node.name, node.lineno)1721- self.visit(node.node, frame)1722- self.signature(node, frame)1723- self.write(")")1724-1725- @optimizeconst1726- def visit_CondExpr(self, node, frame):1727- def write_expr2():1728- if node.expr2 is not None:1729- return self.visit(node.expr2, frame)1730- self.write(1731- "cond_expr_undefined(%r)"1732- % (1733- "the inline if-"1734- "expression on %s evaluated to false and "1735- "no else section was defined." % self.position(node)1736- )1737- )1738-1739- self.write("(")1740- self.visit(node.expr1, frame)1741- self.write(" if ")1742- self.visit(node.test, frame)1743- self.write(" else ")1744- write_expr2()1745- self.write(")")1746-1747- @optimizeconst1748- def visit_Call(self, node, frame, forward_caller=False):1749- if self.environment.is_async:1750- self.write("await auto_await(")1751- if self.environment.sandboxed:1752- self.write("environment.call(context, ")1753- else:1754- self.write("context.call(")1755- self.visit(node.node, frame)1756- extra_kwargs = forward_caller and {"caller": "caller"} or None1757- self.signature(node, frame, extra_kwargs)1758- self.write(")")1759- if self.environment.is_async:1760- self.write(")")1761-1762- def visit_Keyword(self, node, frame):1763- self.write(node.key + "=")1764- self.visit(node.value, frame)1765-1766- # -- Unused nodes for extensions1767-1768- def visit_MarkSafe(self, node, frame):1769- self.write("Markup(")1770- self.visit(node.expr, frame)1771- self.write(")")1772-1773- def visit_MarkSafeIfAutoescape(self, node, frame):1774- self.write("(context.eval_ctx.autoescape and Markup or identity)(")1775- self.visit(node.expr, frame)1776- self.write(")")1777-1778- def visit_EnvironmentAttribute(self, node, frame):1779- self.write("environment." + node.name)1780-1781- def visit_ExtensionAttribute(self, node, frame):1782- self.write("environment.extensions[%r].%s" % (node.identifier, node.name))1783-1784- def visit_ImportedName(self, node, frame):1785- self.write(self.import_aliases[node.importname])1786-1787- def visit_InternalName(self, node, frame):1788- self.write(node.name)1789-1790- def visit_ContextReference(self, node, frame):1791- self.write("context")1792-1793- def visit_DerivedContextReference(self, node, frame):1794- self.write(self.derive_context(frame))1795-1796- def visit_Continue(self, node, frame):1797- self.writeline("continue", node)1798-1799- def visit_Break(self, node, frame):1800- self.writeline("break", node)1801-1802- def visit_Scope(self, node, frame):1803- scope_frame = frame.inner()1804- scope_frame.symbols.analyze_node(node)1805- self.enter_frame(scope_frame)1806- self.blockvisit(node.body, scope_frame)1807- self.leave_frame(scope_frame)1808-1809- def visit_OverlayScope(self, node, frame):1810- ctx = self.temporary_identifier()1811- self.writeline("%s = %s" % (ctx, self.derive_context(frame)))1812- self.writeline("%s.vars = " % ctx)1813- self.visit(node.context, frame)1814- self.push_context_reference(ctx)1815-1816- scope_frame = frame.inner(isolated=True)1817- scope_frame.symbols.analyze_node(node)1818- self.enter_frame(scope_frame)1819- self.blockvisit(node.body, scope_frame)1820- self.leave_frame(scope_frame)1821- self.pop_context_reference()1822-1823- def visit_EvalContextModifier(self, node, frame):1824- for keyword in node.options:1825- self.writeline("context.eval_ctx.%s = " % keyword.key)1826- self.visit(keyword.value, frame)1827- try:1828- val = keyword.value.as_const(frame.eval_ctx)1829- except nodes.Impossible:1830- frame.eval_ctx.volatile = True1831- else:1832- setattr(frame.eval_ctx, keyword.key, val)1833-1834- def visit_ScopedEvalContextModifier(self, node, frame):1835- old_ctx_name = self.temporary_identifier()1836- saved_ctx = frame.eval_ctx.save()1837- self.writeline("%s = context.eval_ctx.save()" % old_ctx_name)1838- self.visit_EvalContextModifier(node, frame)1839- for child in node.body:1840- self.visit(child, frame)1841- frame.eval_ctx.revert(saved_ctx)1842- self.writeline("context.eval_ctx.revert(%s)" % old_ctx_name)deleted:src/jinja2/constants.py-21 removed
1-# -*- coding: utf-8 -*-2-#: list of lorem ipsum words used by the lipsum() helper function3-LOREM_IPSUM_WORDS = u"""\4-a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at5-auctor augue bibendum blandit class commodo condimentum congue consectetuer6-consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus7-diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend8-elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames9-faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac10-hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum11-justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem12-luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie13-mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non14-nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque15-penatibus per pharetra phasellus placerat platea porta porttitor posuere16-potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus17-ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit18-sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor19-tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices20-ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus21-viverra volutpat vulputate"""deleted:src/jinja2/debug.py-271 removed
1-import sys2-from types import CodeType3-4-from . import TemplateSyntaxError5-from ._compat import PYPY6-from .utils import internal_code7-from .utils import missing8-9-10-def rewrite_traceback_stack(source=None):11- """Rewrite the current exception to replace any tracebacks from12- within compiled template code with tracebacks that look like they13- came from the template source.14-15- This must be called within an ``except`` block.16-17- :param exc_info: A :meth:`sys.exc_info` tuple. If not provided,18- the current ``exc_info`` is used.19- :param source: For ``TemplateSyntaxError``, the original source if20- known.21- :return: A :meth:`sys.exc_info` tuple that can be re-raised.22- """23- exc_type, exc_value, tb = sys.exc_info()24-25- if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:26- exc_value.translated = True27- exc_value.source = source28-29- try:30- # Remove the old traceback on Python 3, otherwise the frames31- # from the compiler still show up.32- exc_value.with_traceback(None)33- except AttributeError:34- pass35-36- # Outside of runtime, so the frame isn't executing template37- # code, but it still needs to point at the template.38- tb = fake_traceback(39- exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno40- )41- else:42- # Skip the frame for the render function.43- tb = tb.tb_next44-45- stack = []46-47- # Build the stack of traceback object, replacing any in template48- # code with the source file and line information.49- while tb is not None:50- # Skip frames decorated with @internalcode. These are internal51- # calls that aren't useful in template debugging output.52- if tb.tb_frame.f_code in internal_code:53- tb = tb.tb_next54- continue55-56- template = tb.tb_frame.f_globals.get("__jinja_template__")57-58- if template is not None:59- lineno = template.get_corresponding_lineno(tb.tb_lineno)60- fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)61- stack.append(fake_tb)62- else:63- stack.append(tb)64-65- tb = tb.tb_next66-67- tb_next = None68-69- # Assign tb_next in reverse to avoid circular references.70- for tb in reversed(stack):71- tb_next = tb_set_next(tb, tb_next)72-73- return exc_type, exc_value, tb_next74-75-76-def fake_traceback(exc_value, tb, filename, lineno):77- """Produce a new traceback object that looks like it came from the78- template source instead of the compiled code. The filename, line79- number, and location name will point to the template, and the local80- variables will be the current template context.81-82- :param exc_value: The original exception to be re-raised to create83- the new traceback.84- :param tb: The original traceback to get the local variables and85- code info from.86- :param filename: The template filename.87- :param lineno: The line number in the template source.88- """89- if tb is not None:90- # Replace the real locals with the context that would be91- # available at that point in the template.92- locals = get_template_locals(tb.tb_frame.f_locals)93- locals.pop("__jinja_exception__", None)94- else:95- locals = {}96-97- globals = {98- "__name__": filename,99- "__file__": filename,100- "__jinja_exception__": exc_value,101- }102- # Raise an exception at the correct line number.103- code = compile("\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec")104-105- # Build a new code object that points to the template file and106- # replaces the location with a block name.107- try:108- location = "template"109-110- if tb is not None:111- function = tb.tb_frame.f_code.co_name112-113- if function == "root":114- location = "top-level template code"115- elif function.startswith("block_"):116- location = 'block "%s"' % function[6:]117-118- # Collect arguments for the new code object. CodeType only119- # accepts positional arguments, and arguments were inserted in120- # new Python versions.121- code_args = []122-123- for attr in (124- "argcount",125- "posonlyargcount", # Python 3.8126- "kwonlyargcount", # Python 3127- "nlocals",128- "stacksize",129- "flags",130- "code", # codestring131- "consts", # constants132- "names",133- "varnames",134- ("filename", filename),135- ("name", location),136- "firstlineno",137- "lnotab",138- "freevars",139- "cellvars",140- ):141- if isinstance(attr, tuple):142- # Replace with given value.143- code_args.append(attr[1])144- continue145-146- try:147- # Copy original value if it exists.148- code_args.append(getattr(code, "co_" + attr))149- except AttributeError:150- # Some arguments were added later.151- continue152-153- code = CodeType(*code_args)154- except Exception:155- # Some environments such as Google App Engine don't support156- # modifying code objects.157- pass158-159- # Execute the new code, which is guaranteed to raise, and return160- # the new traceback without this frame.161- try:162- exec(code, globals, locals)163- except BaseException:164- return sys.exc_info()[2].tb_next165-166-167-def get_template_locals(real_locals):168- """Based on the runtime locals, get the context that would be169- available at that point in the template.170- """171- # Start with the current template context.172- ctx = real_locals.get("context")173-174- if ctx:175- data = ctx.get_all().copy()176- else:177- data = {}178-179- # Might be in a derived context that only sets local variables180- # rather than pushing a context. Local variables follow the scheme181- # l_depth_name. Find the highest-depth local that has a value for182- # each name.183- local_overrides = {}184-185- for name, value in real_locals.items():186- if not name.startswith("l_") or value is missing:187- # Not a template variable, or no longer relevant.188- continue189-190- try:191- _, depth, name = name.split("_", 2)192- depth = int(depth)193- except ValueError:194- continue195-196- cur_depth = local_overrides.get(name, (-1,))[0]197-198- if cur_depth < depth:199- local_overrides[name] = (depth, value)200-201- # Modify the context with any derived context.202- for name, (_, value) in local_overrides.items():203- if value is missing:204- data.pop(name, None)205- else:206- data[name] = value207-208- return data209-210-211-if sys.version_info >= (3, 7):212- # tb_next is directly assignable as of Python 3.7213- def tb_set_next(tb, tb_next):214- tb.tb_next = tb_next215- return tb216-217-218-elif PYPY:219- # PyPy might have special support, and won't work with ctypes.220- try:221- import tputil222- except ImportError:223- # Without tproxy support, use the original traceback.224- def tb_set_next(tb, tb_next):225- return tb226-227- else:228- # With tproxy support, create a proxy around the traceback that229- # returns the new tb_next.230- def tb_set_next(tb, tb_next):231- def controller(op):232- if op.opname == "__getattribute__" and op.args[0] == "tb_next":233- return tb_next234-235- return op.delegate()236-237- return tputil.make_proxy(controller, obj=tb)238-239-240-else:241- # Use ctypes to assign tb_next at the C level since it's read-only242- # from Python.243- import ctypes244-245- class _CTraceback(ctypes.Structure):246- _fields_ = [247- # Extra PyObject slots when compiled with Py_TRACE_REFS.248- (249- "PyObject_HEAD",250- ctypes.c_byte * (32 if hasattr(sys, "getobjects") else 16),251- ),252- # Only care about tb_next as an object, not a traceback.253- ("tb_next", ctypes.py_object),254- ]255-256- def tb_set_next(tb, tb_next):257- c_tb = _CTraceback.from_address(id(tb))258-259- # Clear out the old tb_next.260- if tb.tb_next is not None:261- c_tb_next = ctypes.py_object(tb.tb_next)262- c_tb.tb_next = ctypes.py_object()263- ctypes.pythonapi.Py_DecRef(c_tb_next)264-265- # Assign the new tb_next.266- if tb_next is not None:267- c_tb_next = ctypes.py_object(tb_next)268- ctypes.pythonapi.Py_IncRef(c_tb_next)269- c_tb.tb_next = c_tb_next270-271- return tbdeleted:src/jinja2/defaults.py-47 removed
1-# -*- coding: utf-8 -*-2-from ._compat import range_type3-from .filters import FILTERS as DEFAULT_FILTERS # noqa: F4014-from .tests import TESTS as DEFAULT_TESTS # noqa: F4015-from .utils import Cycler6-from .utils import generate_lorem_ipsum7-from .utils import Joiner8-from .utils import Namespace9-10-# defaults for the parser / lexer11-BLOCK_START_STRING = "{%"12-BLOCK_END_STRING = "%}"13-VARIABLE_START_STRING = "{{"14-VARIABLE_END_STRING = "}}"15-COMMENT_START_STRING = "{#"16-COMMENT_END_STRING = "#}"17-LINE_STATEMENT_PREFIX = None18-LINE_COMMENT_PREFIX = None19-TRIM_BLOCKS = False20-LSTRIP_BLOCKS = False21-NEWLINE_SEQUENCE = "\n"22-KEEP_TRAILING_NEWLINE = False23-24-# default filters, tests and namespace25-26-DEFAULT_NAMESPACE = {27- "range": range_type,28- "dict": dict,29- "lipsum": generate_lorem_ipsum,30- "cycler": Cycler,31- "joiner": Joiner,32- "namespace": Namespace,33-}34-35-# default policies36-DEFAULT_POLICIES = {37- "compiler.ascii_str": True,38- "urlize.rel": "noopener",39- "urlize.target": None,40- "truncate.leeway": 5,41- "json.dumps_function": None,42- "json.dumps_kwargs": {"sort_keys": True},43- "ext.i18n.trimmed": False,44-}45-46-# export all constants47-__all__ = tuple(x for x in locals().keys() if x.isupper())deleted:src/jinja2/environment.py-1361 removed
1-# -*- coding: utf-8 -*-2-"""Classes for managing templates and their runtime and compile time3-options.4-"""5-import os6-import sys7-import weakref8-from functools import partial9-from functools import reduce10-11-from . import nodes12-from ._compat import encode_filename13-from ._compat import implements_iterator14-from ._compat import implements_to_string15-from ._compat import iteritems16-from ._compat import PY217-from ._compat import PYPY18-from ._compat import reraise19-from ._compat import string_types20-from ._compat import text_type21-from .compiler import CodeGenerator22-from .compiler import generate23-from .defaults import BLOCK_END_STRING24-from .defaults import BLOCK_START_STRING25-from .defaults import COMMENT_END_STRING26-from .defaults import COMMENT_START_STRING27-from .defaults import DEFAULT_FILTERS28-from .defaults import DEFAULT_NAMESPACE29-from .defaults import DEFAULT_POLICIES30-from .defaults import DEFAULT_TESTS31-from .defaults import KEEP_TRAILING_NEWLINE32-from .defaults import LINE_COMMENT_PREFIX33-from .defaults import LINE_STATEMENT_PREFIX34-from .defaults import LSTRIP_BLOCKS35-from .defaults import NEWLINE_SEQUENCE36-from .defaults import TRIM_BLOCKS37-from .defaults import VARIABLE_END_STRING38-from .defaults import VARIABLE_START_STRING39-from .exceptions import TemplateNotFound40-from .exceptions import TemplateRuntimeError41-from .exceptions import TemplatesNotFound42-from .exceptions import TemplateSyntaxError43-from .exceptions import UndefinedError44-from .lexer import get_lexer45-from .lexer import TokenStream46-from .nodes import EvalContext47-from .parser import Parser48-from .runtime import Context49-from .runtime import new_context50-from .runtime import Undefined51-from .utils import concat52-from .utils import consume53-from .utils import have_async_gen54-from .utils import import_string55-from .utils import internalcode56-from .utils import LRUCache57-from .utils import Markup58-from .utils import missing59-60-# for direct template usage we have up to ten living environments61-_spontaneous_environments = LRUCache(10)62-63-64-def get_spontaneous_environment(cls, *args):65- """Return a new spontaneous environment. A spontaneous environment66- is used for templates created directly rather than through an67- existing environment.68-69- :param cls: Environment class to create.70- :param args: Positional arguments passed to environment.71- """72- key = (cls, args)73-74- try:75- return _spontaneous_environments[key]76- except KeyError:77- _spontaneous_environments[key] = env = cls(*args)78- env.shared = True79- return env80-81-82-def create_cache(size):83- """Return the cache class for the given size."""84- if size == 0:85- return None86- if size < 0:87- return {}88- return LRUCache(size)89-90-91-def copy_cache(cache):92- """Create an empty copy of the given cache."""93- if cache is None:94- return None95- elif type(cache) is dict:96- return {}97- return LRUCache(cache.capacity)98-99-100-def load_extensions(environment, extensions):101- """Load the extensions from the list and bind it to the environment.102- Returns a dict of instantiated environments.103- """104- result = {}105- for extension in extensions:106- if isinstance(extension, string_types):107- extension = import_string(extension)108- result[extension.identifier] = extension(environment)109- return result110-111-112-def fail_for_missing_callable(string, name):113- msg = string % name114- if isinstance(name, Undefined):115- try:116- name._fail_with_undefined_error()117- except Exception as e:118- msg = "%s (%s; did you forget to quote the callable name?)" % (msg, e)119- raise TemplateRuntimeError(msg)120-121-122-def _environment_sanity_check(environment):123- """Perform a sanity check on the environment."""124- assert issubclass(125- environment.undefined, Undefined126- ), "undefined must be a subclass of undefined because filters depend on it."127- assert (128- environment.block_start_string129- != environment.variable_start_string130- != environment.comment_start_string131- ), "block, variable and comment start strings must be different"132- assert environment.newline_sequence in (133- "\r",134- "\r\n",135- "\n",136- ), "newline_sequence set to unknown line ending string."137- return environment138-139-140-class Environment(object):141- r"""The core component of Jinja is the `Environment`. It contains142- important shared variables like configuration, filters, tests,143- globals and others. Instances of this class may be modified if144- they are not shared and if no template was loaded so far.145- Modifications on environments after the first template was loaded146- will lead to surprising effects and undefined behavior.147-148- Here are the possible initialization parameters:149-150- `block_start_string`151- The string marking the beginning of a block. Defaults to ``'{%'``.152-153- `block_end_string`154- The string marking the end of a block. Defaults to ``'%}'``.155-156- `variable_start_string`157- The string marking the beginning of a print statement.158- Defaults to ``'{{'``.159-160- `variable_end_string`161- The string marking the end of a print statement. Defaults to162- ``'}}'``.163-164- `comment_start_string`165- The string marking the beginning of a comment. Defaults to ``'{#'``.166-167- `comment_end_string`168- The string marking the end of a comment. Defaults to ``'#}'``.169-170- `line_statement_prefix`171- If given and a string, this will be used as prefix for line based172- statements. See also :ref:`line-statements`.173-174- `line_comment_prefix`175- If given and a string, this will be used as prefix for line based176- comments. See also :ref:`line-statements`.177-178- .. versionadded:: 2.2179-180- `trim_blocks`181- If this is set to ``True`` the first newline after a block is182- removed (block, not variable tag!). Defaults to `False`.183-184- `lstrip_blocks`185- If this is set to ``True`` leading spaces and tabs are stripped186- from the start of a line to a block. Defaults to `False`.187-188- `newline_sequence`189- The sequence that starts a newline. Must be one of ``'\r'``,190- ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a191- useful default for Linux and OS X systems as well as web192- applications.193-194- `keep_trailing_newline`195- Preserve the trailing newline when rendering templates.196- The default is ``False``, which causes a single newline,197- if present, to be stripped from the end of the template.198-199- .. versionadded:: 2.7200-201- `extensions`202- List of Jinja extensions to use. This can either be import paths203- as strings or extension classes. For more information have a204- look at :ref:`the extensions documentation <jinja-extensions>`.205-206- `optimized`207- should the optimizer be enabled? Default is ``True``.208-209- `undefined`210- :class:`Undefined` or a subclass of it that is used to represent211- undefined values in the template.212-213- `finalize`214- A callable that can be used to process the result of a variable215- expression before it is output. For example one can convert216- ``None`` implicitly into an empty string here.217-218- `autoescape`219- If set to ``True`` the XML/HTML autoescaping feature is enabled by220- default. For more details about autoescaping see221- :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also222- be a callable that is passed the template name and has to223- return ``True`` or ``False`` depending on autoescape should be224- enabled by default.225-226- .. versionchanged:: 2.4227- `autoescape` can now be a function228-229- `loader`230- The template loader for this environment.231-232- `cache_size`233- The size of the cache. Per default this is ``400`` which means234- that if more than 400 templates are loaded the loader will clean235- out the least recently used template. If the cache size is set to236- ``0`` templates are recompiled all the time, if the cache size is237- ``-1`` the cache will not be cleaned.238-239- .. versionchanged:: 2.8240- The cache size was increased to 400 from a low 50.241-242- `auto_reload`243- Some loaders load templates from locations where the template244- sources may change (ie: file system or database). If245- ``auto_reload`` is set to ``True`` (default) every time a template is246- requested the loader checks if the source changed and if yes, it247- will reload the template. For higher performance it's possible to248- disable that.249-250- `bytecode_cache`251- If set to a bytecode cache object, this object will provide a252- cache for the internal Jinja bytecode so that templates don't253- have to be parsed if they were not changed.254-255- See :ref:`bytecode-cache` for more information.256-257- `enable_async`258- If set to true this enables async template execution which allows259- you to take advantage of newer Python features. This requires260- Python 3.6 or later.261- """262-263- #: if this environment is sandboxed. Modifying this variable won't make264- #: the environment sandboxed though. For a real sandboxed environment265- #: have a look at jinja2.sandbox. This flag alone controls the code266- #: generation by the compiler.267- sandboxed = False268-269- #: True if the environment is just an overlay270- overlayed = False271-272- #: the environment this environment is linked to if it is an overlay273- linked_to = None274-275- #: shared environments have this set to `True`. A shared environment276- #: must not be modified277- shared = False278-279- #: the class that is used for code generation. See280- #: :class:`~jinja2.compiler.CodeGenerator` for more information.281- code_generator_class = CodeGenerator282-283- #: the context class thatis used for templates. See284- #: :class:`~jinja2.runtime.Context` for more information.285- context_class = Context286-287- def __init__(288- self,289- block_start_string=BLOCK_START_STRING,290- block_end_string=BLOCK_END_STRING,291- variable_start_string=VARIABLE_START_STRING,292- variable_end_string=VARIABLE_END_STRING,293- comment_start_string=COMMENT_START_STRING,294- comment_end_string=COMMENT_END_STRING,295- line_statement_prefix=LINE_STATEMENT_PREFIX,296- line_comment_prefix=LINE_COMMENT_PREFIX,297- trim_blocks=TRIM_BLOCKS,298- lstrip_blocks=LSTRIP_BLOCKS,299- newline_sequence=NEWLINE_SEQUENCE,300- keep_trailing_newline=KEEP_TRAILING_NEWLINE,301- extensions=(),302- optimized=True,303- undefined=Undefined,304- finalize=None,305- autoescape=False,306- loader=None,307- cache_size=400,308- auto_reload=True,309- bytecode_cache=None,310- enable_async=False,311- ):312- # !!Important notice!!313- # The constructor accepts quite a few arguments that should be314- # passed by keyword rather than position. However it's important to315- # not change the order of arguments because it's used at least316- # internally in those cases:317- # - spontaneous environments (i18n extension and Template)318- # - unittests319- # If parameter changes are required only add parameters at the end320- # and don't change the arguments (or the defaults!) of the arguments321- # existing already.322-323- # lexer / parser information324- self.block_start_string = block_start_string325- self.block_end_string = block_end_string326- self.variable_start_string = variable_start_string327- self.variable_end_string = variable_end_string328- self.comment_start_string = comment_start_string329- self.comment_end_string = comment_end_string330- self.line_statement_prefix = line_statement_prefix331- self.line_comment_prefix = line_comment_prefix332- self.trim_blocks = trim_blocks333- self.lstrip_blocks = lstrip_blocks334- self.newline_sequence = newline_sequence335- self.keep_trailing_newline = keep_trailing_newline336-337- # runtime information338- self.undefined = undefined339- self.optimized = optimized340- self.finalize = finalize341- self.autoescape = autoescape342-343- # defaults344- self.filters = DEFAULT_FILTERS.copy()345- self.tests = DEFAULT_TESTS.copy()346- self.globals = DEFAULT_NAMESPACE.copy()347-348- # set the loader provided349- self.loader = loader350- self.cache = create_cache(cache_size)351- self.bytecode_cache = bytecode_cache352- self.auto_reload = auto_reload353-354- # configurable policies355- self.policies = DEFAULT_POLICIES.copy()356-357- # load extensions358- self.extensions = load_extensions(self, extensions)359-360- self.enable_async = enable_async361- self.is_async = self.enable_async and have_async_gen362- if self.is_async:363- # runs patch_all() to enable async support364- from . import asyncsupport # noqa: F401365-366- _environment_sanity_check(self)367-368- def add_extension(self, extension):369- """Adds an extension after the environment was created.370-371- .. versionadded:: 2.5372- """373- self.extensions.update(load_extensions(self, [extension]))374-375- def extend(self, **attributes):376- """Add the items to the instance of the environment if they do not exist377- yet. This is used by :ref:`extensions <writing-extensions>` to register378- callbacks and configuration values without breaking inheritance.379- """380- for key, value in iteritems(attributes):381- if not hasattr(self, key):382- setattr(self, key, value)383-384- def overlay(385- self,386- block_start_string=missing,387- block_end_string=missing,388- variable_start_string=missing,389- variable_end_string=missing,390- comment_start_string=missing,391- comment_end_string=missing,392- line_statement_prefix=missing,393- line_comment_prefix=missing,394- trim_blocks=missing,395- lstrip_blocks=missing,396- extensions=missing,397- optimized=missing,398- undefined=missing,399- finalize=missing,400- autoescape=missing,401- loader=missing,402- cache_size=missing,403- auto_reload=missing,404- bytecode_cache=missing,405- ):406- """Create a new overlay environment that shares all the data with the407- current environment except for cache and the overridden attributes.408- Extensions cannot be removed for an overlayed environment. An overlayed409- environment automatically gets all the extensions of the environment it410- is linked to plus optional extra extensions.411-412- Creating overlays should happen after the initial environment was set413- up completely. Not all attributes are truly linked, some are just414- copied over so modifications on the original environment may not shine415- through.416- """417- args = dict(locals())418- del args["self"], args["cache_size"], args["extensions"]419-420- rv = object.__new__(self.__class__)421- rv.__dict__.update(self.__dict__)422- rv.overlayed = True423- rv.linked_to = self424-425- for key, value in iteritems(args):426- if value is not missing:427- setattr(rv, key, value)428-429- if cache_size is not missing:430- rv.cache = create_cache(cache_size)431- else:432- rv.cache = copy_cache(self.cache)433-434- rv.extensions = {}435- for key, value in iteritems(self.extensions):436- rv.extensions[key] = value.bind(rv)437- if extensions is not missing:438- rv.extensions.update(load_extensions(rv, extensions))439-440- return _environment_sanity_check(rv)441-442- lexer = property(get_lexer, doc="The lexer for this environment.")443-444- def iter_extensions(self):445- """Iterates over the extensions by priority."""446- return iter(sorted(self.extensions.values(), key=lambda x: x.priority))447-448- def getitem(self, obj, argument):449- """Get an item or attribute of an object but prefer the item."""450- try:451- return obj[argument]452- except (AttributeError, TypeError, LookupError):453- if isinstance(argument, string_types):454- try:455- attr = str(argument)456- except Exception:457- pass458- else:459- try:460- return getattr(obj, attr)461- except AttributeError:462- pass463- return self.undefined(obj=obj, name=argument)464-465- def getattr(self, obj, attribute):466- """Get an item or attribute of an object but prefer the attribute.467- Unlike :meth:`getitem` the attribute *must* be a bytestring.468- """469- try:470- return getattr(obj, attribute)471- except AttributeError:472- pass473- try:474- return obj[attribute]475- except (TypeError, LookupError, AttributeError):476- return self.undefined(obj=obj, name=attribute)477-478- def call_filter(479- self, name, value, args=None, kwargs=None, context=None, eval_ctx=None480- ):481- """Invokes a filter on a value the same way the compiler does it.482-483- Note that on Python 3 this might return a coroutine in case the484- filter is running from an environment in async mode and the filter485- supports async execution. It's your responsibility to await this486- if needed.487-488- .. versionadded:: 2.7489- """490- func = self.filters.get(name)491- if func is None:492- fail_for_missing_callable("no filter named %r", name)493- args = [value] + list(args or ())494- if getattr(func, "contextfilter", False):495- if context is None:496- raise TemplateRuntimeError(497- "Attempted to invoke context filter without context"498- )499- args.insert(0, context)500- elif getattr(func, "evalcontextfilter", False):501- if eval_ctx is None:502- if context is not None:503- eval_ctx = context.eval_ctx504- else:505- eval_ctx = EvalContext(self)506- args.insert(0, eval_ctx)507- elif getattr(func, "environmentfilter", False):508- args.insert(0, self)509- return func(*args, **(kwargs or {}))510-511- def call_test(self, name, value, args=None, kwargs=None):512- """Invokes a test on a value the same way the compiler does it.513-514- .. versionadded:: 2.7515- """516- func = self.tests.get(name)517- if func is None:518- fail_for_missing_callable("no test named %r", name)519- return func(value, *(args or ()), **(kwargs or {}))520-521- @internalcode522- def parse(self, source, name=None, filename=None):523- """Parse the sourcecode and return the abstract syntax tree. This524- tree of nodes is used by the compiler to convert the template into525- executable source- or bytecode. This is useful for debugging or to526- extract information from templates.527-528- If you are :ref:`developing Jinja extensions <writing-extensions>`529- this gives you a good overview of the node tree generated.530- """531- try:532- return self._parse(source, name, filename)533- except TemplateSyntaxError:534- self.handle_exception(source=source)535-536- def _parse(self, source, name, filename):537- """Internal parsing function used by `parse` and `compile`."""538- return Parser(self, source, name, encode_filename(filename)).parse()539-540- def lex(self, source, name=None, filename=None):541- """Lex the given sourcecode and return a generator that yields542- tokens as tuples in the form ``(lineno, token_type, value)``.543- This can be useful for :ref:`extension development <writing-extensions>`544- and debugging templates.545-546- This does not perform preprocessing. If you want the preprocessing547- of the extensions to be applied you have to filter source through548- the :meth:`preprocess` method.549- """550- source = text_type(source)551- try:552- return self.lexer.tokeniter(source, name, filename)553- except TemplateSyntaxError:554- self.handle_exception(source=source)555-556- def preprocess(self, source, name=None, filename=None):557- """Preprocesses the source with all extensions. This is automatically558- called for all parsing and compiling methods but *not* for :meth:`lex`559- because there you usually only want the actual source tokenized.560- """561- return reduce(562- lambda s, e: e.preprocess(s, name, filename),563- self.iter_extensions(),564- text_type(source),565- )566-567- def _tokenize(self, source, name, filename=None, state=None):568- """Called by the parser to do the preprocessing and filtering569- for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.570- """571- source = self.preprocess(source, name, filename)572- stream = self.lexer.tokenize(source, name, filename, state)573- for ext in self.iter_extensions():574- stream = ext.filter_stream(stream)575- if not isinstance(stream, TokenStream):576- stream = TokenStream(stream, name, filename)577- return stream578-579- def _generate(self, source, name, filename, defer_init=False):580- """Internal hook that can be overridden to hook a different generate581- method in.582-583- .. versionadded:: 2.5584- """585- return generate(586- source,587- self,588- name,589- filename,590- defer_init=defer_init,591- optimized=self.optimized,592- )593-594- def _compile(self, source, filename):595- """Internal hook that can be overridden to hook a different compile596- method in.597-598- .. versionadded:: 2.5599- """600- return compile(source, filename, "exec")601-602- @internalcode603- def compile(self, source, name=None, filename=None, raw=False, defer_init=False):604- """Compile a node or template source code. The `name` parameter is605- the load name of the template after it was joined using606- :meth:`join_path` if necessary, not the filename on the file system.607- the `filename` parameter is the estimated filename of the template on608- the file system. If the template came from a database or memory this609- can be omitted.610-611- The return value of this method is a python code object. If the `raw`612- parameter is `True` the return value will be a string with python613- code equivalent to the bytecode returned otherwise. This method is614- mainly used internally.615-616- `defer_init` is use internally to aid the module code generator. This617- causes the generated code to be able to import without the global618- environment variable to be set.619-620- .. versionadded:: 2.4621- `defer_init` parameter added.622- """623- source_hint = None624- try:625- if isinstance(source, string_types):626- source_hint = source627- source = self._parse(source, name, filename)628- source = self._generate(source, name, filename, defer_init=defer_init)629- if raw:630- return source631- if filename is None:632- filename = "<template>"633- else:634- filename = encode_filename(filename)635- return self._compile(source, filename)636- except TemplateSyntaxError:637- self.handle_exception(source=source_hint)638-639- def compile_expression(self, source, undefined_to_none=True):640- """A handy helper method that returns a callable that accepts keyword641- arguments that appear as variables in the expression. If called it642- returns the result of the expression.643-644- This is useful if applications want to use the same rules as Jinja645- in template "configuration files" or similar situations.646-647- Example usage:648-649- >>> env = Environment()650- >>> expr = env.compile_expression('foo == 42')651- >>> expr(foo=23)652- False653- >>> expr(foo=42)654- True655-656- Per default the return value is converted to `None` if the657- expression returns an undefined value. This can be changed658- by setting `undefined_to_none` to `False`.659-660- >>> env.compile_expression('var')() is None661- True662- >>> env.compile_expression('var', undefined_to_none=False)()663- Undefined664-665- .. versionadded:: 2.1666- """667- parser = Parser(self, source, state="variable")668- try:669- expr = parser.parse_expression()670- if not parser.stream.eos:671- raise TemplateSyntaxError(672- "chunk after expression", parser.stream.current.lineno, None, None673- )674- expr.set_environment(self)675- except TemplateSyntaxError:676- if sys.exc_info() is not None:677- self.handle_exception(source=source)678-679- body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]680- template = self.from_string(nodes.Template(body, lineno=1))681- return TemplateExpression(template, undefined_to_none)682-683- def compile_templates(684- self,685- target,686- extensions=None,687- filter_func=None,688- zip="deflated",689- log_function=None,690- ignore_errors=True,691- py_compile=False,692- ):693- """Finds all the templates the loader can find, compiles them694- and stores them in `target`. If `zip` is `None`, instead of in a695- zipfile, the templates will be stored in a directory.696- By default a deflate zip algorithm is used. To switch to697- the stored algorithm, `zip` can be set to ``'stored'``.698-699- `extensions` and `filter_func` are passed to :meth:`list_templates`.700- Each template returned will be compiled to the target folder or701- zipfile.702-703- By default template compilation errors are ignored. In case a704- log function is provided, errors are logged. If you want template705- syntax errors to abort the compilation you can set `ignore_errors`706- to `False` and you will get an exception on syntax errors.707-708- If `py_compile` is set to `True` .pyc files will be written to the709- target instead of standard .py files. This flag does not do anything710- on pypy and Python 3 where pyc files are not picked up by itself and711- don't give much benefit.712-713- .. versionadded:: 2.4714- """715- from .loaders import ModuleLoader716-717- if log_function is None:718-719- def log_function(x):720- pass721-722- if py_compile:723- if not PY2 or PYPY:724- import warnings725-726- warnings.warn(727- "'py_compile=True' has no effect on PyPy or Python"728- " 3 and will be removed in version 3.0",729- DeprecationWarning,730- stacklevel=2,731- )732- py_compile = False733- else:734- import imp735- import marshal736-737- py_header = imp.get_magic() + u"\xff\xff\xff\xff".encode("iso-8859-15")738-739- # Python 3.3 added a source filesize to the header740- if sys.version_info >= (3, 3):741- py_header += u"\x00\x00\x00\x00".encode("iso-8859-15")742-743- def write_file(filename, data):744- if zip:745- info = ZipInfo(filename)746- info.external_attr = 0o755 << 16747- zip_file.writestr(info, data)748- else:749- if isinstance(data, text_type):750- data = data.encode("utf8")751-752- with open(os.path.join(target, filename), "wb") as f:753- f.write(data)754-755- if zip is not None:756- from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED757-758- zip_file = ZipFile(759- target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]760- )761- log_function('Compiling into Zip archive "%s"' % target)762- else:763- if not os.path.isdir(target):764- os.makedirs(target)765- log_function('Compiling into folder "%s"' % target)766-767- try:768- for name in self.list_templates(extensions, filter_func):769- source, filename, _ = self.loader.get_source(self, name)770- try:771- code = self.compile(source, name, filename, True, True)772- except TemplateSyntaxError as e:773- if not ignore_errors:774- raise775- log_function('Could not compile "%s": %s' % (name, e))776- continue777-778- filename = ModuleLoader.get_module_filename(name)779-780- if py_compile:781- c = self._compile(code, encode_filename(filename))782- write_file(filename + "c", py_header + marshal.dumps(c))783- log_function('Byte-compiled "%s" as %s' % (name, filename + "c"))784- else:785- write_file(filename, code)786- log_function('Compiled "%s" as %s' % (name, filename))787- finally:788- if zip:789- zip_file.close()790-791- log_function("Finished compiling templates")792-793- def list_templates(self, extensions=None, filter_func=None):794- """Returns a list of templates for this environment. This requires795- that the loader supports the loader's796- :meth:`~BaseLoader.list_templates` method.797-798- If there are other files in the template folder besides the799- actual templates, the returned list can be filtered. There are two800- ways: either `extensions` is set to a list of file extensions for801- templates, or a `filter_func` can be provided which is a callable that802- is passed a template name and should return `True` if it should end up803- in the result list.804-805- If the loader does not support that, a :exc:`TypeError` is raised.806-807- .. versionadded:: 2.4808- """809- names = self.loader.list_templates()810-811- if extensions is not None:812- if filter_func is not None:813- raise TypeError(814- "either extensions or filter_func can be passed, but not both"815- )816-817- def filter_func(x):818- return "." in x and x.rsplit(".", 1)[1] in extensions819-820- if filter_func is not None:821- names = [name for name in names if filter_func(name)]822-823- return names824-825- def handle_exception(self, source=None):826- """Exception handling helper. This is used internally to either raise827- rewritten exceptions or return a rendered traceback for the template.828- """829- from .debug import rewrite_traceback_stack830-831- reraise(*rewrite_traceback_stack(source=source))832-833- def join_path(self, template, parent):834- """Join a template with the parent. By default all the lookups are835- relative to the loader root so this method returns the `template`836- parameter unchanged, but if the paths should be relative to the837- parent template, this function can be used to calculate the real838- template name.839-840- Subclasses may override this method and implement template path841- joining here.842- """843- return template844-845- @internalcode846- def _load_template(self, name, globals):847- if self.loader is None:848- raise TypeError("no loader for this environment specified")849- cache_key = (weakref.ref(self.loader), name)850- if self.cache is not None:851- template = self.cache.get(cache_key)852- if template is not None and (853- not self.auto_reload or template.is_up_to_date854- ):855- return template856- template = self.loader.load(self, name, globals)857- if self.cache is not None:858- self.cache[cache_key] = template859- return template860-861- @internalcode862- def get_template(self, name, parent=None, globals=None):863- """Load a template from the loader. If a loader is configured this864- method asks the loader for the template and returns a :class:`Template`.865- If the `parent` parameter is not `None`, :meth:`join_path` is called866- to get the real template name before loading.867-868- The `globals` parameter can be used to provide template wide globals.869- These variables are available in the context at render time.870-871- If the template does not exist a :exc:`TemplateNotFound` exception is872- raised.873-874- .. versionchanged:: 2.4875- If `name` is a :class:`Template` object it is returned from the876- function unchanged.877- """878- if isinstance(name, Template):879- return name880- if parent is not None:881- name = self.join_path(name, parent)882- return self._load_template(name, self.make_globals(globals))883-884- @internalcode885- def select_template(self, names, parent=None, globals=None):886- """Works like :meth:`get_template` but tries a number of templates887- before it fails. If it cannot find any of the templates, it will888- raise a :exc:`TemplatesNotFound` exception.889-890- .. versionchanged:: 2.11891- If names is :class:`Undefined`, an :exc:`UndefinedError` is892- raised instead. If no templates were found and names893- contains :class:`Undefined`, the message is more helpful.894-895- .. versionchanged:: 2.4896- If `names` contains a :class:`Template` object it is returned897- from the function unchanged.898-899- .. versionadded:: 2.3900- """901- if isinstance(names, Undefined):902- names._fail_with_undefined_error()903-904- if not names:905- raise TemplatesNotFound(906- message=u"Tried to select from an empty list " u"of templates."907- )908- globals = self.make_globals(globals)909- for name in names:910- if isinstance(name, Template):911- return name912- if parent is not None:913- name = self.join_path(name, parent)914- try:915- return self._load_template(name, globals)916- except (TemplateNotFound, UndefinedError):917- pass918- raise TemplatesNotFound(names)919-920- @internalcode921- def get_or_select_template(self, template_name_or_list, parent=None, globals=None):922- """Does a typecheck and dispatches to :meth:`select_template`923- if an iterable of template names is given, otherwise to924- :meth:`get_template`.925-926- .. versionadded:: 2.3927- """928- if isinstance(template_name_or_list, (string_types, Undefined)):929- return self.get_template(template_name_or_list, parent, globals)930- elif isinstance(template_name_or_list, Template):931- return template_name_or_list932- return self.select_template(template_name_or_list, parent, globals)933-934- def from_string(self, source, globals=None, template_class=None):935- """Load a template from a string. This parses the source given and936- returns a :class:`Template` object.937- """938- globals = self.make_globals(globals)939- cls = template_class or self.template_class940- return cls.from_code(self, self.compile(source), globals, None)941-942- def make_globals(self, d):943- """Return a dict for the globals."""944- if not d:945- return self.globals946- return dict(self.globals, **d)947-948-949-class Template(object):950- """The central template object. This class represents a compiled template951- and is used to evaluate it.952-953- Normally the template object is generated from an :class:`Environment` but954- it also has a constructor that makes it possible to create a template955- instance directly using the constructor. It takes the same arguments as956- the environment constructor but it's not possible to specify a loader.957-958- Every template object has a few methods and members that are guaranteed959- to exist. However it's important that a template object should be960- considered immutable. Modifications on the object are not supported.961-962- Template objects created from the constructor rather than an environment963- do have an `environment` attribute that points to a temporary environment964- that is probably shared with other templates created with the constructor965- and compatible settings.966-967- >>> template = Template('Hello {{ name }}!')968- >>> template.render(name='John Doe') == u'Hello John Doe!'969- True970- >>> stream = template.stream(name='John Doe')971- >>> next(stream) == u'Hello John Doe!'972- True973- >>> next(stream)974- Traceback (most recent call last):975- ...976- StopIteration977- """978-979- #: Type of environment to create when creating a template directly980- #: rather than through an existing environment.981- environment_class = Environment982-983- def __new__(984- cls,985- source,986- block_start_string=BLOCK_START_STRING,987- block_end_string=BLOCK_END_STRING,988- variable_start_string=VARIABLE_START_STRING,989- variable_end_string=VARIABLE_END_STRING,990- comment_start_string=COMMENT_START_STRING,991- comment_end_string=COMMENT_END_STRING,992- line_statement_prefix=LINE_STATEMENT_PREFIX,993- line_comment_prefix=LINE_COMMENT_PREFIX,994- trim_blocks=TRIM_BLOCKS,995- lstrip_blocks=LSTRIP_BLOCKS,996- newline_sequence=NEWLINE_SEQUENCE,997- keep_trailing_newline=KEEP_TRAILING_NEWLINE,998- extensions=(),999- optimized=True,1000- undefined=Undefined,1001- finalize=None,1002- autoescape=False,1003- enable_async=False,1004- ):1005- env = get_spontaneous_environment(1006- cls.environment_class,1007- block_start_string,1008- block_end_string,1009- variable_start_string,1010- variable_end_string,1011- comment_start_string,1012- comment_end_string,1013- line_statement_prefix,1014- line_comment_prefix,1015- trim_blocks,1016- lstrip_blocks,1017- newline_sequence,1018- keep_trailing_newline,1019- frozenset(extensions),1020- optimized,1021- undefined,1022- finalize,1023- autoescape,1024- None,1025- 0,1026- False,1027- None,1028- enable_async,1029- )1030- return env.from_string(source, template_class=cls)1031-1032- @classmethod1033- def from_code(cls, environment, code, globals, uptodate=None):1034- """Creates a template object from compiled code and the globals. This1035- is used by the loaders and environment to create a template object.1036- """1037- namespace = {"environment": environment, "__file__": code.co_filename}1038- exec(code, namespace)1039- rv = cls._from_namespace(environment, namespace, globals)1040- rv._uptodate = uptodate1041- return rv1042-1043- @classmethod1044- def from_module_dict(cls, environment, module_dict, globals):1045- """Creates a template object from a module. This is used by the1046- module loader to create a template object.1047-1048- .. versionadded:: 2.41049- """1050- return cls._from_namespace(environment, module_dict, globals)1051-1052- @classmethod1053- def _from_namespace(cls, environment, namespace, globals):1054- t = object.__new__(cls)1055- t.environment = environment1056- t.globals = globals1057- t.name = namespace["name"]1058- t.filename = namespace["__file__"]1059- t.blocks = namespace["blocks"]1060-1061- # render function and module1062- t.root_render_func = namespace["root"]1063- t._module = None1064-1065- # debug and loader helpers1066- t._debug_info = namespace["debug_info"]1067- t._uptodate = None1068-1069- # store the reference1070- namespace["environment"] = environment1071- namespace["__jinja_template__"] = t1072-1073- return t1074-1075- def render(self, *args, **kwargs):1076- """This method accepts the same arguments as the `dict` constructor:1077- A dict, a dict subclass or some keyword arguments. If no arguments1078- are given the context will be empty. These two calls do the same::1079-1080- template.render(knights='that say nih')1081- template.render({'knights': 'that say nih'})1082-1083- This will return the rendered template as unicode string.1084- """1085- vars = dict(*args, **kwargs)1086- try:1087- return concat(self.root_render_func(self.new_context(vars)))1088- except Exception:1089- self.environment.handle_exception()1090-1091- def render_async(self, *args, **kwargs):1092- """This works similar to :meth:`render` but returns a coroutine1093- that when awaited returns the entire rendered template string. This1094- requires the async feature to be enabled.1095-1096- Example usage::1097-1098- await template.render_async(knights='that say nih; asynchronously')1099- """1100- # see asyncsupport for the actual implementation1101- raise NotImplementedError(1102- "This feature is not available for this version of Python"1103- )1104-1105- def stream(self, *args, **kwargs):1106- """Works exactly like :meth:`generate` but returns a1107- :class:`TemplateStream`.1108- """1109- return TemplateStream(self.generate(*args, **kwargs))1110-1111- def generate(self, *args, **kwargs):1112- """For very large templates it can be useful to not render the whole1113- template at once but evaluate each statement after another and yield1114- piece for piece. This method basically does exactly that and returns1115- a generator that yields one item after another as unicode strings.1116-1117- It accepts the same arguments as :meth:`render`.1118- """1119- vars = dict(*args, **kwargs)1120- try:1121- for event in self.root_render_func(self.new_context(vars)):1122- yield event1123- except Exception:1124- yield self.environment.handle_exception()1125-1126- def generate_async(self, *args, **kwargs):1127- """An async version of :meth:`generate`. Works very similarly but1128- returns an async iterator instead.1129- """1130- # see asyncsupport for the actual implementation1131- raise NotImplementedError(1132- "This feature is not available for this version of Python"1133- )1134-1135- def new_context(self, vars=None, shared=False, locals=None):1136- """Create a new :class:`Context` for this template. The vars1137- provided will be passed to the template. Per default the globals1138- are added to the context. If shared is set to `True` the data1139- is passed as is to the context without adding the globals.1140-1141- `locals` can be a dict of local variables for internal usage.1142- """1143- return new_context(1144- self.environment, self.name, self.blocks, vars, shared, self.globals, locals1145- )1146-1147- def make_module(self, vars=None, shared=False, locals=None):1148- """This method works like the :attr:`module` attribute when called1149- without arguments but it will evaluate the template on every call1150- rather than caching it. It's also possible to provide1151- a dict which is then used as context. The arguments are the same1152- as for the :meth:`new_context` method.1153- """1154- return TemplateModule(self, self.new_context(vars, shared, locals))1155-1156- def make_module_async(self, vars=None, shared=False, locals=None):1157- """As template module creation can invoke template code for1158- asynchronous executions this method must be used instead of the1159- normal :meth:`make_module` one. Likewise the module attribute1160- becomes unavailable in async mode.1161- """1162- # see asyncsupport for the actual implementation1163- raise NotImplementedError(1164- "This feature is not available for this version of Python"1165- )1166-1167- @internalcode1168- def _get_default_module(self):1169- if self._module is not None:1170- return self._module1171- self._module = rv = self.make_module()1172- return rv1173-1174- @property1175- def module(self):1176- """The template as module. This is used for imports in the1177- template runtime but is also useful if one wants to access1178- exported template variables from the Python layer:1179-1180- >>> t = Template('{% macro foo() %}42{% endmacro %}23')1181- >>> str(t.module)1182- '23'1183- >>> t.module.foo() == u'42'1184- True1185-1186- This attribute is not available if async mode is enabled.1187- """1188- return self._get_default_module()1189-1190- def get_corresponding_lineno(self, lineno):1191- """Return the source line number of a line number in the1192- generated bytecode as they are not in sync.1193- """1194- for template_line, code_line in reversed(self.debug_info):1195- if code_line <= lineno:1196- return template_line1197- return 11198-1199- @property1200- def is_up_to_date(self):1201- """If this variable is `False` there is a newer version available."""1202- if self._uptodate is None:1203- return True1204- return self._uptodate()1205-1206- @property1207- def debug_info(self):1208- """The debug info mapping."""1209- if self._debug_info:1210- return [tuple(map(int, x.split("="))) for x in self._debug_info.split("&")]1211- return []1212-1213- def __repr__(self):1214- if self.name is None:1215- name = "memory:%x" % id(self)1216- else:1217- name = repr(self.name)1218- return "<%s %s>" % (self.__class__.__name__, name)1219-1220-1221-@implements_to_string1222-class TemplateModule(object):1223- """Represents an imported template. All the exported names of the1224- template are available as attributes on this object. Additionally1225- converting it into an unicode- or bytestrings renders the contents.1226- """1227-1228- def __init__(self, template, context, body_stream=None):1229- if body_stream is None:1230- if context.environment.is_async:1231- raise RuntimeError(1232- "Async mode requires a body stream "1233- "to be passed to a template module. Use "1234- "the async methods of the API you are "1235- "using."1236- )1237- body_stream = list(template.root_render_func(context))1238- self._body_stream = body_stream1239- self.__dict__.update(context.get_exported())1240- self.__name__ = template.name1241-1242- def __html__(self):1243- return Markup(concat(self._body_stream))1244-1245- def __str__(self):1246- return concat(self._body_stream)1247-1248- def __repr__(self):1249- if self.__name__ is None:1250- name = "memory:%x" % id(self)1251- else:1252- name = repr(self.__name__)1253- return "<%s %s>" % (self.__class__.__name__, name)1254-1255-1256-class TemplateExpression(object):1257- """The :meth:`jinja2.Environment.compile_expression` method returns an1258- instance of this object. It encapsulates the expression-like access1259- to the template with an expression it wraps.1260- """1261-1262- def __init__(self, template, undefined_to_none):1263- self._template = template1264- self._undefined_to_none = undefined_to_none1265-1266- def __call__(self, *args, **kwargs):1267- context = self._template.new_context(dict(*args, **kwargs))1268- consume(self._template.root_render_func(context))1269- rv = context.vars["result"]1270- if self._undefined_to_none and isinstance(rv, Undefined):1271- rv = None1272- return rv1273-1274-1275-@implements_iterator1276-class TemplateStream(object):1277- """A template stream works pretty much like an ordinary python generator1278- but it can buffer multiple items to reduce the number of total iterations.1279- Per default the output is unbuffered which means that for every unbuffered1280- instruction in the template one unicode string is yielded.1281-1282- If buffering is enabled with a buffer size of 5, five items are combined1283- into a new unicode string. This is mainly useful if you are streaming1284- big templates to a client via WSGI which flushes after each iteration.1285- """1286-1287- def __init__(self, gen):1288- self._gen = gen1289- self.disable_buffering()1290-1291- def dump(self, fp, encoding=None, errors="strict"):1292- """Dump the complete stream into a file or file-like object.1293- Per default unicode strings are written, if you want to encode1294- before writing specify an `encoding`.1295-1296- Example usage::1297-1298- Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1299- """1300- close = False1301- if isinstance(fp, string_types):1302- if encoding is None:1303- encoding = "utf-8"1304- fp = open(fp, "wb")1305- close = True1306- try:1307- if encoding is not None:1308- iterable = (x.encode(encoding, errors) for x in self)1309- else:1310- iterable = self1311- if hasattr(fp, "writelines"):1312- fp.writelines(iterable)1313- else:1314- for item in iterable:1315- fp.write(item)1316- finally:1317- if close:1318- fp.close()1319-1320- def disable_buffering(self):1321- """Disable the output buffering."""1322- self._next = partial(next, self._gen)1323- self.buffered = False1324-1325- def _buffered_generator(self, size):1326- buf = []1327- c_size = 01328- push = buf.append1329-1330- while 1:1331- try:1332- while c_size < size:1333- c = next(self._gen)1334- push(c)1335- if c:1336- c_size += 11337- except StopIteration:1338- if not c_size:1339- return1340- yield concat(buf)1341- del buf[:]1342- c_size = 01343-1344- def enable_buffering(self, size=5):1345- """Enable buffering. Buffer `size` items before yielding them."""1346- if size <= 1:1347- raise ValueError("buffer size too small")1348-1349- self.buffered = True1350- self._next = partial(next, self._buffered_generator(size))1351-1352- def __iter__(self):1353- return self1354-1355- def __next__(self):1356- return self._next()1357-1358-1359-# hook in default template class. if anyone reads this comment: ignore that1360-# it's possible to use custom templates ;-)1361-Environment.template_class = Templatedeleted:src/jinja2/exceptions.py-177 removed
1-# -*- coding: utf-8 -*-2-from ._compat import imap3-from ._compat import implements_to_string4-from ._compat import PY25-from ._compat import text_type6-7-8-class TemplateError(Exception):9- """Baseclass for all template errors."""10-11- if PY2:12-13- def __init__(self, message=None):14- if message is not None:15- message = text_type(message).encode("utf-8")16- Exception.__init__(self, message)17-18- @property19- def message(self):20- if self.args:21- message = self.args[0]22- if message is not None:23- return message.decode("utf-8", "replace")24-25- def __unicode__(self):26- return self.message or u""27-28- else:29-30- def __init__(self, message=None):31- Exception.__init__(self, message)32-33- @property34- def message(self):35- if self.args:36- message = self.args[0]37- if message is not None:38- return message39-40-41-@implements_to_string42-class TemplateNotFound(IOError, LookupError, TemplateError):43- """Raised if a template does not exist.44-45- .. versionchanged:: 2.1146- If the given name is :class:`Undefined` and no message was47- provided, an :exc:`UndefinedError` is raised.48- """49-50- # looks weird, but removes the warning descriptor that just51- # bogusly warns us about message being deprecated52- message = None53-54- def __init__(self, name, message=None):55- IOError.__init__(self, name)56-57- if message is None:58- from .runtime import Undefined59-60- if isinstance(name, Undefined):61- name._fail_with_undefined_error()62-63- message = name64-65- self.message = message66- self.name = name67- self.templates = [name]68-69- def __str__(self):70- return self.message71-72-73-class TemplatesNotFound(TemplateNotFound):74- """Like :class:`TemplateNotFound` but raised if multiple templates75- are selected. This is a subclass of :class:`TemplateNotFound`76- exception, so just catching the base exception will catch both.77-78- .. versionchanged:: 2.1179- If a name in the list of names is :class:`Undefined`, a message80- about it being undefined is shown rather than the empty string.81-82- .. versionadded:: 2.283- """84-85- def __init__(self, names=(), message=None):86- if message is None:87- from .runtime import Undefined88-89- parts = []90-91- for name in names:92- if isinstance(name, Undefined):93- parts.append(name._undefined_message)94- else:95- parts.append(name)96-97- message = u"none of the templates given were found: " + u", ".join(98- imap(text_type, parts)99- )100- TemplateNotFound.__init__(self, names and names[-1] or None, message)101- self.templates = list(names)102-103-104-@implements_to_string105-class TemplateSyntaxError(TemplateError):106- """Raised to tell the user that there is a problem with the template."""107-108- def __init__(self, message, lineno, name=None, filename=None):109- TemplateError.__init__(self, message)110- self.lineno = lineno111- self.name = name112- self.filename = filename113- self.source = None114-115- # this is set to True if the debug.translate_syntax_error116- # function translated the syntax error into a new traceback117- self.translated = False118-119- def __str__(self):120- # for translated errors we only return the message121- if self.translated:122- return self.message123-124- # otherwise attach some stuff125- location = "line %d" % self.lineno126- name = self.filename or self.name127- if name:128- location = 'File "%s", %s' % (name, location)129- lines = [self.message, " " + location]130-131- # if the source is set, add the line to the output132- if self.source is not None:133- try:134- line = self.source.splitlines()[self.lineno - 1]135- except IndexError:136- line = None137- if line:138- lines.append(" " + line.strip())139-140- return u"\n".join(lines)141-142- def __reduce__(self):143- # https://bugs.python.org/issue1692335 Exceptions that take144- # multiple required arguments have problems with pickling.145- # Without this, raises TypeError: __init__() missing 1 required146- # positional argument: 'lineno'147- return self.__class__, (self.message, self.lineno, self.name, self.filename)148-149-150-class TemplateAssertionError(TemplateSyntaxError):151- """Like a template syntax error, but covers cases where something in the152- template caused an error at compile time that wasn't necessarily caused153- by a syntax error. However it's a direct subclass of154- :exc:`TemplateSyntaxError` and has the same attributes.155- """156-157-158-class TemplateRuntimeError(TemplateError):159- """A generic runtime error in the template engine. Under some situations160- Jinja may raise this exception.161- """162-163-164-class UndefinedError(TemplateRuntimeError):165- """Raised if a template tries to operate on :class:`Undefined`."""166-167-168-class SecurityError(TemplateRuntimeError):169- """Raised if a template tries to do something insecure if the170- sandbox is enabled.171- """172-173-174-class FilterArgumentError(TemplateRuntimeError):175- """This error is raised if a filter was called with inappropriate176- arguments177- """deleted:src/jinja2/ext.py-703 removed
1-# -*- coding: utf-8 -*-2-"""Extension API for adding custom tags and behavior."""3-import pprint4-import re5-from sys import version_info6-7-from . import nodes8-from ._compat import iteritems9-from ._compat import string_types10-from ._compat import with_metaclass11-from .defaults import BLOCK_END_STRING12-from .defaults import BLOCK_START_STRING13-from .defaults import COMMENT_END_STRING14-from .defaults import COMMENT_START_STRING15-from .defaults import KEEP_TRAILING_NEWLINE16-from .defaults import LINE_COMMENT_PREFIX17-from .defaults import LINE_STATEMENT_PREFIX18-from .defaults import LSTRIP_BLOCKS19-from .defaults import NEWLINE_SEQUENCE20-from .defaults import TRIM_BLOCKS21-from .defaults import VARIABLE_END_STRING22-from .defaults import VARIABLE_START_STRING23-from .environment import Environment24-from .exceptions import TemplateAssertionError25-from .exceptions import TemplateSyntaxError26-from .nodes import ContextReference27-from .runtime import concat28-from .utils import contextfunction29-from .utils import import_string30-from .utils import Markup31-32-# the only real useful gettext functions for a Jinja template. Note33-# that ugettext must be assigned to gettext as Jinja doesn't support34-# non unicode strings.35-GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext")36-37-_ws_re = re.compile(r"\s*\n\s*")38-39-40-class ExtensionRegistry(type):41- """Gives the extension an unique identifier."""42-43- def __new__(mcs, name, bases, d):44- rv = type.__new__(mcs, name, bases, d)45- rv.identifier = rv.__module__ + "." + rv.__name__46- return rv47-48-49-class Extension(with_metaclass(ExtensionRegistry, object)):50- """Extensions can be used to add extra functionality to the Jinja template51- system at the parser level. Custom extensions are bound to an environment52- but may not store environment specific data on `self`. The reason for53- this is that an extension can be bound to another environment (for54- overlays) by creating a copy and reassigning the `environment` attribute.55-56- As extensions are created by the environment they cannot accept any57- arguments for configuration. One may want to work around that by using58- a factory function, but that is not possible as extensions are identified59- by their import name. The correct way to configure the extension is60- storing the configuration values on the environment. Because this way the61- environment ends up acting as central configuration storage the62- attributes may clash which is why extensions have to ensure that the names63- they choose for configuration are not too generic. ``prefix`` for example64- is a terrible name, ``fragment_cache_prefix`` on the other hand is a good65- name as includes the name of the extension (fragment cache).66- """67-68- #: if this extension parses this is the list of tags it's listening to.69- tags = set()70-71- #: the priority of that extension. This is especially useful for72- #: extensions that preprocess values. A lower value means higher73- #: priority.74- #:75- #: .. versionadded:: 2.476- priority = 10077-78- def __init__(self, environment):79- self.environment = environment80-81- def bind(self, environment):82- """Create a copy of this extension bound to another environment."""83- rv = object.__new__(self.__class__)84- rv.__dict__.update(self.__dict__)85- rv.environment = environment86- return rv87-88- def preprocess(self, source, name, filename=None):89- """This method is called before the actual lexing and can be used to90- preprocess the source. The `filename` is optional. The return value91- must be the preprocessed source.92- """93- return source94-95- def filter_stream(self, stream):96- """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used97- to filter tokens returned. This method has to return an iterable of98- :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a99- :class:`~jinja2.lexer.TokenStream`.100- """101- return stream102-103- def parse(self, parser):104- """If any of the :attr:`tags` matched this method is called with the105- parser as first argument. The token the parser stream is pointing at106- is the name token that matched. This method has to return one or a107- list of multiple nodes.108- """109- raise NotImplementedError()110-111- def attr(self, name, lineno=None):112- """Return an attribute node for the current extension. This is useful113- to pass constants on extensions to generated template code.114-115- ::116-117- self.attr('_my_attribute', lineno=lineno)118- """119- return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)120-121- def call_method(122- self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None123- ):124- """Call a method of the extension. This is a shortcut for125- :meth:`attr` + :class:`jinja2.nodes.Call`.126- """127- if args is None:128- args = []129- if kwargs is None:130- kwargs = []131- return nodes.Call(132- self.attr(name, lineno=lineno),133- args,134- kwargs,135- dyn_args,136- dyn_kwargs,137- lineno=lineno,138- )139-140-141-@contextfunction142-def _gettext_alias(__context, *args, **kwargs):143- return __context.call(__context.resolve("gettext"), *args, **kwargs)144-145-146-def _make_new_gettext(func):147- @contextfunction148- def gettext(__context, __string, **variables):149- rv = __context.call(func, __string)150- if __context.eval_ctx.autoescape:151- rv = Markup(rv)152- # Always treat as a format string, even if there are no153- # variables. This makes translation strings more consistent154- # and predictable. This requires escaping155- return rv % variables156-157- return gettext158-159-160-def _make_new_ngettext(func):161- @contextfunction162- def ngettext(__context, __singular, __plural, __num, **variables):163- variables.setdefault("num", __num)164- rv = __context.call(func, __singular, __plural, __num)165- if __context.eval_ctx.autoescape:166- rv = Markup(rv)167- # Always treat as a format string, see gettext comment above.168- return rv % variables169-170- return ngettext171-172-173-class InternationalizationExtension(Extension):174- """This extension adds gettext support to Jinja."""175-176- tags = {"trans"}177-178- # TODO: the i18n extension is currently reevaluating values in a few179- # situations. Take this example:180- # {% trans count=something() %}{{ count }} foo{% pluralize181- # %}{{ count }} fooss{% endtrans %}182- # something is called twice here. One time for the gettext value and183- # the other time for the n-parameter of the ngettext function.184-185- def __init__(self, environment):186- Extension.__init__(self, environment)187- environment.globals["_"] = _gettext_alias188- environment.extend(189- install_gettext_translations=self._install,190- install_null_translations=self._install_null,191- install_gettext_callables=self._install_callables,192- uninstall_gettext_translations=self._uninstall,193- extract_translations=self._extract,194- newstyle_gettext=False,195- )196-197- def _install(self, translations, newstyle=None):198- gettext = getattr(translations, "ugettext", None)199- if gettext is None:200- gettext = translations.gettext201- ngettext = getattr(translations, "ungettext", None)202- if ngettext is None:203- ngettext = translations.ngettext204- self._install_callables(gettext, ngettext, newstyle)205-206- def _install_null(self, newstyle=None):207- self._install_callables(208- lambda x: x, lambda s, p, n: (n != 1 and (p,) or (s,))[0], newstyle209- )210-211- def _install_callables(self, gettext, ngettext, newstyle=None):212- if newstyle is not None:213- self.environment.newstyle_gettext = newstyle214- if self.environment.newstyle_gettext:215- gettext = _make_new_gettext(gettext)216- ngettext = _make_new_ngettext(ngettext)217- self.environment.globals.update(gettext=gettext, ngettext=ngettext)218-219- def _uninstall(self, translations):220- for key in "gettext", "ngettext":221- self.environment.globals.pop(key, None)222-223- def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):224- if isinstance(source, string_types):225- source = self.environment.parse(source)226- return extract_from_ast(source, gettext_functions)227-228- def parse(self, parser):229- """Parse a translatable tag."""230- lineno = next(parser.stream).lineno231- num_called_num = False232-233- # find all the variables referenced. Additionally a variable can be234- # defined in the body of the trans block too, but this is checked at235- # a later state.236- plural_expr = None237- plural_expr_assignment = None238- variables = {}239- trimmed = None240- while parser.stream.current.type != "block_end":241- if variables:242- parser.stream.expect("comma")243-244- # skip colon for python compatibility245- if parser.stream.skip_if("colon"):246- break247-248- name = parser.stream.expect("name")249- if name.value in variables:250- parser.fail(251- "translatable variable %r defined twice." % name.value,252- name.lineno,253- exc=TemplateAssertionError,254- )255-256- # expressions257- if parser.stream.current.type == "assign":258- next(parser.stream)259- variables[name.value] = var = parser.parse_expression()260- elif trimmed is None and name.value in ("trimmed", "notrimmed"):261- trimmed = name.value == "trimmed"262- continue263- else:264- variables[name.value] = var = nodes.Name(name.value, "load")265-266- if plural_expr is None:267- if isinstance(var, nodes.Call):268- plural_expr = nodes.Name("_trans", "load")269- variables[name.value] = plural_expr270- plural_expr_assignment = nodes.Assign(271- nodes.Name("_trans", "store"), var272- )273- else:274- plural_expr = var275- num_called_num = name.value == "num"276-277- parser.stream.expect("block_end")278-279- plural = None280- have_plural = False281- referenced = set()282-283- # now parse until endtrans or pluralize284- singular_names, singular = self._parse_block(parser, True)285- if singular_names:286- referenced.update(singular_names)287- if plural_expr is None:288- plural_expr = nodes.Name(singular_names[0], "load")289- num_called_num = singular_names[0] == "num"290-291- # if we have a pluralize block, we parse that too292- if parser.stream.current.test("name:pluralize"):293- have_plural = True294- next(parser.stream)295- if parser.stream.current.type != "block_end":296- name = parser.stream.expect("name")297- if name.value not in variables:298- parser.fail(299- "unknown variable %r for pluralization" % name.value,300- name.lineno,301- exc=TemplateAssertionError,302- )303- plural_expr = variables[name.value]304- num_called_num = name.value == "num"305- parser.stream.expect("block_end")306- plural_names, plural = self._parse_block(parser, False)307- next(parser.stream)308- referenced.update(plural_names)309- else:310- next(parser.stream)311-312- # register free names as simple name expressions313- for var in referenced:314- if var not in variables:315- variables[var] = nodes.Name(var, "load")316-317- if not have_plural:318- plural_expr = None319- elif plural_expr is None:320- parser.fail("pluralize without variables", lineno)321-322- if trimmed is None:323- trimmed = self.environment.policies["ext.i18n.trimmed"]324- if trimmed:325- singular = self._trim_whitespace(singular)326- if plural:327- plural = self._trim_whitespace(plural)328-329- node = self._make_node(330- singular,331- plural,332- variables,333- plural_expr,334- bool(referenced),335- num_called_num and have_plural,336- )337- node.set_lineno(lineno)338- if plural_expr_assignment is not None:339- return [plural_expr_assignment, node]340- else:341- return node342-343- def _trim_whitespace(self, string, _ws_re=_ws_re):344- return _ws_re.sub(" ", string.strip())345-346- def _parse_block(self, parser, allow_pluralize):347- """Parse until the next block tag with a given name."""348- referenced = []349- buf = []350- while 1:351- if parser.stream.current.type == "data":352- buf.append(parser.stream.current.value.replace("%", "%%"))353- next(parser.stream)354- elif parser.stream.current.type == "variable_begin":355- next(parser.stream)356- name = parser.stream.expect("name").value357- referenced.append(name)358- buf.append("%%(%s)s" % name)359- parser.stream.expect("variable_end")360- elif parser.stream.current.type == "block_begin":361- next(parser.stream)362- if parser.stream.current.test("name:endtrans"):363- break364- elif parser.stream.current.test("name:pluralize"):365- if allow_pluralize:366- break367- parser.fail(368- "a translatable section can have only one pluralize section"369- )370- parser.fail(371- "control structures in translatable sections are not allowed"372- )373- elif parser.stream.eos:374- parser.fail("unclosed translation block")375- else:376- raise RuntimeError("internal parser error")377-378- return referenced, concat(buf)379-380- def _make_node(381- self, singular, plural, variables, plural_expr, vars_referenced, num_called_num382- ):383- """Generates a useful node from the data provided."""384- # no variables referenced? no need to escape for old style385- # gettext invocations only if there are vars.386- if not vars_referenced and not self.environment.newstyle_gettext:387- singular = singular.replace("%%", "%")388- if plural:389- plural = plural.replace("%%", "%")390-391- # singular only:392- if plural_expr is None:393- gettext = nodes.Name("gettext", "load")394- node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None)395-396- # singular and plural397- else:398- ngettext = nodes.Name("ngettext", "load")399- node = nodes.Call(400- ngettext,401- [nodes.Const(singular), nodes.Const(plural), plural_expr],402- [],403- None,404- None,405- )406-407- # in case newstyle gettext is used, the method is powerful408- # enough to handle the variable expansion and autoescape409- # handling itself410- if self.environment.newstyle_gettext:411- for key, value in iteritems(variables):412- # the function adds that later anyways in case num was413- # called num, so just skip it.414- if num_called_num and key == "num":415- continue416- node.kwargs.append(nodes.Keyword(key, value))417-418- # otherwise do that here419- else:420- # mark the return value as safe if we are in an421- # environment with autoescaping turned on422- node = nodes.MarkSafeIfAutoescape(node)423- if variables:424- node = nodes.Mod(425- node,426- nodes.Dict(427- [428- nodes.Pair(nodes.Const(key), value)429- for key, value in variables.items()430- ]431- ),432- )433- return nodes.Output([node])434-435-436-class ExprStmtExtension(Extension):437- """Adds a `do` tag to Jinja that works like the print statement just438- that it doesn't print the return value.439- """440-441- tags = set(["do"])442-443- def parse(self, parser):444- node = nodes.ExprStmt(lineno=next(parser.stream).lineno)445- node.node = parser.parse_tuple()446- return node447-448-449-class LoopControlExtension(Extension):450- """Adds break and continue to the template engine."""451-452- tags = set(["break", "continue"])453-454- def parse(self, parser):455- token = next(parser.stream)456- if token.value == "break":457- return nodes.Break(lineno=token.lineno)458- return nodes.Continue(lineno=token.lineno)459-460-461-class WithExtension(Extension):462- pass463-464-465-class AutoEscapeExtension(Extension):466- pass467-468-469-class DebugExtension(Extension):470- """A ``{% debug %}`` tag that dumps the available variables,471- filters, and tests.472-473- .. code-block:: html+jinja474-475- <pre>{% debug %}</pre>476-477- .. code-block:: text478-479- {'context': {'cycler': <class 'jinja2.utils.Cycler'>,480- ...,481- 'namespace': <class 'jinja2.utils.Namespace'>},482- 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',483- ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],484- 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',485- ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}486-487- .. versionadded:: 2.11.0488- """489-490- tags = {"debug"}491-492- def parse(self, parser):493- lineno = parser.stream.expect("name:debug").lineno494- context = ContextReference()495- result = self.call_method("_render", [context], lineno=lineno)496- return nodes.Output([result], lineno=lineno)497-498- def _render(self, context):499- result = {500- "context": context.get_all(),501- "filters": sorted(self.environment.filters.keys()),502- "tests": sorted(self.environment.tests.keys()),503- }504-505- # Set the depth since the intent is to show the top few names.506- if version_info[:2] >= (3, 4):507- return pprint.pformat(result, depth=3, compact=True)508- else:509- return pprint.pformat(result, depth=3)510-511-512-def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True):513- """Extract localizable strings from the given template node. Per514- default this function returns matches in babel style that means non string515- parameters as well as keyword arguments are returned as `None`. This516- allows Babel to figure out what you really meant if you are using517- gettext functions that allow keyword arguments for placeholder expansion.518- If you don't want that behavior set the `babel_style` parameter to `False`519- which causes only strings to be returned and parameters are always stored520- in tuples. As a consequence invalid gettext calls (calls without a single521- string parameter or string parameters after non-string parameters) are522- skipped.523-524- This example explains the behavior:525-526- >>> from jinja2 import Environment527- >>> env = Environment()528- >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')529- >>> list(extract_from_ast(node))530- [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]531- >>> list(extract_from_ast(node, babel_style=False))532- [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]533-534- For every string found this function yields a ``(lineno, function,535- message)`` tuple, where:536-537- * ``lineno`` is the number of the line on which the string was found,538- * ``function`` is the name of the ``gettext`` function used (if the539- string was extracted from embedded Python code), and540- * ``message`` is the string itself (a ``unicode`` object, or a tuple541- of ``unicode`` objects for functions with multiple string arguments).542-543- This extraction function operates on the AST and is because of that unable544- to extract any comments. For comment support you have to use the babel545- extraction interface or extract comments yourself.546- """547- for node in node.find_all(nodes.Call):548- if (549- not isinstance(node.node, nodes.Name)550- or node.node.name not in gettext_functions551- ):552- continue553-554- strings = []555- for arg in node.args:556- if isinstance(arg, nodes.Const) and isinstance(arg.value, string_types):557- strings.append(arg.value)558- else:559- strings.append(None)560-561- for _ in node.kwargs:562- strings.append(None)563- if node.dyn_args is not None:564- strings.append(None)565- if node.dyn_kwargs is not None:566- strings.append(None)567-568- if not babel_style:569- strings = tuple(x for x in strings if x is not None)570- if not strings:571- continue572- else:573- if len(strings) == 1:574- strings = strings[0]575- else:576- strings = tuple(strings)577- yield node.lineno, node.node.name, strings578-579-580-class _CommentFinder(object):581- """Helper class to find comments in a token stream. Can only582- find comments for gettext calls forwards. Once the comment583- from line 4 is found, a comment for line 1 will not return a584- usable value.585- """586-587- def __init__(self, tokens, comment_tags):588- self.tokens = tokens589- self.comment_tags = comment_tags590- self.offset = 0591- self.last_lineno = 0592-593- def find_backwards(self, offset):594- try:595- for _, token_type, token_value in reversed(596- self.tokens[self.offset : offset]597- ):598- if token_type in ("comment", "linecomment"):599- try:600- prefix, comment = token_value.split(None, 1)601- except ValueError:602- continue603- if prefix in self.comment_tags:604- return [comment.rstrip()]605- return []606- finally:607- self.offset = offset608-609- def find_comments(self, lineno):610- if not self.comment_tags or self.last_lineno > lineno:611- return []612- for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):613- if token_lineno > lineno:614- return self.find_backwards(self.offset + idx)615- return self.find_backwards(len(self.tokens))616-617-618-def babel_extract(fileobj, keywords, comment_tags, options):619- """Babel extraction method for Jinja templates.620-621- .. versionchanged:: 2.3622- Basic support for translation comments was added. If `comment_tags`623- is now set to a list of keywords for extraction, the extractor will624- try to find the best preceding comment that begins with one of the625- keywords. For best results, make sure to not have more than one626- gettext call in one line of code and the matching comment in the627- same line or the line before.628-629- .. versionchanged:: 2.5.1630- The `newstyle_gettext` flag can be set to `True` to enable newstyle631- gettext calls.632-633- .. versionchanged:: 2.7634- A `silent` option can now be provided. If set to `False` template635- syntax errors are propagated instead of being ignored.636-637- :param fileobj: the file-like object the messages should be extracted from638- :param keywords: a list of keywords (i.e. function names) that should be639- recognized as translation functions640- :param comment_tags: a list of translator tags to search for and include641- in the results.642- :param options: a dictionary of additional options (optional)643- :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.644- (comments will be empty currently)645- """646- extensions = set()647- for extension in options.get("extensions", "").split(","):648- extension = extension.strip()649- if not extension:650- continue651- extensions.add(import_string(extension))652- if InternationalizationExtension not in extensions:653- extensions.add(InternationalizationExtension)654-655- def getbool(options, key, default=False):656- return options.get(key, str(default)).lower() in ("1", "on", "yes", "true")657-658- silent = getbool(options, "silent", True)659- environment = Environment(660- options.get("block_start_string", BLOCK_START_STRING),661- options.get("block_end_string", BLOCK_END_STRING),662- options.get("variable_start_string", VARIABLE_START_STRING),663- options.get("variable_end_string", VARIABLE_END_STRING),664- options.get("comment_start_string", COMMENT_START_STRING),665- options.get("comment_end_string", COMMENT_END_STRING),666- options.get("line_statement_prefix") or LINE_STATEMENT_PREFIX,667- options.get("line_comment_prefix") or LINE_COMMENT_PREFIX,668- getbool(options, "trim_blocks", TRIM_BLOCKS),669- getbool(options, "lstrip_blocks", LSTRIP_BLOCKS),670- NEWLINE_SEQUENCE,671- getbool(options, "keep_trailing_newline", KEEP_TRAILING_NEWLINE),672- frozenset(extensions),673- cache_size=0,674- auto_reload=False,675- )676-677- if getbool(options, "trimmed"):678- environment.policies["ext.i18n.trimmed"] = True679- if getbool(options, "newstyle_gettext"):680- environment.newstyle_gettext = True681-682- source = fileobj.read().decode(options.get("encoding", "utf-8"))683- try:684- node = environment.parse(source)685- tokens = list(environment.lex(environment.preprocess(source)))686- except TemplateSyntaxError:687- if not silent:688- raise689- # skip templates with syntax errors690- return691-692- finder = _CommentFinder(tokens, comment_tags)693- for lineno, func, message in extract_from_ast(node, keywords):694- yield lineno, func, message, finder.find_comments(lineno)695-696-697-#: nicer import names698-i18n = InternationalizationExtension699-do = ExprStmtExtension700-loopcontrols = LoopControlExtension701-with_ = WithExtension702-autoescape = AutoEscapeExtension703-debug = DebugExtensiondeleted:src/jinja2/filters.py-1382 removed
1-# -*- coding: utf-8 -*-2-"""Built-in template filters used with the ``|`` operator."""3-import math4-import random5-import re6-import warnings7-from collections import namedtuple8-from itertools import chain9-from itertools import groupby10-11-from markupsafe import escape12-from markupsafe import Markup13-from markupsafe import soft_unicode14-15-from ._compat import abc16-from ._compat import imap17-from ._compat import iteritems18-from ._compat import string_types19-from ._compat import text_type20-from .exceptions import FilterArgumentError21-from .runtime import Undefined22-from .utils import htmlsafe_json_dumps23-from .utils import pformat24-from .utils import unicode_urlencode25-from .utils import urlize26-27-_word_re = re.compile(r"\w+", re.UNICODE)28-_word_beginning_split_re = re.compile(r"([-\s\(\{\[\<]+)", re.UNICODE)29-30-31-def contextfilter(f):32- """Decorator for marking context dependent filters. The current33- :class:`Context` will be passed as first argument.34- """35- f.contextfilter = True36- return f37-38-39-def evalcontextfilter(f):40- """Decorator for marking eval-context dependent filters. An eval41- context object is passed as first argument. For more information42- about the eval context, see :ref:`eval-context`.43-44- .. versionadded:: 2.445- """46- f.evalcontextfilter = True47- return f48-49-50-def environmentfilter(f):51- """Decorator for marking environment dependent filters. The current52- :class:`Environment` is passed to the filter as first argument.53- """54- f.environmentfilter = True55- return f56-57-58-def ignore_case(value):59- """For use as a postprocessor for :func:`make_attrgetter`. Converts strings60- to lowercase and returns other types as-is."""61- return value.lower() if isinstance(value, string_types) else value62-63-64-def make_attrgetter(environment, attribute, postprocess=None, default=None):65- """Returns a callable that looks up the given attribute from a66- passed object with the rules of the environment. Dots are allowed67- to access attributes of attributes. Integer parts in paths are68- looked up as integers.69- """70- attribute = _prepare_attribute_parts(attribute)71-72- def attrgetter(item):73- for part in attribute:74- item = environment.getitem(item, part)75-76- if default and isinstance(item, Undefined):77- item = default78-79- if postprocess is not None:80- item = postprocess(item)81-82- return item83-84- return attrgetter85-86-87-def make_multi_attrgetter(environment, attribute, postprocess=None):88- """Returns a callable that looks up the given comma separated89- attributes from a passed object with the rules of the environment.90- Dots are allowed to access attributes of each attribute. Integer91- parts in paths are looked up as integers.92-93- The value returned by the returned callable is a list of extracted94- attribute values.95-96- Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.97- """98- attribute_parts = (99- attribute.split(",") if isinstance(attribute, string_types) else [attribute]100- )101- attribute = [102- _prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts103- ]104-105- def attrgetter(item):106- items = [None] * len(attribute)107- for i, attribute_part in enumerate(attribute):108- item_i = item109- for part in attribute_part:110- item_i = environment.getitem(item_i, part)111-112- if postprocess is not None:113- item_i = postprocess(item_i)114-115- items[i] = item_i116- return items117-118- return attrgetter119-120-121-def _prepare_attribute_parts(attr):122- if attr is None:123- return []124- elif isinstance(attr, string_types):125- return [int(x) if x.isdigit() else x for x in attr.split(".")]126- else:127- return [attr]128-129-130-def do_forceescape(value):131- """Enforce HTML escaping. This will probably double escape variables."""132- if hasattr(value, "__html__"):133- value = value.__html__()134- return escape(text_type(value))135-136-137-def do_urlencode(value):138- """Quote data for use in a URL path or query using UTF-8.139-140- Basic wrapper around :func:`urllib.parse.quote` when given a141- string, or :func:`urllib.parse.urlencode` for a dict or iterable.142-143- :param value: Data to quote. A string will be quoted directly. A144- dict or iterable of ``(key, value)`` pairs will be joined as a145- query string.146-147- When given a string, "/" is not quoted. HTTP servers treat "/" and148- "%2F" equivalently in paths. If you need quoted slashes, use the149- ``|replace("/", "%2F")`` filter.150-151- .. versionadded:: 2.7152- """153- if isinstance(value, string_types) or not isinstance(value, abc.Iterable):154- return unicode_urlencode(value)155-156- if isinstance(value, dict):157- items = iteritems(value)158- else:159- items = iter(value)160-161- return u"&".join(162- "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))163- for k, v in items164- )165-166-167-@evalcontextfilter168-def do_replace(eval_ctx, s, old, new, count=None):169- """Return a copy of the value with all occurrences of a substring170- replaced with a new one. The first argument is the substring171- that should be replaced, the second is the replacement string.172- If the optional third argument ``count`` is given, only the first173- ``count`` occurrences are replaced:174-175- .. sourcecode:: jinja176-177- {{ "Hello World"|replace("Hello", "Goodbye") }}178- -> Goodbye World179-180- {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}181- -> d'oh, d'oh, aaargh182- """183- if count is None:184- count = -1185- if not eval_ctx.autoescape:186- return text_type(s).replace(text_type(old), text_type(new), count)187- if (188- hasattr(old, "__html__")189- or hasattr(new, "__html__")190- and not hasattr(s, "__html__")191- ):192- s = escape(s)193- else:194- s = soft_unicode(s)195- return s.replace(soft_unicode(old), soft_unicode(new), count)196-197-198-def do_upper(s):199- """Convert a value to uppercase."""200- return soft_unicode(s).upper()201-202-203-def do_lower(s):204- """Convert a value to lowercase."""205- return soft_unicode(s).lower()206-207-208-@evalcontextfilter209-def do_xmlattr(_eval_ctx, d, autospace=True):210- """Create an SGML/XML attribute string based on the items in a dict.211- All values that are neither `none` nor `undefined` are automatically212- escaped:213-214- .. sourcecode:: html+jinja215-216- <ul{{ {'class': 'my_list', 'missing': none,217- 'id': 'list-%d'|format(variable)}|xmlattr }}>218- ...219- </ul>220-221- Results in something like this:222-223- .. sourcecode:: html224-225- <ul class="my_list" id="list-42">226- ...227- </ul>228-229- As you can see it automatically prepends a space in front of the item230- if the filter returned something unless the second parameter is false.231- """232- rv = u" ".join(233- u'%s="%s"' % (escape(key), escape(value))234- for key, value in iteritems(d)235- if value is not None and not isinstance(value, Undefined)236- )237- if autospace and rv:238- rv = u" " + rv239- if _eval_ctx.autoescape:240- rv = Markup(rv)241- return rv242-243-244-def do_capitalize(s):245- """Capitalize a value. The first character will be uppercase, all others246- lowercase.247- """248- return soft_unicode(s).capitalize()249-250-251-def do_title(s):252- """Return a titlecased version of the value. I.e. words will start with253- uppercase letters, all remaining characters are lowercase.254- """255- return "".join(256- [257- item[0].upper() + item[1:].lower()258- for item in _word_beginning_split_re.split(soft_unicode(s))259- if item260- ]261- )262-263-264-def do_dictsort(value, case_sensitive=False, by="key", reverse=False):265- """Sort a dict and yield (key, value) pairs. Because python dicts are266- unsorted you may want to use this function to order them by either267- key or value:268-269- .. sourcecode:: jinja270-271- {% for item in mydict|dictsort %}272- sort the dict by key, case insensitive273-274- {% for item in mydict|dictsort(reverse=true) %}275- sort the dict by key, case insensitive, reverse order276-277- {% for item in mydict|dictsort(true) %}278- sort the dict by key, case sensitive279-280- {% for item in mydict|dictsort(false, 'value') %}281- sort the dict by value, case insensitive282- """283- if by == "key":284- pos = 0285- elif by == "value":286- pos = 1287- else:288- raise FilterArgumentError('You can only sort by either "key" or "value"')289-290- def sort_func(item):291- value = item[pos]292-293- if not case_sensitive:294- value = ignore_case(value)295-296- return value297-298- return sorted(value.items(), key=sort_func, reverse=reverse)299-300-301-@environmentfilter302-def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):303- """Sort an iterable using Python's :func:`sorted`.304-305- .. sourcecode:: jinja306-307- {% for city in cities|sort %}308- ...309- {% endfor %}310-311- :param reverse: Sort descending instead of ascending.312- :param case_sensitive: When sorting strings, sort upper and lower313- case separately.314- :param attribute: When sorting objects or dicts, an attribute or315- key to sort by. Can use dot notation like ``"address.city"``.316- Can be a list of attributes like ``"age,name"``.317-318- The sort is stable, it does not change the relative order of319- elements that compare equal. This makes it is possible to chain320- sorts on different attributes and ordering.321-322- .. sourcecode:: jinja323-324- {% for user in users|sort(attribute="name")325- |sort(reverse=true, attribute="age") %}326- ...327- {% endfor %}328-329- As a shortcut to chaining when the direction is the same for all330- attributes, pass a comma separate list of attributes.331-332- .. sourcecode:: jinja333-334- {% for user users|sort(attribute="age,name") %}335- ...336- {% endfor %}337-338- .. versionchanged:: 2.11.0339- The ``attribute`` parameter can be a comma separated list of340- attributes, e.g. ``"age,name"``.341-342- .. versionchanged:: 2.6343- The ``attribute`` parameter was added.344- """345- key_func = make_multi_attrgetter(346- environment, attribute, postprocess=ignore_case if not case_sensitive else None347- )348- return sorted(value, key=key_func, reverse=reverse)349-350-351-@environmentfilter352-def do_unique(environment, value, case_sensitive=False, attribute=None):353- """Returns a list of unique items from the given iterable.354-355- .. sourcecode:: jinja356-357- {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}358- -> ['foo', 'bar', 'foobar']359-360- The unique items are yielded in the same order as their first occurrence in361- the iterable passed to the filter.362-363- :param case_sensitive: Treat upper and lower case strings as distinct.364- :param attribute: Filter objects with unique values for this attribute.365- """366- getter = make_attrgetter(367- environment, attribute, postprocess=ignore_case if not case_sensitive else None368- )369- seen = set()370-371- for item in value:372- key = getter(item)373-374- if key not in seen:375- seen.add(key)376- yield item377-378-379-def _min_or_max(environment, value, func, case_sensitive, attribute):380- it = iter(value)381-382- try:383- first = next(it)384- except StopIteration:385- return environment.undefined("No aggregated item, sequence was empty.")386-387- key_func = make_attrgetter(388- environment, attribute, postprocess=ignore_case if not case_sensitive else None389- )390- return func(chain([first], it), key=key_func)391-392-393-@environmentfilter394-def do_min(environment, value, case_sensitive=False, attribute=None):395- """Return the smallest item from the sequence.396-397- .. sourcecode:: jinja398-399- {{ [1, 2, 3]|min }}400- -> 1401-402- :param case_sensitive: Treat upper and lower case strings as distinct.403- :param attribute: Get the object with the min value of this attribute.404- """405- return _min_or_max(environment, value, min, case_sensitive, attribute)406-407-408-@environmentfilter409-def do_max(environment, value, case_sensitive=False, attribute=None):410- """Return the largest item from the sequence.411-412- .. sourcecode:: jinja413-414- {{ [1, 2, 3]|max }}415- -> 3416-417- :param case_sensitive: Treat upper and lower case strings as distinct.418- :param attribute: Get the object with the max value of this attribute.419- """420- return _min_or_max(environment, value, max, case_sensitive, attribute)421-422-423-def do_default(value, default_value=u"", boolean=False):424- """If the value is undefined it will return the passed default value,425- otherwise the value of the variable:426-427- .. sourcecode:: jinja428-429- {{ my_variable|default('my_variable is not defined') }}430-431- This will output the value of ``my_variable`` if the variable was432- defined, otherwise ``'my_variable is not defined'``. If you want433- to use default with variables that evaluate to false you have to434- set the second parameter to `true`:435-436- .. sourcecode:: jinja437-438- {{ ''|default('the string was empty', true) }}439-440- .. versionchanged:: 2.11441- It's now possible to configure the :class:`~jinja2.Environment` with442- :class:`~jinja2.ChainableUndefined` to make the `default` filter work443- on nested elements and attributes that may contain undefined values444- in the chain without getting an :exc:`~jinja2.UndefinedError`.445- """446- if isinstance(value, Undefined) or (boolean and not value):447- return default_value448- return value449-450-451-@evalcontextfilter452-def do_join(eval_ctx, value, d=u"", attribute=None):453- """Return a string which is the concatenation of the strings in the454- sequence. The separator between elements is an empty string per455- default, you can define it with the optional parameter:456-457- .. sourcecode:: jinja458-459- {{ [1, 2, 3]|join('|') }}460- -> 1|2|3461-462- {{ [1, 2, 3]|join }}463- -> 123464-465- It is also possible to join certain attributes of an object:466-467- .. sourcecode:: jinja468-469- {{ users|join(', ', attribute='username') }}470-471- .. versionadded:: 2.6472- The `attribute` parameter was added.473- """474- if attribute is not None:475- value = imap(make_attrgetter(eval_ctx.environment, attribute), value)476-477- # no automatic escaping? joining is a lot easier then478- if not eval_ctx.autoescape:479- return text_type(d).join(imap(text_type, value))480-481- # if the delimiter doesn't have an html representation we check482- # if any of the items has. If yes we do a coercion to Markup483- if not hasattr(d, "__html__"):484- value = list(value)485- do_escape = False486- for idx, item in enumerate(value):487- if hasattr(item, "__html__"):488- do_escape = True489- else:490- value[idx] = text_type(item)491- if do_escape:492- d = escape(d)493- else:494- d = text_type(d)495- return d.join(value)496-497- # no html involved, to normal joining498- return soft_unicode(d).join(imap(soft_unicode, value))499-500-501-def do_center(value, width=80):502- """Centers the value in a field of a given width."""503- return text_type(value).center(width)504-505-506-@environmentfilter507-def do_first(environment, seq):508- """Return the first item of a sequence."""509- try:510- return next(iter(seq))511- except StopIteration:512- return environment.undefined("No first item, sequence was empty.")513-514-515-@environmentfilter516-def do_last(environment, seq):517- """518- Return the last item of a sequence.519-520- Note: Does not work with generators. You may want to explicitly521- convert it to a list:522-523- .. sourcecode:: jinja524-525- {{ data | selectattr('name', '==', 'Jinja') | list | last }}526- """527- try:528- return next(iter(reversed(seq)))529- except StopIteration:530- return environment.undefined("No last item, sequence was empty.")531-532-533-@contextfilter534-def do_random(context, seq):535- """Return a random item from the sequence."""536- try:537- return random.choice(seq)538- except IndexError:539- return context.environment.undefined("No random item, sequence was empty.")540-541-542-def do_filesizeformat(value, binary=False):543- """Format the value like a 'human-readable' file size (i.e. 13 kB,544- 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,545- Giga, etc.), if the second parameter is set to `True` the binary546- prefixes are used (Mebi, Gibi).547- """548- bytes = float(value)549- base = binary and 1024 or 1000550- prefixes = [551- (binary and "KiB" or "kB"),552- (binary and "MiB" or "MB"),553- (binary and "GiB" or "GB"),554- (binary and "TiB" or "TB"),555- (binary and "PiB" or "PB"),556- (binary and "EiB" or "EB"),557- (binary and "ZiB" or "ZB"),558- (binary and "YiB" or "YB"),559- ]560- if bytes == 1:561- return "1 Byte"562- elif bytes < base:563- return "%d Bytes" % bytes564- else:565- for i, prefix in enumerate(prefixes):566- unit = base ** (i + 2)567- if bytes < unit:568- return "%.1f %s" % ((base * bytes / unit), prefix)569- return "%.1f %s" % ((base * bytes / unit), prefix)570-571-572-def do_pprint(value, verbose=False):573- """Pretty print a variable. Useful for debugging.574-575- With Jinja 1.2 onwards you can pass it a parameter. If this parameter576- is truthy the output will be more verbose (this requires `pretty`)577- """578- return pformat(value, verbose=verbose)579-580-581-@evalcontextfilter582-def do_urlize(583- eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None584-):585- """Converts URLs in plain text into clickable links.586-587- If you pass the filter an additional integer it will shorten the urls588- to that number. Also a third argument exists that makes the urls589- "nofollow":590-591- .. sourcecode:: jinja592-593- {{ mytext|urlize(40, true) }}594- links are shortened to 40 chars and defined with rel="nofollow"595-596- If *target* is specified, the ``target`` attribute will be added to the597- ``<a>`` tag:598-599- .. sourcecode:: jinja600-601- {{ mytext|urlize(40, target='_blank') }}602-603- .. versionchanged:: 2.8+604- The *target* parameter was added.605- """606- policies = eval_ctx.environment.policies607- rel = set((rel or "").split() or [])608- if nofollow:609- rel.add("nofollow")610- rel.update((policies["urlize.rel"] or "").split())611- if target is None:612- target = policies["urlize.target"]613- rel = " ".join(sorted(rel)) or None614- rv = urlize(value, trim_url_limit, rel=rel, target=target)615- if eval_ctx.autoescape:616- rv = Markup(rv)617- return rv618-619-620-def do_indent(s, width=4, first=False, blank=False, indentfirst=None):621- """Return a copy of the string with each line indented by 4 spaces. The622- first line and blank lines are not indented by default.623-624- :param width: Number of spaces to indent by.625- :param first: Don't skip indenting the first line.626- :param blank: Don't skip indenting empty lines.627-628- .. versionchanged:: 2.10629- Blank lines are not indented by default.630-631- Rename the ``indentfirst`` argument to ``first``.632- """633- if indentfirst is not None:634- warnings.warn(635- "The 'indentfirst' argument is renamed to 'first' and will"636- " be removed in version 3.0.",637- DeprecationWarning,638- stacklevel=2,639- )640- first = indentfirst641-642- indention = u" " * width643- newline = u"\n"644-645- if isinstance(s, Markup):646- indention = Markup(indention)647- newline = Markup(newline)648-649- s += newline # this quirk is necessary for splitlines method650-651- if blank:652- rv = (newline + indention).join(s.splitlines())653- else:654- lines = s.splitlines()655- rv = lines.pop(0)656-657- if lines:658- rv += newline + newline.join(659- indention + line if line else line for line in lines660- )661-662- if first:663- rv = indention + rv664-665- return rv666-667-668-@environmentfilter669-def do_truncate(env, s, length=255, killwords=False, end="...", leeway=None):670- """Return a truncated copy of the string. The length is specified671- with the first parameter which defaults to ``255``. If the second672- parameter is ``true`` the filter will cut the text at length. Otherwise673- it will discard the last word. If the text was in fact674- truncated it will append an ellipsis sign (``"..."``). If you want a675- different ellipsis sign than ``"..."`` you can specify it using the676- third parameter. Strings that only exceed the length by the tolerance677- margin given in the fourth parameter will not be truncated.678-679- .. sourcecode:: jinja680-681- {{ "foo bar baz qux"|truncate(9) }}682- -> "foo..."683- {{ "foo bar baz qux"|truncate(9, True) }}684- -> "foo ba..."685- {{ "foo bar baz qux"|truncate(11) }}686- -> "foo bar baz qux"687- {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}688- -> "foo bar..."689-690- The default leeway on newer Jinja versions is 5 and was 0 before but691- can be reconfigured globally.692- """693- if leeway is None:694- leeway = env.policies["truncate.leeway"]695- assert length >= len(end), "expected length >= %s, got %s" % (len(end), length)696- assert leeway >= 0, "expected leeway >= 0, got %s" % leeway697- if len(s) <= length + leeway:698- return s699- if killwords:700- return s[: length - len(end)] + end701- result = s[: length - len(end)].rsplit(" ", 1)[0]702- return result + end703-704-705-@environmentfilter706-def do_wordwrap(707- environment,708- s,709- width=79,710- break_long_words=True,711- wrapstring=None,712- break_on_hyphens=True,713-):714- """Wrap a string to the given width. Existing newlines are treated715- as paragraphs to be wrapped separately.716-717- :param s: Original text to wrap.718- :param width: Maximum length of wrapped lines.719- :param break_long_words: If a word is longer than ``width``, break720- it across lines.721- :param break_on_hyphens: If a word contains hyphens, it may be split722- across lines.723- :param wrapstring: String to join each wrapped line. Defaults to724- :attr:`Environment.newline_sequence`.725-726- .. versionchanged:: 2.11727- Existing newlines are treated as paragraphs wrapped separately.728-729- .. versionchanged:: 2.11730- Added the ``break_on_hyphens`` parameter.731-732- .. versionchanged:: 2.7733- Added the ``wrapstring`` parameter.734- """735-736- import textwrap737-738- if not wrapstring:739- wrapstring = environment.newline_sequence740-741- # textwrap.wrap doesn't consider existing newlines when wrapping.742- # If the string has a newline before width, wrap will still insert743- # a newline at width, resulting in a short line. Instead, split and744- # wrap each paragraph individually.745- return wrapstring.join(746- [747- wrapstring.join(748- textwrap.wrap(749- line,750- width=width,751- expand_tabs=False,752- replace_whitespace=False,753- break_long_words=break_long_words,754- break_on_hyphens=break_on_hyphens,755- )756- )757- for line in s.splitlines()758- ]759- )760-761-762-def do_wordcount(s):763- """Count the words in that string."""764- return len(_word_re.findall(s))765-766-767-def do_int(value, default=0, base=10):768- """Convert the value into an integer. If the769- conversion doesn't work it will return ``0``. You can770- override this default using the first parameter. You771- can also override the default base (10) in the second772- parameter, which handles input with prefixes such as773- 0b, 0o and 0x for bases 2, 8 and 16 respectively.774- The base is ignored for decimal numbers and non-string values.775- """776- try:777- if isinstance(value, string_types):778- return int(value, base)779- return int(value)780- except (TypeError, ValueError):781- # this quirk is necessary so that "42.23"|int gives 42.782- try:783- return int(float(value))784- except (TypeError, ValueError):785- return default786-787-788-def do_float(value, default=0.0):789- """Convert the value into a floating point number. If the790- conversion doesn't work it will return ``0.0``. You can791- override this default using the first parameter.792- """793- try:794- return float(value)795- except (TypeError, ValueError):796- return default797-798-799-def do_format(value, *args, **kwargs):800- """Apply the given values to a `printf-style`_ format string, like801- ``string % values``.802-803- .. sourcecode:: jinja804-805- {{ "%s, %s!"|format(greeting, name) }}806- Hello, World!807-808- In most cases it should be more convenient and efficient to use the809- ``%`` operator or :meth:`str.format`.810-811- .. code-block:: text812-813- {{ "%s, %s!" % (greeting, name) }}814- {{ "{}, {}!".format(greeting, name) }}815-816- .. _printf-style: https://docs.python.org/library/stdtypes.html817- #printf-style-string-formatting818- """819- if args and kwargs:820- raise FilterArgumentError(821- "can't handle positional and keyword arguments at the same time"822- )823- return soft_unicode(value) % (kwargs or args)824-825-826-def do_trim(value, chars=None):827- """Strip leading and trailing characters, by default whitespace."""828- return soft_unicode(value).strip(chars)829-830-831-def do_striptags(value):832- """Strip SGML/XML tags and replace adjacent whitespace by one space."""833- if hasattr(value, "__html__"):834- value = value.__html__()835- return Markup(text_type(value)).striptags()836-837-838-def do_slice(value, slices, fill_with=None):839- """Slice an iterator and return a list of lists containing840- those items. Useful if you want to create a div containing841- three ul tags that represent columns:842-843- .. sourcecode:: html+jinja844-845- <div class="columnwrapper">846- {%- for column in items|slice(3) %}847- <ul class="column-{{ loop.index }}">848- {%- for item in column %}849- <li>{{ item }}</li>850- {%- endfor %}851- </ul>852- {%- endfor %}853- </div>854-855- If you pass it a second argument it's used to fill missing856- values on the last iteration.857- """858- seq = list(value)859- length = len(seq)860- items_per_slice = length // slices861- slices_with_extra = length % slices862- offset = 0863- for slice_number in range(slices):864- start = offset + slice_number * items_per_slice865- if slice_number < slices_with_extra:866- offset += 1867- end = offset + (slice_number + 1) * items_per_slice868- tmp = seq[start:end]869- if fill_with is not None and slice_number >= slices_with_extra:870- tmp.append(fill_with)871- yield tmp872-873-874-def do_batch(value, linecount, fill_with=None):875- """876- A filter that batches items. It works pretty much like `slice`877- just the other way round. It returns a list of lists with the878- given number of items. If you provide a second parameter this879- is used to fill up missing items. See this example:880-881- .. sourcecode:: html+jinja882-883- <table>884- {%- for row in items|batch(3, ' ') %}885- <tr>886- {%- for column in row %}887- <td>{{ column }}</td>888- {%- endfor %}889- </tr>890- {%- endfor %}891- </table>892- """893- tmp = []894- for item in value:895- if len(tmp) == linecount:896- yield tmp897- tmp = []898- tmp.append(item)899- if tmp:900- if fill_with is not None and len(tmp) < linecount:901- tmp += [fill_with] * (linecount - len(tmp))902- yield tmp903-904-905-def do_round(value, precision=0, method="common"):906- """Round the number to a given precision. The first907- parameter specifies the precision (default is ``0``), the908- second the rounding method:909-910- - ``'common'`` rounds either up or down911- - ``'ceil'`` always rounds up912- - ``'floor'`` always rounds down913-914- If you don't specify a method ``'common'`` is used.915-916- .. sourcecode:: jinja917-918- {{ 42.55|round }}919- -> 43.0920- {{ 42.55|round(1, 'floor') }}921- -> 42.5922-923- Note that even if rounded to 0 precision, a float is returned. If924- you need a real integer, pipe it through `int`:925-926- .. sourcecode:: jinja927-928- {{ 42.55|round|int }}929- -> 43930- """931- if method not in {"common", "ceil", "floor"}:932- raise FilterArgumentError("method must be common, ceil or floor")933- if method == "common":934- return round(value, precision)935- func = getattr(math, method)936- return func(value * (10 ** precision)) / (10 ** precision)937-938-939-# Use a regular tuple repr here. This is what we did in the past and we940-# really want to hide this custom type as much as possible. In particular941-# we do not want to accidentally expose an auto generated repr in case942-# people start to print this out in comments or something similar for943-# debugging.944-_GroupTuple = namedtuple("_GroupTuple", ["grouper", "list"])945-_GroupTuple.__repr__ = tuple.__repr__946-_GroupTuple.__str__ = tuple.__str__947-948-949-@environmentfilter950-def do_groupby(environment, value, attribute):951- """Group a sequence of objects by an attribute using Python's952- :func:`itertools.groupby`. The attribute can use dot notation for953- nested access, like ``"address.city"``. Unlike Python's ``groupby``,954- the values are sorted first so only one group is returned for each955- unique value.956-957- For example, a list of ``User`` objects with a ``city`` attribute958- can be rendered in groups. In this example, ``grouper`` refers to959- the ``city`` value of the group.960-961- .. sourcecode:: html+jinja962-963- <ul>{% for city, items in users|groupby("city") %}964- <li>{{ city }}965- <ul>{% for user in items %}966- <li>{{ user.name }}967- {% endfor %}</ul>968- </li>969- {% endfor %}</ul>970-971- ``groupby`` yields namedtuples of ``(grouper, list)``, which972- can be used instead of the tuple unpacking above. ``grouper`` is the973- value of the attribute, and ``list`` is the items with that value.974-975- .. sourcecode:: html+jinja976-977- <ul>{% for group in users|groupby("city") %}978- <li>{{ group.grouper }}: {{ group.list|join(", ") }}979- {% endfor %}</ul>980-981- .. versionchanged:: 2.6982- The attribute supports dot notation for nested access.983- """984- expr = make_attrgetter(environment, attribute)985- return [986- _GroupTuple(key, list(values))987- for key, values in groupby(sorted(value, key=expr), expr)988- ]989-990-991-@environmentfilter992-def do_sum(environment, iterable, attribute=None, start=0):993- """Returns the sum of a sequence of numbers plus the value of parameter994- 'start' (which defaults to 0). When the sequence is empty it returns995- start.996-997- It is also possible to sum up only certain attributes:998-999- .. sourcecode:: jinja1000-1001- Total: {{ items|sum(attribute='price') }}1002-1003- .. versionchanged:: 2.61004- The `attribute` parameter was added to allow suming up over1005- attributes. Also the `start` parameter was moved on to the right.1006- """1007- if attribute is not None:1008- iterable = imap(make_attrgetter(environment, attribute), iterable)1009- return sum(iterable, start)1010-1011-1012-def do_list(value):1013- """Convert the value into a list. If it was a string the returned list1014- will be a list of characters.1015- """1016- return list(value)1017-1018-1019-def do_mark_safe(value):1020- """Mark the value as safe which means that in an environment with automatic1021- escaping enabled this variable will not be escaped.1022- """1023- return Markup(value)1024-1025-1026-def do_mark_unsafe(value):1027- """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1028- return text_type(value)1029-1030-1031-def do_reverse(value):1032- """Reverse the object or return an iterator that iterates over it the other1033- way round.1034- """1035- if isinstance(value, string_types):1036- return value[::-1]1037- try:1038- return reversed(value)1039- except TypeError:1040- try:1041- rv = list(value)1042- rv.reverse()1043- return rv1044- except TypeError:1045- raise FilterArgumentError("argument must be iterable")1046-1047-1048-@environmentfilter1049-def do_attr(environment, obj, name):1050- """Get an attribute of an object. ``foo|attr("bar")`` works like1051- ``foo.bar`` just that always an attribute is returned and items are not1052- looked up.1053-1054- See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.1055- """1056- try:1057- name = str(name)1058- except UnicodeError:1059- pass1060- else:1061- try:1062- value = getattr(obj, name)1063- except AttributeError:1064- pass1065- else:1066- if environment.sandboxed and not environment.is_safe_attribute(1067- obj, name, value1068- ):1069- return environment.unsafe_undefined(obj, name)1070- return value1071- return environment.undefined(obj=obj, name=name)1072-1073-1074-@contextfilter1075-def do_map(*args, **kwargs):1076- """Applies a filter on a sequence of objects or looks up an attribute.1077- This is useful when dealing with lists of objects but you are really1078- only interested in a certain value of it.1079-1080- The basic usage is mapping on an attribute. Imagine you have a list1081- of users but you are only interested in a list of usernames:1082-1083- .. sourcecode:: jinja1084-1085- Users on this page: {{ users|map(attribute='username')|join(', ') }}1086-1087- You can specify a ``default`` value to use if an object in the list1088- does not have the given attribute.1089-1090- .. sourcecode:: jinja1091-1092- {{ users|map(attribute="username", default="Anonymous")|join(", ") }}1093-1094- Alternatively you can let it invoke a filter by passing the name of the1095- filter and the arguments afterwards. A good example would be applying a1096- text conversion filter on a sequence:1097-1098- .. sourcecode:: jinja1099-1100- Users on this page: {{ titles|map('lower')|join(', ') }}1101-1102- Similar to a generator comprehension such as:1103-1104- .. code-block:: python1105-1106- (u.username for u in users)1107- (u.username or "Anonymous" for u in users)1108- (do_lower(x) for x in titles)1109-1110- .. versionchanged:: 2.11.01111- Added the ``default`` parameter.1112-1113- .. versionadded:: 2.71114- """1115- seq, func = prepare_map(args, kwargs)1116- if seq:1117- for item in seq:1118- yield func(item)1119-1120-1121-@contextfilter1122-def do_select(*args, **kwargs):1123- """Filters a sequence of objects by applying a test to each object,1124- and only selecting the objects with the test succeeding.1125-1126- If no test is specified, each object will be evaluated as a boolean.1127-1128- Example usage:1129-1130- .. sourcecode:: jinja1131-1132- {{ numbers|select("odd") }}1133- {{ numbers|select("odd") }}1134- {{ numbers|select("divisibleby", 3) }}1135- {{ numbers|select("lessthan", 42) }}1136- {{ strings|select("equalto", "mystring") }}1137-1138- Similar to a generator comprehension such as:1139-1140- .. code-block:: python1141-1142- (n for n in numbers if test_odd(n))1143- (n for n in numbers if test_divisibleby(n, 3))1144-1145- .. versionadded:: 2.71146- """1147- return select_or_reject(args, kwargs, lambda x: x, False)1148-1149-1150-@contextfilter1151-def do_reject(*args, **kwargs):1152- """Filters a sequence of objects by applying a test to each object,1153- and rejecting the objects with the test succeeding.1154-1155- If no test is specified, each object will be evaluated as a boolean.1156-1157- Example usage:1158-1159- .. sourcecode:: jinja1160-1161- {{ numbers|reject("odd") }}1162-1163- Similar to a generator comprehension such as:1164-1165- .. code-block:: python1166-1167- (n for n in numbers if not test_odd(n))1168-1169- .. versionadded:: 2.71170- """1171- return select_or_reject(args, kwargs, lambda x: not x, False)1172-1173-1174-@contextfilter1175-def do_selectattr(*args, **kwargs):1176- """Filters a sequence of objects by applying a test to the specified1177- attribute of each object, and only selecting the objects with the1178- test succeeding.1179-1180- If no test is specified, the attribute's value will be evaluated as1181- a boolean.1182-1183- Example usage:1184-1185- .. sourcecode:: jinja1186-1187- {{ users|selectattr("is_active") }}1188- {{ users|selectattr("email", "none") }}1189-1190- Similar to a generator comprehension such as:1191-1192- .. code-block:: python1193-1194- (u for user in users if user.is_active)1195- (u for user in users if test_none(user.email))1196-1197- .. versionadded:: 2.71198- """1199- return select_or_reject(args, kwargs, lambda x: x, True)1200-1201-1202-@contextfilter1203-def do_rejectattr(*args, **kwargs):1204- """Filters a sequence of objects by applying a test to the specified1205- attribute of each object, and rejecting the objects with the test1206- succeeding.1207-1208- If no test is specified, the attribute's value will be evaluated as1209- a boolean.1210-1211- .. sourcecode:: jinja1212-1213- {{ users|rejectattr("is_active") }}1214- {{ users|rejectattr("email", "none") }}1215-1216- Similar to a generator comprehension such as:1217-1218- .. code-block:: python1219-1220- (u for user in users if not user.is_active)1221- (u for user in users if not test_none(user.email))1222-1223- .. versionadded:: 2.71224- """1225- return select_or_reject(args, kwargs, lambda x: not x, True)1226-1227-1228-@evalcontextfilter1229-def do_tojson(eval_ctx, value, indent=None):1230- """Dumps a structure to JSON so that it's safe to use in ``<script>``1231- tags. It accepts the same arguments and returns a JSON string. Note that1232- this is available in templates through the ``|tojson`` filter which will1233- also mark the result as safe. Due to how this function escapes certain1234- characters this is safe even if used outside of ``<script>`` tags.1235-1236- The following characters are escaped in strings:1237-1238- - ``<``1239- - ``>``1240- - ``&``1241- - ``'``1242-1243- This makes it safe to embed such strings in any place in HTML with the1244- notable exception of double quoted attributes. In that case single1245- quote your attributes or HTML escape it in addition.1246-1247- The indent parameter can be used to enable pretty printing. Set it to1248- the number of spaces that the structures should be indented with.1249-1250- Note that this filter is for use in HTML contexts only.1251-1252- .. versionadded:: 2.91253- """1254- policies = eval_ctx.environment.policies1255- dumper = policies["json.dumps_function"]1256- options = policies["json.dumps_kwargs"]1257- if indent is not None:1258- options = dict(options)1259- options["indent"] = indent1260- return htmlsafe_json_dumps(value, dumper=dumper, **options)1261-1262-1263-def prepare_map(args, kwargs):1264- context = args[0]1265- seq = args[1]1266- default = None1267-1268- if len(args) == 2 and "attribute" in kwargs:1269- attribute = kwargs.pop("attribute")1270- default = kwargs.pop("default", None)1271- if kwargs:1272- raise FilterArgumentError(1273- "Unexpected keyword argument %r" % next(iter(kwargs))1274- )1275- func = make_attrgetter(context.environment, attribute, default=default)1276- else:1277- try:1278- name = args[2]1279- args = args[3:]1280- except LookupError:1281- raise FilterArgumentError("map requires a filter argument")1282-1283- def func(item):1284- return context.environment.call_filter(1285- name, item, args, kwargs, context=context1286- )1287-1288- return seq, func1289-1290-1291-def prepare_select_or_reject(args, kwargs, modfunc, lookup_attr):1292- context = args[0]1293- seq = args[1]1294- if lookup_attr:1295- try:1296- attr = args[2]1297- except LookupError:1298- raise FilterArgumentError("Missing parameter for attribute name")1299- transfunc = make_attrgetter(context.environment, attr)1300- off = 11301- else:1302- off = 01303-1304- def transfunc(x):1305- return x1306-1307- try:1308- name = args[2 + off]1309- args = args[3 + off :]1310-1311- def func(item):1312- return context.environment.call_test(name, item, args, kwargs)1313-1314- except LookupError:1315- func = bool1316-1317- return seq, lambda item: modfunc(func(transfunc(item)))1318-1319-1320-def select_or_reject(args, kwargs, modfunc, lookup_attr):1321- seq, func = prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)1322- if seq:1323- for item in seq:1324- if func(item):1325- yield item1326-1327-1328-FILTERS = {1329- "abs": abs,1330- "attr": do_attr,1331- "batch": do_batch,1332- "capitalize": do_capitalize,1333- "center": do_center,1334- "count": len,1335- "d": do_default,1336- "default": do_default,1337- "dictsort": do_dictsort,1338- "e": escape,1339- "escape": escape,1340- "filesizeformat": do_filesizeformat,1341- "first": do_first,1342- "float": do_float,1343- "forceescape": do_forceescape,1344- "format": do_format,1345- "groupby": do_groupby,1346- "indent": do_indent,1347- "int": do_int,1348- "join": do_join,1349- "last": do_last,1350- "length": len,1351- "list": do_list,1352- "lower": do_lower,1353- "map": do_map,1354- "min": do_min,1355- "max": do_max,1356- "pprint": do_pprint,1357- "random": do_random,1358- "reject": do_reject,1359- "rejectattr": do_rejectattr,1360- "replace": do_replace,1361- "reverse": do_reverse,1362- "round": do_round,1363- "safe": do_mark_safe,1364- "select": do_select,1365- "selectattr": do_selectattr,1366- "slice": do_slice,1367- "sort": do_sort,1368- "string": soft_unicode,1369- "striptags": do_striptags,1370- "sum": do_sum,1371- "title": do_title,1372- "trim": do_trim,1373- "truncate": do_truncate,1374- "unique": do_unique,1375- "upper": do_upper,1376- "urlencode": do_urlencode,1377- "urlize": do_urlize,1378- "wordcount": do_wordcount,1379- "wordwrap": do_wordwrap,1380- "xmlattr": do_xmlattr,1381- "tojson": do_tojson,1382-}deleted:src/jinja2/idtracking.py-290 removed
1-from ._compat import iteritems2-from .visitor import NodeVisitor3-4-VAR_LOAD_PARAMETER = "param"5-VAR_LOAD_RESOLVE = "resolve"6-VAR_LOAD_ALIAS = "alias"7-VAR_LOAD_UNDEFINED = "undefined"8-9-10-def find_symbols(nodes, parent_symbols=None):11- sym = Symbols(parent=parent_symbols)12- visitor = FrameSymbolVisitor(sym)13- for node in nodes:14- visitor.visit(node)15- return sym16-17-18-def symbols_for_node(node, parent_symbols=None):19- sym = Symbols(parent=parent_symbols)20- sym.analyze_node(node)21- return sym22-23-24-class Symbols(object):25- def __init__(self, parent=None, level=None):26- if level is None:27- if parent is None:28- level = 029- else:30- level = parent.level + 131- self.level = level32- self.parent = parent33- self.refs = {}34- self.loads = {}35- self.stores = set()36-37- def analyze_node(self, node, **kwargs):38- visitor = RootVisitor(self)39- visitor.visit(node, **kwargs)40-41- def _define_ref(self, name, load=None):42- ident = "l_%d_%s" % (self.level, name)43- self.refs[name] = ident44- if load is not None:45- self.loads[ident] = load46- return ident47-48- def find_load(self, target):49- if target in self.loads:50- return self.loads[target]51- if self.parent is not None:52- return self.parent.find_load(target)53-54- def find_ref(self, name):55- if name in self.refs:56- return self.refs[name]57- if self.parent is not None:58- return self.parent.find_ref(name)59-60- def ref(self, name):61- rv = self.find_ref(name)62- if rv is None:63- raise AssertionError(64- "Tried to resolve a name to a reference that "65- "was unknown to the frame (%r)" % name66- )67- return rv68-69- def copy(self):70- rv = object.__new__(self.__class__)71- rv.__dict__.update(self.__dict__)72- rv.refs = self.refs.copy()73- rv.loads = self.loads.copy()74- rv.stores = self.stores.copy()75- return rv76-77- def store(self, name):78- self.stores.add(name)79-80- # If we have not see the name referenced yet, we need to figure81- # out what to set it to.82- if name not in self.refs:83- # If there is a parent scope we check if the name has a84- # reference there. If it does it means we might have to alias85- # to a variable there.86- if self.parent is not None:87- outer_ref = self.parent.find_ref(name)88- if outer_ref is not None:89- self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref))90- return91-92- # Otherwise we can just set it to undefined.93- self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))94-95- def declare_parameter(self, name):96- self.stores.add(name)97- return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))98-99- def load(self, name):100- target = self.find_ref(name)101- if target is None:102- self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))103-104- def branch_update(self, branch_symbols):105- stores = {}106- for branch in branch_symbols:107- for target in branch.stores:108- if target in self.stores:109- continue110- stores[target] = stores.get(target, 0) + 1111-112- for sym in branch_symbols:113- self.refs.update(sym.refs)114- self.loads.update(sym.loads)115- self.stores.update(sym.stores)116-117- for name, branch_count in iteritems(stores):118- if branch_count == len(branch_symbols):119- continue120- target = self.find_ref(name)121- assert target is not None, "should not happen"122-123- if self.parent is not None:124- outer_target = self.parent.find_ref(name)125- if outer_target is not None:126- self.loads[target] = (VAR_LOAD_ALIAS, outer_target)127- continue128- self.loads[target] = (VAR_LOAD_RESOLVE, name)129-130- def dump_stores(self):131- rv = {}132- node = self133- while node is not None:134- for name in node.stores:135- if name not in rv:136- rv[name] = self.find_ref(name)137- node = node.parent138- return rv139-140- def dump_param_targets(self):141- rv = set()142- node = self143- while node is not None:144- for target, (instr, _) in iteritems(self.loads):145- if instr == VAR_LOAD_PARAMETER:146- rv.add(target)147- node = node.parent148- return rv149-150-151-class RootVisitor(NodeVisitor):152- def __init__(self, symbols):153- self.sym_visitor = FrameSymbolVisitor(symbols)154-155- def _simple_visit(self, node, **kwargs):156- for child in node.iter_child_nodes():157- self.sym_visitor.visit(child)158-159- visit_Template = (160- visit_Block161- ) = (162- visit_Macro163- ) = (164- visit_FilterBlock165- ) = visit_Scope = visit_If = visit_ScopedEvalContextModifier = _simple_visit166-167- def visit_AssignBlock(self, node, **kwargs):168- for child in node.body:169- self.sym_visitor.visit(child)170-171- def visit_CallBlock(self, node, **kwargs):172- for child in node.iter_child_nodes(exclude=("call",)):173- self.sym_visitor.visit(child)174-175- def visit_OverlayScope(self, node, **kwargs):176- for child in node.body:177- self.sym_visitor.visit(child)178-179- def visit_For(self, node, for_branch="body", **kwargs):180- if for_branch == "body":181- self.sym_visitor.visit(node.target, store_as_param=True)182- branch = node.body183- elif for_branch == "else":184- branch = node.else_185- elif for_branch == "test":186- self.sym_visitor.visit(node.target, store_as_param=True)187- if node.test is not None:188- self.sym_visitor.visit(node.test)189- return190- else:191- raise RuntimeError("Unknown for branch")192- for item in branch or ():193- self.sym_visitor.visit(item)194-195- def visit_With(self, node, **kwargs):196- for target in node.targets:197- self.sym_visitor.visit(target)198- for child in node.body:199- self.sym_visitor.visit(child)200-201- def generic_visit(self, node, *args, **kwargs):202- raise NotImplementedError(203- "Cannot find symbols for %r" % node.__class__.__name__204- )205-206-207-class FrameSymbolVisitor(NodeVisitor):208- """A visitor for `Frame.inspect`."""209-210- def __init__(self, symbols):211- self.symbols = symbols212-213- def visit_Name(self, node, store_as_param=False, **kwargs):214- """All assignments to names go through this function."""215- if store_as_param or node.ctx == "param":216- self.symbols.declare_parameter(node.name)217- elif node.ctx == "store":218- self.symbols.store(node.name)219- elif node.ctx == "load":220- self.symbols.load(node.name)221-222- def visit_NSRef(self, node, **kwargs):223- self.symbols.load(node.name)224-225- def visit_If(self, node, **kwargs):226- self.visit(node.test, **kwargs)227-228- original_symbols = self.symbols229-230- def inner_visit(nodes):231- self.symbols = rv = original_symbols.copy()232- for subnode in nodes:233- self.visit(subnode, **kwargs)234- self.symbols = original_symbols235- return rv236-237- body_symbols = inner_visit(node.body)238- elif_symbols = inner_visit(node.elif_)239- else_symbols = inner_visit(node.else_ or ())240-241- self.symbols.branch_update([body_symbols, elif_symbols, else_symbols])242-243- def visit_Macro(self, node, **kwargs):244- self.symbols.store(node.name)245-246- def visit_Import(self, node, **kwargs):247- self.generic_visit(node, **kwargs)248- self.symbols.store(node.target)249-250- def visit_FromImport(self, node, **kwargs):251- self.generic_visit(node, **kwargs)252- for name in node.names:253- if isinstance(name, tuple):254- self.symbols.store(name[1])255- else:256- self.symbols.store(name)257-258- def visit_Assign(self, node, **kwargs):259- """Visit assignments in the correct order."""260- self.visit(node.node, **kwargs)261- self.visit(node.target, **kwargs)262-263- def visit_For(self, node, **kwargs):264- """Visiting stops at for blocks. However the block sequence265- is visited as part of the outer scope.266- """267- self.visit(node.iter, **kwargs)268-269- def visit_CallBlock(self, node, **kwargs):270- self.visit(node.call, **kwargs)271-272- def visit_FilterBlock(self, node, **kwargs):273- self.visit(node.filter, **kwargs)274-275- def visit_With(self, node, **kwargs):276- for target in node.values:277- self.visit(target)278-279- def visit_AssignBlock(self, node, **kwargs):280- """Stop visiting at block assigns."""281- self.visit(node.target, **kwargs)282-283- def visit_Scope(self, node, **kwargs):284- """Stop visiting at scopes."""285-286- def visit_Block(self, node, **kwargs):287- """Stop visiting at blocks."""288-289- def visit_OverlayScope(self, node, **kwargs):290- """Do not visit into overlay scopes."""deleted:src/jinja2/lexer.py-841 removed
1-# -*- coding: utf-8 -*-2-"""Implements a Jinja / Python combination lexer. The ``Lexer`` class3-is used to do some preprocessing. It filters out invalid operators like4-the bitshift operators we don't allow in templates. It separates5-template code and python code in expressions.6-"""7-import re8-from ast import literal_eval9-from collections import deque10-from operator import itemgetter11-12-from ._compat import implements_iterator13-from ._compat import intern14-from ._compat import iteritems15-from ._compat import text_type16-from .exceptions import TemplateSyntaxError17-from .utils import LRUCache18-19-# cache for the lexers. Exists in order to be able to have multiple20-# environments with the same lexer21-_lexer_cache = LRUCache(50)22-23-# static regular expressions24-whitespace_re = re.compile(r"\s+", re.U)25-newline_re = re.compile(r"(\r\n|\r|\n)")26-string_re = re.compile(27- r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S28-)29-integer_re = re.compile(r"(\d+_)*\d+")30-float_re = re.compile(31- r"""32- (?<!\.) # doesn't start with a .33- (\d+_)*\d+ # digits, possibly _ separated34- (35- (\.(\d+_)*\d+)? # optional fractional part36- e[+\-]?(\d+_)*\d+ # exponent part37- |38- \.(\d+_)*\d+ # required fractional part39- )40- """,41- re.IGNORECASE | re.VERBOSE,42-)43-44-try:45- # check if this Python supports Unicode identifiers46- compile("föö", "<unknown>", "eval")47-except SyntaxError:48- # Python 2, no Unicode support, use ASCII identifiers49- name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*")50- check_ident = False51-else:52- # Unicode support, import generated re pattern and set flag to use53- # str.isidentifier to validate during lexing.54- from ._identifier import pattern as name_re55-56- check_ident = True57-58-# internal the tokens and keep references to them59-TOKEN_ADD = intern("add")60-TOKEN_ASSIGN = intern("assign")61-TOKEN_COLON = intern("colon")62-TOKEN_COMMA = intern("comma")63-TOKEN_DIV = intern("div")64-TOKEN_DOT = intern("dot")65-TOKEN_EQ = intern("eq")66-TOKEN_FLOORDIV = intern("floordiv")67-TOKEN_GT = intern("gt")68-TOKEN_GTEQ = intern("gteq")69-TOKEN_LBRACE = intern("lbrace")70-TOKEN_LBRACKET = intern("lbracket")71-TOKEN_LPAREN = intern("lparen")72-TOKEN_LT = intern("lt")73-TOKEN_LTEQ = intern("lteq")74-TOKEN_MOD = intern("mod")75-TOKEN_MUL = intern("mul")76-TOKEN_NE = intern("ne")77-TOKEN_PIPE = intern("pipe")78-TOKEN_POW = intern("pow")79-TOKEN_RBRACE = intern("rbrace")80-TOKEN_RBRACKET = intern("rbracket")81-TOKEN_RPAREN = intern("rparen")82-TOKEN_SEMICOLON = intern("semicolon")83-TOKEN_SUB = intern("sub")84-TOKEN_TILDE = intern("tilde")85-TOKEN_WHITESPACE = intern("whitespace")86-TOKEN_FLOAT = intern("float")87-TOKEN_INTEGER = intern("integer")88-TOKEN_NAME = intern("name")89-TOKEN_STRING = intern("string")90-TOKEN_OPERATOR = intern("operator")91-TOKEN_BLOCK_BEGIN = intern("block_begin")92-TOKEN_BLOCK_END = intern("block_end")93-TOKEN_VARIABLE_BEGIN = intern("variable_begin")94-TOKEN_VARIABLE_END = intern("variable_end")95-TOKEN_RAW_BEGIN = intern("raw_begin")96-TOKEN_RAW_END = intern("raw_end")97-TOKEN_COMMENT_BEGIN = intern("comment_begin")98-TOKEN_COMMENT_END = intern("comment_end")99-TOKEN_COMMENT = intern("comment")100-TOKEN_LINESTATEMENT_BEGIN = intern("linestatement_begin")101-TOKEN_LINESTATEMENT_END = intern("linestatement_end")102-TOKEN_LINECOMMENT_BEGIN = intern("linecomment_begin")103-TOKEN_LINECOMMENT_END = intern("linecomment_end")104-TOKEN_LINECOMMENT = intern("linecomment")105-TOKEN_DATA = intern("data")106-TOKEN_INITIAL = intern("initial")107-TOKEN_EOF = intern("eof")108-109-# bind operators to token types110-operators = {111- "+": TOKEN_ADD,112- "-": TOKEN_SUB,113- "/": TOKEN_DIV,114- "//": TOKEN_FLOORDIV,115- "*": TOKEN_MUL,116- "%": TOKEN_MOD,117- "**": TOKEN_POW,118- "~": TOKEN_TILDE,119- "[": TOKEN_LBRACKET,120- "]": TOKEN_RBRACKET,121- "(": TOKEN_LPAREN,122- ")": TOKEN_RPAREN,123- "{": TOKEN_LBRACE,124- "}": TOKEN_RBRACE,125- "==": TOKEN_EQ,126- "!=": TOKEN_NE,127- ">": TOKEN_GT,128- ">=": TOKEN_GTEQ,129- "<": TOKEN_LT,130- "<=": TOKEN_LTEQ,131- "=": TOKEN_ASSIGN,132- ".": TOKEN_DOT,133- ":": TOKEN_COLON,134- "|": TOKEN_PIPE,135- ",": TOKEN_COMMA,136- ";": TOKEN_SEMICOLON,137-}138-139-reverse_operators = dict([(v, k) for k, v in iteritems(operators)])140-assert len(operators) == len(reverse_operators), "operators dropped"141-operator_re = re.compile(142- "(%s)" % "|".join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))143-)144-145-ignored_tokens = frozenset(146- [147- TOKEN_COMMENT_BEGIN,148- TOKEN_COMMENT,149- TOKEN_COMMENT_END,150- TOKEN_WHITESPACE,151- TOKEN_LINECOMMENT_BEGIN,152- TOKEN_LINECOMMENT_END,153- TOKEN_LINECOMMENT,154- ]155-)156-ignore_if_empty = frozenset(157- [TOKEN_WHITESPACE, TOKEN_DATA, TOKEN_COMMENT, TOKEN_LINECOMMENT]158-)159-160-161-def _describe_token_type(token_type):162- if token_type in reverse_operators:163- return reverse_operators[token_type]164- return {165- TOKEN_COMMENT_BEGIN: "begin of comment",166- TOKEN_COMMENT_END: "end of comment",167- TOKEN_COMMENT: "comment",168- TOKEN_LINECOMMENT: "comment",169- TOKEN_BLOCK_BEGIN: "begin of statement block",170- TOKEN_BLOCK_END: "end of statement block",171- TOKEN_VARIABLE_BEGIN: "begin of print statement",172- TOKEN_VARIABLE_END: "end of print statement",173- TOKEN_LINESTATEMENT_BEGIN: "begin of line statement",174- TOKEN_LINESTATEMENT_END: "end of line statement",175- TOKEN_DATA: "template data / text",176- TOKEN_EOF: "end of template",177- }.get(token_type, token_type)178-179-180-def describe_token(token):181- """Returns a description of the token."""182- if token.type == TOKEN_NAME:183- return token.value184- return _describe_token_type(token.type)185-186-187-def describe_token_expr(expr):188- """Like `describe_token` but for token expressions."""189- if ":" in expr:190- type, value = expr.split(":", 1)191- if type == TOKEN_NAME:192- return value193- else:194- type = expr195- return _describe_token_type(type)196-197-198-def count_newlines(value):199- """Count the number of newline characters in the string. This is200- useful for extensions that filter a stream.201- """202- return len(newline_re.findall(value))203-204-205-def compile_rules(environment):206- """Compiles all the rules from the environment into a list of rules."""207- e = re.escape208- rules = [209- (210- len(environment.comment_start_string),211- TOKEN_COMMENT_BEGIN,212- e(environment.comment_start_string),213- ),214- (215- len(environment.block_start_string),216- TOKEN_BLOCK_BEGIN,217- e(environment.block_start_string),218- ),219- (220- len(environment.variable_start_string),221- TOKEN_VARIABLE_BEGIN,222- e(environment.variable_start_string),223- ),224- ]225-226- if environment.line_statement_prefix is not None:227- rules.append(228- (229- len(environment.line_statement_prefix),230- TOKEN_LINESTATEMENT_BEGIN,231- r"^[ \t\v]*" + e(environment.line_statement_prefix),232- )233- )234- if environment.line_comment_prefix is not None:235- rules.append(236- (237- len(environment.line_comment_prefix),238- TOKEN_LINECOMMENT_BEGIN,239- r"(?:^|(?<=\S))[^\S\r\n]*" + e(environment.line_comment_prefix),240- )241- )242-243- return [x[1:] for x in sorted(rules, reverse=True)]244-245-246-class Failure(object):247- """Class that raises a `TemplateSyntaxError` if called.248- Used by the `Lexer` to specify known errors.249- """250-251- def __init__(self, message, cls=TemplateSyntaxError):252- self.message = message253- self.error_class = cls254-255- def __call__(self, lineno, filename):256- raise self.error_class(self.message, lineno, filename)257-258-259-class Token(tuple):260- """Token class."""261-262- __slots__ = ()263- lineno, type, value = (property(itemgetter(x)) for x in range(3))264-265- def __new__(cls, lineno, type, value):266- return tuple.__new__(cls, (lineno, intern(str(type)), value))267-268- def __str__(self):269- if self.type in reverse_operators:270- return reverse_operators[self.type]271- elif self.type == "name":272- return self.value273- return self.type274-275- def test(self, expr):276- """Test a token against a token expression. This can either be a277- token type or ``'token_type:token_value'``. This can only test278- against string values and types.279- """280- # here we do a regular string equality check as test_any is usually281- # passed an iterable of not interned strings.282- if self.type == expr:283- return True284- elif ":" in expr:285- return expr.split(":", 1) == [self.type, self.value]286- return False287-288- def test_any(self, *iterable):289- """Test against multiple token expressions."""290- for expr in iterable:291- if self.test(expr):292- return True293- return False294-295- def __repr__(self):296- return "Token(%r, %r, %r)" % (self.lineno, self.type, self.value)297-298-299-@implements_iterator300-class TokenStreamIterator(object):301- """The iterator for tokenstreams. Iterate over the stream302- until the eof token is reached.303- """304-305- def __init__(self, stream):306- self.stream = stream307-308- def __iter__(self):309- return self310-311- def __next__(self):312- token = self.stream.current313- if token.type is TOKEN_EOF:314- self.stream.close()315- raise StopIteration()316- next(self.stream)317- return token318-319-320-@implements_iterator321-class TokenStream(object):322- """A token stream is an iterable that yields :class:`Token`\\s. The323- parser however does not iterate over it but calls :meth:`next` to go324- one token ahead. The current active token is stored as :attr:`current`.325- """326-327- def __init__(self, generator, name, filename):328- self._iter = iter(generator)329- self._pushed = deque()330- self.name = name331- self.filename = filename332- self.closed = False333- self.current = Token(1, TOKEN_INITIAL, "")334- next(self)335-336- def __iter__(self):337- return TokenStreamIterator(self)338-339- def __bool__(self):340- return bool(self._pushed) or self.current.type is not TOKEN_EOF341-342- __nonzero__ = __bool__ # py2343-344- @property345- def eos(self):346- """Are we at the end of the stream?"""347- return not self348-349- def push(self, token):350- """Push a token back to the stream."""351- self._pushed.append(token)352-353- def look(self):354- """Look at the next token."""355- old_token = next(self)356- result = self.current357- self.push(result)358- self.current = old_token359- return result360-361- def skip(self, n=1):362- """Got n tokens ahead."""363- for _ in range(n):364- next(self)365-366- def next_if(self, expr):367- """Perform the token test and return the token if it matched.368- Otherwise the return value is `None`.369- """370- if self.current.test(expr):371- return next(self)372-373- def skip_if(self, expr):374- """Like :meth:`next_if` but only returns `True` or `False`."""375- return self.next_if(expr) is not None376-377- def __next__(self):378- """Go one token ahead and return the old one.379-380- Use the built-in :func:`next` instead of calling this directly.381- """382- rv = self.current383- if self._pushed:384- self.current = self._pushed.popleft()385- elif self.current.type is not TOKEN_EOF:386- try:387- self.current = next(self._iter)388- except StopIteration:389- self.close()390- return rv391-392- def close(self):393- """Close the stream."""394- self.current = Token(self.current.lineno, TOKEN_EOF, "")395- self._iter = None396- self.closed = True397-398- def expect(self, expr):399- """Expect a given token type and return it. This accepts the same400- argument as :meth:`jinja2.lexer.Token.test`.401- """402- if not self.current.test(expr):403- expr = describe_token_expr(expr)404- if self.current.type is TOKEN_EOF:405- raise TemplateSyntaxError(406- "unexpected end of template, expected %r." % expr,407- self.current.lineno,408- self.name,409- self.filename,410- )411- raise TemplateSyntaxError(412- "expected token %r, got %r" % (expr, describe_token(self.current)),413- self.current.lineno,414- self.name,415- self.filename,416- )417- try:418- return self.current419- finally:420- next(self)421-422-423-def get_lexer(environment):424- """Return a lexer which is probably cached."""425- key = (426- environment.block_start_string,427- environment.block_end_string,428- environment.variable_start_string,429- environment.variable_end_string,430- environment.comment_start_string,431- environment.comment_end_string,432- environment.line_statement_prefix,433- environment.line_comment_prefix,434- environment.trim_blocks,435- environment.lstrip_blocks,436- environment.newline_sequence,437- environment.keep_trailing_newline,438- )439- lexer = _lexer_cache.get(key)440- if lexer is None:441- lexer = Lexer(environment)442- _lexer_cache[key] = lexer443- return lexer444-445-446-class OptionalLStrip(tuple):447- """A special tuple for marking a point in the state that can have448- lstrip applied.449- """450-451- __slots__ = ()452-453- # Even though it looks like a no-op, creating instances fails454- # without this.455- def __new__(cls, *members, **kwargs):456- return super(OptionalLStrip, cls).__new__(cls, members)457-458-459-class Lexer(object):460- """Class that implements a lexer for a given environment. Automatically461- created by the environment class, usually you don't have to do that.462-463- Note that the lexer is not automatically bound to an environment.464- Multiple environments can share the same lexer.465- """466-467- def __init__(self, environment):468- # shortcuts469- e = re.escape470-471- def c(x):472- return re.compile(x, re.M | re.S)473-474- # lexing rules for tags475- tag_rules = [476- (whitespace_re, TOKEN_WHITESPACE, None),477- (float_re, TOKEN_FLOAT, None),478- (integer_re, TOKEN_INTEGER, None),479- (name_re, TOKEN_NAME, None),480- (string_re, TOKEN_STRING, None),481- (operator_re, TOKEN_OPERATOR, None),482- ]483-484- # assemble the root lexing rule. because "|" is ungreedy485- # we have to sort by length so that the lexer continues working486- # as expected when we have parsing rules like <% for block and487- # <%= for variables. (if someone wants asp like syntax)488- # variables are just part of the rules if variable processing489- # is required.490- root_tag_rules = compile_rules(environment)491-492- # block suffix if trimming is enabled493- block_suffix_re = environment.trim_blocks and "\\n?" or ""494-495- # If lstrip is enabled, it should not be applied if there is any496- # non-whitespace between the newline and block.497- self.lstrip_unless_re = c(r"[^ \t]") if environment.lstrip_blocks else None498-499- self.newline_sequence = environment.newline_sequence500- self.keep_trailing_newline = environment.keep_trailing_newline501-502- # global lexing rules503- self.rules = {504- "root": [505- # directives506- (507- c(508- "(.*?)(?:%s)"509- % "|".join(510- [511- r"(?P<raw_begin>%s(\-|\+|)\s*raw\s*(?:\-%s\s*|%s))"512- % (513- e(environment.block_start_string),514- e(environment.block_end_string),515- e(environment.block_end_string),516- )517- ]518- + [519- r"(?P<%s>%s(\-|\+|))" % (n, r)520- for n, r in root_tag_rules521- ]522- )523- ),524- OptionalLStrip(TOKEN_DATA, "#bygroup"),525- "#bygroup",526- ),527- # data528- (c(".+"), TOKEN_DATA, None),529- ],530- # comments531- TOKEN_COMMENT_BEGIN: [532- (533- c(534- r"(.*?)((?:\-%s\s*|%s)%s)"535- % (536- e(environment.comment_end_string),537- e(environment.comment_end_string),538- block_suffix_re,539- )540- ),541- (TOKEN_COMMENT, TOKEN_COMMENT_END),542- "#pop",543- ),544- (c("(.)"), (Failure("Missing end of comment tag"),), None),545- ],546- # blocks547- TOKEN_BLOCK_BEGIN: [548- (549- c(550- r"(?:\-%s\s*|%s)%s"551- % (552- e(environment.block_end_string),553- e(environment.block_end_string),554- block_suffix_re,555- )556- ),557- TOKEN_BLOCK_END,558- "#pop",559- ),560- ]561- + tag_rules,562- # variables563- TOKEN_VARIABLE_BEGIN: [564- (565- c(566- r"\-%s\s*|%s"567- % (568- e(environment.variable_end_string),569- e(environment.variable_end_string),570- )571- ),572- TOKEN_VARIABLE_END,573- "#pop",574- )575- ]576- + tag_rules,577- # raw block578- TOKEN_RAW_BEGIN: [579- (580- c(581- r"(.*?)((?:%s(\-|\+|))\s*endraw\s*(?:\-%s\s*|%s%s))"582- % (583- e(environment.block_start_string),584- e(environment.block_end_string),585- e(environment.block_end_string),586- block_suffix_re,587- )588- ),589- OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END),590- "#pop",591- ),592- (c("(.)"), (Failure("Missing end of raw directive"),), None),593- ],594- # line statements595- TOKEN_LINESTATEMENT_BEGIN: [596- (c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")597- ]598- + tag_rules,599- # line comments600- TOKEN_LINECOMMENT_BEGIN: [601- (602- c(r"(.*?)()(?=\n|$)"),603- (TOKEN_LINECOMMENT, TOKEN_LINECOMMENT_END),604- "#pop",605- )606- ],607- }608-609- def _normalize_newlines(self, value):610- """Called for strings and template data to normalize it to unicode."""611- return newline_re.sub(self.newline_sequence, value)612-613- def tokenize(self, source, name=None, filename=None, state=None):614- """Calls tokeniter + tokenize and wraps it in a token stream."""615- stream = self.tokeniter(source, name, filename, state)616- return TokenStream(self.wrap(stream, name, filename), name, filename)617-618- def wrap(self, stream, name=None, filename=None):619- """This is called with the stream as returned by `tokenize` and wraps620- every token in a :class:`Token` and converts the value.621- """622- for lineno, token, value in stream:623- if token in ignored_tokens:624- continue625- elif token == TOKEN_LINESTATEMENT_BEGIN:626- token = TOKEN_BLOCK_BEGIN627- elif token == TOKEN_LINESTATEMENT_END:628- token = TOKEN_BLOCK_END629- # we are not interested in those tokens in the parser630- elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END):631- continue632- elif token == TOKEN_DATA:633- value = self._normalize_newlines(value)634- elif token == "keyword":635- token = value636- elif token == TOKEN_NAME:637- value = str(value)638- if check_ident and not value.isidentifier():639- raise TemplateSyntaxError(640- "Invalid character in identifier", lineno, name, filename641- )642- elif token == TOKEN_STRING:643- # try to unescape string644- try:645- value = (646- self._normalize_newlines(value[1:-1])647- .encode("ascii", "backslashreplace")648- .decode("unicode-escape")649- )650- except Exception as e:651- msg = str(e).split(":")[-1].strip()652- raise TemplateSyntaxError(msg, lineno, name, filename)653- elif token == TOKEN_INTEGER:654- value = int(value.replace("_", ""))655- elif token == TOKEN_FLOAT:656- # remove all "_" first to support more Python versions657- value = literal_eval(value.replace("_", ""))658- elif token == TOKEN_OPERATOR:659- token = operators[value]660- yield Token(lineno, token, value)661-662- def tokeniter(self, source, name, filename=None, state=None):663- """This method tokenizes the text and returns the tokens in a664- generator. Use this method if you just want to tokenize a template.665- """666- source = text_type(source)667- lines = source.splitlines()668- if self.keep_trailing_newline and source:669- for newline in ("\r\n", "\r", "\n"):670- if source.endswith(newline):671- lines.append("")672- break673- source = "\n".join(lines)674- pos = 0675- lineno = 1676- stack = ["root"]677- if state is not None and state != "root":678- assert state in ("variable", "block"), "invalid state"679- stack.append(state + "_begin")680- statetokens = self.rules[stack[-1]]681- source_length = len(source)682- balancing_stack = []683- lstrip_unless_re = self.lstrip_unless_re684-685- while 1:686- # tokenizer loop687- for regex, tokens, new_state in statetokens:688- m = regex.match(source, pos)689- # if no match we try again with the next rule690- if m is None:691- continue692-693- # we only match blocks and variables if braces / parentheses694- # are balanced. continue parsing with the lower rule which695- # is the operator rule. do this only if the end tags look696- # like operators697- if balancing_stack and tokens in (698- TOKEN_VARIABLE_END,699- TOKEN_BLOCK_END,700- TOKEN_LINESTATEMENT_END,701- ):702- continue703-704- # tuples support more options705- if isinstance(tokens, tuple):706- groups = m.groups()707-708- if isinstance(tokens, OptionalLStrip):709- # Rule supports lstrip. Match will look like710- # text, block type, whitespace control, type, control, ...711- text = groups[0]712-713- # Skipping the text and first type, every other group is the714- # whitespace control for each type. One of the groups will be715- # -, +, or empty string instead of None.716- strip_sign = next(g for g in groups[2::2] if g is not None)717-718- if strip_sign == "-":719- # Strip all whitespace between the text and the tag.720- groups = (text.rstrip(),) + groups[1:]721- elif (722- # Not marked for preserving whitespace.723- strip_sign != "+"724- # lstrip is enabled.725- and lstrip_unless_re is not None726- # Not a variable expression.727- and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)728- ):729- # The start of text between the last newline and the tag.730- l_pos = text.rfind("\n") + 1731-732- # If there's only whitespace between the newline and the733- # tag, strip it.734- if not lstrip_unless_re.search(text, l_pos):735- groups = (text[:l_pos],) + groups[1:]736-737- for idx, token in enumerate(tokens):738- # failure group739- if token.__class__ is Failure:740- raise token(lineno, filename)741- # bygroup is a bit more complex, in that case we742- # yield for the current token the first named743- # group that matched744- elif token == "#bygroup":745- for key, value in iteritems(m.groupdict()):746- if value is not None:747- yield lineno, key, value748- lineno += value.count("\n")749- break750- else:751- raise RuntimeError(752- "%r wanted to resolve "753- "the token dynamically"754- " but no group matched" % regex755- )756- # normal group757- else:758- data = groups[idx]759- if data or token not in ignore_if_empty:760- yield lineno, token, data761- lineno += data.count("\n")762-763- # strings as token just are yielded as it.764- else:765- data = m.group()766- # update brace/parentheses balance767- if tokens == TOKEN_OPERATOR:768- if data == "{":769- balancing_stack.append("}")770- elif data == "(":771- balancing_stack.append(")")772- elif data == "[":773- balancing_stack.append("]")774- elif data in ("}", ")", "]"):775- if not balancing_stack:776- raise TemplateSyntaxError(777- "unexpected '%s'" % data, lineno, name, filename778- )779- expected_op = balancing_stack.pop()780- if expected_op != data:781- raise TemplateSyntaxError(782- "unexpected '%s', "783- "expected '%s'" % (data, expected_op),784- lineno,785- name,786- filename,787- )788- # yield items789- if data or tokens not in ignore_if_empty:790- yield lineno, tokens, data791- lineno += data.count("\n")792-793- # fetch new position into new variable so that we can check794- # if there is a internal parsing error which would result795- # in an infinite loop796- pos2 = m.end()797-798- # handle state changes799- if new_state is not None:800- # remove the uppermost state801- if new_state == "#pop":802- stack.pop()803- # resolve the new state by group checking804- elif new_state == "#bygroup":805- for key, value in iteritems(m.groupdict()):806- if value is not None:807- stack.append(key)808- break809- else:810- raise RuntimeError(811- "%r wanted to resolve the "812- "new state dynamically but"813- " no group matched" % regex814- )815- # direct state name given816- else:817- stack.append(new_state)818- statetokens = self.rules[stack[-1]]819- # we are still at the same position and no stack change.820- # this means a loop without break condition, avoid that and821- # raise error822- elif pos2 == pos:823- raise RuntimeError(824- "%r yielded empty string without stack change" % regex825- )826- # publish new function and start again827- pos = pos2828- break829- # if loop terminated without break we haven't found a single match830- # either we are at the end of the file or we have a problem831- else:832- # end of text833- if pos >= source_length:834- return835- # something went wrong836- raise TemplateSyntaxError(837- "unexpected char %r at %d" % (source[pos], pos),838- lineno,839- name,840- filename,841- )deleted:src/jinja2/loaders.py-572 removed
1-# -*- coding: utf-8 -*-2-"""API and implementations for loading templates from different data3-sources.4-"""5-import os6-import pkgutil7-import sys8-import weakref9-from hashlib import sha110-from importlib import import_module11-from os import path12-from types import ModuleType13-14-from ._compat import abc15-from ._compat import fspath16-from ._compat import iteritems17-from ._compat import string_types18-from .exceptions import TemplateNotFound19-from .utils import internalcode20-from .utils import open_if_exists21-22-23-def split_template_path(template):24- """Split a path into segments and perform a sanity check. If it detects25- '..' in the path it will raise a `TemplateNotFound` error.26- """27- pieces = []28- for piece in template.split("/"):29- if (30- path.sep in piece31- or (path.altsep and path.altsep in piece)32- or piece == path.pardir33- ):34- raise TemplateNotFound(template)35- elif piece and piece != ".":36- pieces.append(piece)37- return pieces38-39-40-class BaseLoader(object):41- """Baseclass for all loaders. Subclass this and override `get_source` to42- implement a custom loading mechanism. The environment provides a43- `get_template` method that calls the loader's `load` method to get the44- :class:`Template` object.45-46- A very basic example for a loader that looks up templates on the file47- system could look like this::48-49- from jinja2 import BaseLoader, TemplateNotFound50- from os.path import join, exists, getmtime51-52- class MyLoader(BaseLoader):53-54- def __init__(self, path):55- self.path = path56-57- def get_source(self, environment, template):58- path = join(self.path, template)59- if not exists(path):60- raise TemplateNotFound(template)61- mtime = getmtime(path)62- with file(path) as f:63- source = f.read().decode('utf-8')64- return source, path, lambda: mtime == getmtime(path)65- """66-67- #: if set to `False` it indicates that the loader cannot provide access68- #: to the source of templates.69- #:70- #: .. versionadded:: 2.471- has_source_access = True72-73- def get_source(self, environment, template):74- """Get the template source, filename and reload helper for a template.75- It's passed the environment and template name and has to return a76- tuple in the form ``(source, filename, uptodate)`` or raise a77- `TemplateNotFound` error if it can't locate the template.78-79- The source part of the returned tuple must be the source of the80- template as unicode string or a ASCII bytestring. The filename should81- be the name of the file on the filesystem if it was loaded from there,82- otherwise `None`. The filename is used by python for the tracebacks83- if no loader extension is used.84-85- The last item in the tuple is the `uptodate` function. If auto86- reloading is enabled it's always called to check if the template87- changed. No arguments are passed so the function must store the88- old state somewhere (for example in a closure). If it returns `False`89- the template will be reloaded.90- """91- if not self.has_source_access:92- raise RuntimeError(93- "%s cannot provide access to the source" % self.__class__.__name__94- )95- raise TemplateNotFound(template)96-97- def list_templates(self):98- """Iterates over all templates. If the loader does not support that99- it should raise a :exc:`TypeError` which is the default behavior.100- """101- raise TypeError("this loader cannot iterate over all templates")102-103- @internalcode104- def load(self, environment, name, globals=None):105- """Loads a template. This method looks up the template in the cache106- or loads one by calling :meth:`get_source`. Subclasses should not107- override this method as loaders working on collections of other108- loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)109- will not call this method but `get_source` directly.110- """111- code = None112- if globals is None:113- globals = {}114-115- # first we try to get the source for this template together116- # with the filename and the uptodate function.117- source, filename, uptodate = self.get_source(environment, name)118-119- # try to load the code from the bytecode cache if there is a120- # bytecode cache configured.121- bcc = environment.bytecode_cache122- if bcc is not None:123- bucket = bcc.get_bucket(environment, name, filename, source)124- code = bucket.code125-126- # if we don't have code so far (not cached, no longer up to127- # date) etc. we compile the template128- if code is None:129- code = environment.compile(source, name, filename)130-131- # if the bytecode cache is available and the bucket doesn't132- # have a code so far, we give the bucket the new code and put133- # it back to the bytecode cache.134- if bcc is not None and bucket.code is None:135- bucket.code = code136- bcc.set_bucket(bucket)137-138- return environment.template_class.from_code(139- environment, code, globals, uptodate140- )141-142-143-class FileSystemLoader(BaseLoader):144- """Loads templates from the file system. This loader can find templates145- in folders on the file system and is the preferred way to load them.146-147- The loader takes the path to the templates as string, or if multiple148- locations are wanted a list of them which is then looked up in the149- given order::150-151- >>> loader = FileSystemLoader('/path/to/templates')152- >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])153-154- Per default the template encoding is ``'utf-8'`` which can be changed155- by setting the `encoding` parameter to something else.156-157- To follow symbolic links, set the *followlinks* parameter to ``True``::158-159- >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)160-161- .. versionchanged:: 2.8162- The ``followlinks`` parameter was added.163- """164-165- def __init__(self, searchpath, encoding="utf-8", followlinks=False):166- if not isinstance(searchpath, abc.Iterable) or isinstance(167- searchpath, string_types168- ):169- searchpath = [searchpath]170-171- # In Python 3.5, os.path.join doesn't support Path. This can be172- # simplified to list(searchpath) when Python 3.5 is dropped.173- self.searchpath = [fspath(p) for p in searchpath]174-175- self.encoding = encoding176- self.followlinks = followlinks177-178- def get_source(self, environment, template):179- pieces = split_template_path(template)180- for searchpath in self.searchpath:181- filename = path.join(searchpath, *pieces)182- f = open_if_exists(filename)183- if f is None:184- continue185- try:186- contents = f.read().decode(self.encoding)187- finally:188- f.close()189-190- mtime = path.getmtime(filename)191-192- def uptodate():193- try:194- return path.getmtime(filename) == mtime195- except OSError:196- return False197-198- return contents, filename, uptodate199- raise TemplateNotFound(template)200-201- def list_templates(self):202- found = set()203- for searchpath in self.searchpath:204- walk_dir = os.walk(searchpath, followlinks=self.followlinks)205- for dirpath, _, filenames in walk_dir:206- for filename in filenames:207- template = (208- os.path.join(dirpath, filename)[len(searchpath) :]209- .strip(os.path.sep)210- .replace(os.path.sep, "/")211- )212- if template[:2] == "./":213- template = template[2:]214- if template not in found:215- found.add(template)216- return sorted(found)217-218-219-class PackageLoader(BaseLoader):220- """Load templates from a directory in a Python package.221-222- :param package_name: Import name of the package that contains the223- template directory.224- :param package_path: Directory within the imported package that225- contains the templates.226- :param encoding: Encoding of template files.227-228- The following example looks up templates in the ``pages`` directory229- within the ``project.ui`` package.230-231- .. code-block:: python232-233- loader = PackageLoader("project.ui", "pages")234-235- Only packages installed as directories (standard pip behavior) or236- zip/egg files (less common) are supported. The Python API for237- introspecting data in packages is too limited to support other238- installation methods the way this loader requires.239-240- There is limited support for :pep:`420` namespace packages. The241- template directory is assumed to only be in one namespace242- contributor. Zip files contributing to a namespace are not243- supported.244-245- .. versionchanged:: 2.11.0246- No longer uses ``setuptools`` as a dependency.247-248- .. versionchanged:: 2.11.0249- Limited PEP 420 namespace package support.250- """251-252- def __init__(self, package_name, package_path="templates", encoding="utf-8"):253- if package_path == os.path.curdir:254- package_path = ""255- elif package_path[:2] == os.path.curdir + os.path.sep:256- package_path = package_path[2:]257-258- package_path = os.path.normpath(package_path).rstrip(os.path.sep)259- self.package_path = package_path260- self.package_name = package_name261- self.encoding = encoding262-263- # Make sure the package exists. This also makes namespace264- # packages work, otherwise get_loader returns None.265- import_module(package_name)266- self._loader = loader = pkgutil.get_loader(package_name)267-268- # Zip loader's archive attribute points at the zip.269- self._archive = getattr(loader, "archive", None)270- self._template_root = None271-272- if hasattr(loader, "get_filename"):273- # A standard directory package, or a zip package.274- self._template_root = os.path.join(275- os.path.dirname(loader.get_filename(package_name)), package_path276- )277- elif hasattr(loader, "_path"):278- # A namespace package, limited support. Find the first279- # contributor with the template directory.280- for root in loader._path:281- root = os.path.join(root, package_path)282-283- if os.path.isdir(root):284- self._template_root = root285- break286-287- if self._template_root is None:288- raise ValueError(289- "The %r package was not installed in a way that"290- " PackageLoader understands." % package_name291- )292-293- def get_source(self, environment, template):294- p = os.path.join(self._template_root, *split_template_path(template))295-296- if self._archive is None:297- # Package is a directory.298- if not os.path.isfile(p):299- raise TemplateNotFound(template)300-301- with open(p, "rb") as f:302- source = f.read()303-304- mtime = os.path.getmtime(p)305-306- def up_to_date():307- return os.path.isfile(p) and os.path.getmtime(p) == mtime308-309- else:310- # Package is a zip file.311- try:312- source = self._loader.get_data(p)313- except OSError:314- raise TemplateNotFound(template)315-316- # Could use the zip's mtime for all template mtimes, but317- # would need to safely reload the module if it's out of318- # date, so just report it as always current.319- up_to_date = None320-321- return source.decode(self.encoding), p, up_to_date322-323- def list_templates(self):324- results = []325-326- if self._archive is None:327- # Package is a directory.328- offset = len(self._template_root)329-330- for dirpath, _, filenames in os.walk(self._template_root):331- dirpath = dirpath[offset:].lstrip(os.path.sep)332- results.extend(333- os.path.join(dirpath, name).replace(os.path.sep, "/")334- for name in filenames335- )336- else:337- if not hasattr(self._loader, "_files"):338- raise TypeError(339- "This zip import does not have the required"340- " metadata to list templates."341- )342-343- # Package is a zip file.344- prefix = (345- self._template_root[len(self._archive) :].lstrip(os.path.sep)346- + os.path.sep347- )348- offset = len(prefix)349-350- for name in self._loader._files.keys():351- # Find names under the templates directory that aren't directories.352- if name.startswith(prefix) and name[-1] != os.path.sep:353- results.append(name[offset:].replace(os.path.sep, "/"))354-355- results.sort()356- return results357-358-359-class DictLoader(BaseLoader):360- """Loads a template from a python dict. It's passed a dict of unicode361- strings bound to template names. This loader is useful for unittesting:362-363- >>> loader = DictLoader({'index.html': 'source here'})364-365- Because auto reloading is rarely useful this is disabled per default.366- """367-368- def __init__(self, mapping):369- self.mapping = mapping370-371- def get_source(self, environment, template):372- if template in self.mapping:373- source = self.mapping[template]374- return source, None, lambda: source == self.mapping.get(template)375- raise TemplateNotFound(template)376-377- def list_templates(self):378- return sorted(self.mapping)379-380-381-class FunctionLoader(BaseLoader):382- """A loader that is passed a function which does the loading. The383- function receives the name of the template and has to return either384- an unicode string with the template source, a tuple in the form ``(source,385- filename, uptodatefunc)`` or `None` if the template does not exist.386-387- >>> def load_template(name):388- ... if name == 'index.html':389- ... return '...'390- ...391- >>> loader = FunctionLoader(load_template)392-393- The `uptodatefunc` is a function that is called if autoreload is enabled394- and has to return `True` if the template is still up to date. For more395- details have a look at :meth:`BaseLoader.get_source` which has the same396- return value.397- """398-399- def __init__(self, load_func):400- self.load_func = load_func401-402- def get_source(self, environment, template):403- rv = self.load_func(template)404- if rv is None:405- raise TemplateNotFound(template)406- elif isinstance(rv, string_types):407- return rv, None, None408- return rv409-410-411-class PrefixLoader(BaseLoader):412- """A loader that is passed a dict of loaders where each loader is bound413- to a prefix. The prefix is delimited from the template by a slash per414- default, which can be changed by setting the `delimiter` argument to415- something else::416-417- loader = PrefixLoader({418- 'app1': PackageLoader('mypackage.app1'),419- 'app2': PackageLoader('mypackage.app2')420- })421-422- By loading ``'app1/index.html'`` the file from the app1 package is loaded,423- by loading ``'app2/index.html'`` the file from the second.424- """425-426- def __init__(self, mapping, delimiter="/"):427- self.mapping = mapping428- self.delimiter = delimiter429-430- def get_loader(self, template):431- try:432- prefix, name = template.split(self.delimiter, 1)433- loader = self.mapping[prefix]434- except (ValueError, KeyError):435- raise TemplateNotFound(template)436- return loader, name437-438- def get_source(self, environment, template):439- loader, name = self.get_loader(template)440- try:441- return loader.get_source(environment, name)442- except TemplateNotFound:443- # re-raise the exception with the correct filename here.444- # (the one that includes the prefix)445- raise TemplateNotFound(template)446-447- @internalcode448- def load(self, environment, name, globals=None):449- loader, local_name = self.get_loader(name)450- try:451- return loader.load(environment, local_name, globals)452- except TemplateNotFound:453- # re-raise the exception with the correct filename here.454- # (the one that includes the prefix)455- raise TemplateNotFound(name)456-457- def list_templates(self):458- result = []459- for prefix, loader in iteritems(self.mapping):460- for template in loader.list_templates():461- result.append(prefix + self.delimiter + template)462- return result463-464-465-class ChoiceLoader(BaseLoader):466- """This loader works like the `PrefixLoader` just that no prefix is467- specified. If a template could not be found by one loader the next one468- is tried.469-470- >>> loader = ChoiceLoader([471- ... FileSystemLoader('/path/to/user/templates'),472- ... FileSystemLoader('/path/to/system/templates')473- ... ])474-475- This is useful if you want to allow users to override builtin templates476- from a different location.477- """478-479- def __init__(self, loaders):480- self.loaders = loaders481-482- def get_source(self, environment, template):483- for loader in self.loaders:484- try:485- return loader.get_source(environment, template)486- except TemplateNotFound:487- pass488- raise TemplateNotFound(template)489-490- @internalcode491- def load(self, environment, name, globals=None):492- for loader in self.loaders:493- try:494- return loader.load(environment, name, globals)495- except TemplateNotFound:496- pass497- raise TemplateNotFound(name)498-499- def list_templates(self):500- found = set()501- for loader in self.loaders:502- found.update(loader.list_templates())503- return sorted(found)504-505-506-class _TemplateModule(ModuleType):507- """Like a normal module but with support for weak references"""508-509-510-class ModuleLoader(BaseLoader):511- """This loader loads templates from precompiled templates.512-513- Example usage:514-515- >>> loader = ChoiceLoader([516- ... ModuleLoader('/path/to/compiled/templates'),517- ... FileSystemLoader('/path/to/templates')518- ... ])519-520- Templates can be precompiled with :meth:`Environment.compile_templates`.521- """522-523- has_source_access = False524-525- def __init__(self, path):526- package_name = "_jinja2_module_templates_%x" % id(self)527-528- # create a fake module that looks for the templates in the529- # path given.530- mod = _TemplateModule(package_name)531-532- if not isinstance(path, abc.Iterable) or isinstance(path, string_types):533- path = [path]534-535- mod.__path__ = [fspath(p) for p in path]536-537- sys.modules[package_name] = weakref.proxy(538- mod, lambda x: sys.modules.pop(package_name, None)539- )540-541- # the only strong reference, the sys.modules entry is weak542- # so that the garbage collector can remove it once the543- # loader that created it goes out of business.544- self.module = mod545- self.package_name = package_name546-547- @staticmethod548- def get_template_key(name):549- return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()550-551- @staticmethod552- def get_module_filename(name):553- return ModuleLoader.get_template_key(name) + ".py"554-555- @internalcode556- def load(self, environment, name, globals=None):557- key = self.get_template_key(name)558- module = "%s.%s" % (self.package_name, key)559- mod = getattr(self.module, module, None)560- if mod is None:561- try:562- mod = __import__(module, None, None, ["root"])563- except ImportError:564- raise TemplateNotFound(name)565-566- # remove the entry from sys.modules, we only want the attribute567- # on the module object we have stored on the loader.568- sys.modules.pop(module, None)569-570- return environment.template_class.from_module_dict(571- environment, mod.__dict__, globals572- )deleted:src/jinja2/meta.py-101 removed
1-# -*- coding: utf-8 -*-2-"""Functions that expose information about templates that might be3-interesting for introspection.4-"""5-from . import nodes6-from ._compat import iteritems7-from ._compat import string_types8-from .compiler import CodeGenerator9-10-11-class TrackingCodeGenerator(CodeGenerator):12- """We abuse the code generator for introspection."""13-14- def __init__(self, environment):15- CodeGenerator.__init__(self, environment, "<introspection>", "<introspection>")16- self.undeclared_identifiers = set()17-18- def write(self, x):19- """Don't write."""20-21- def enter_frame(self, frame):22- """Remember all undeclared identifiers."""23- CodeGenerator.enter_frame(self, frame)24- for _, (action, param) in iteritems(frame.symbols.loads):25- if action == "resolve" and param not in self.environment.globals:26- self.undeclared_identifiers.add(param)27-28-29-def find_undeclared_variables(ast):30- """Returns a set of all variables in the AST that will be looked up from31- the context at runtime. Because at compile time it's not known which32- variables will be used depending on the path the execution takes at33- runtime, all variables are returned.34-35- >>> from jinja2 import Environment, meta36- >>> env = Environment()37- >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')38- >>> meta.find_undeclared_variables(ast) == set(['bar'])39- True40-41- .. admonition:: Implementation42-43- Internally the code generator is used for finding undeclared variables.44- This is good to know because the code generator might raise a45- :exc:`TemplateAssertionError` during compilation and as a matter of46- fact this function can currently raise that exception as well.47- """48- codegen = TrackingCodeGenerator(ast.environment)49- codegen.visit(ast)50- return codegen.undeclared_identifiers51-52-53-def find_referenced_templates(ast):54- """Finds all the referenced templates from the AST. This will return an55- iterator over all the hardcoded template extensions, inclusions and56- imports. If dynamic inheritance or inclusion is used, `None` will be57- yielded.58-59- >>> from jinja2 import Environment, meta60- >>> env = Environment()61- >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')62- >>> list(meta.find_referenced_templates(ast))63- ['layout.html', None]64-65- This function is useful for dependency tracking. For example if you want66- to rebuild parts of the website after a layout template has changed.67- """68- for node in ast.find_all(69- (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)70- ):71- if not isinstance(node.template, nodes.Const):72- # a tuple with some non consts in there73- if isinstance(node.template, (nodes.Tuple, nodes.List)):74- for template_name in node.template.items:75- # something const, only yield the strings and ignore76- # non-string consts that really just make no sense77- if isinstance(template_name, nodes.Const):78- if isinstance(template_name.value, string_types):79- yield template_name.value80- # something dynamic in there81- else:82- yield None83- # something dynamic we don't know about here84- else:85- yield None86- continue87- # constant is a basestring, direct template name88- if isinstance(node.template.value, string_types):89- yield node.template.value90- # a tuple or list (latter *should* not happen) made of consts,91- # yield the consts that are strings. We could warn here for92- # non string values93- elif isinstance(node, nodes.Include) and isinstance(94- node.template.value, (tuple, list)95- ):96- for template_name in node.template.value:97- if isinstance(template_name, string_types):98- yield template_name99- # something else we don't care about, we could warn here100- else:101- yield Nonedeleted:src/jinja2/nativetypes.py-111 removed
1-import types2-from ast import literal_eval3-from itertools import chain4-from itertools import islice5-6-from . import nodes7-from ._compat import text_type8-from .compiler import CodeGenerator9-from .compiler import has_safe_repr10-from .environment import Environment11-from .environment import Template12-13-14-def native_concat(nodes, preserve_quotes=True):15- """Return a native Python type from the list of compiled nodes. If16- the result is a single node, its value is returned. Otherwise, the17- nodes are concatenated as strings. If the result can be parsed with18- :func:`ast.literal_eval`, the parsed value is returned. Otherwise,19- the string is returned.20-21- :param nodes: Iterable of nodes to concatenate.22- :param preserve_quotes: Whether to re-wrap literal strings with23- quotes, to preserve quotes around expressions for later parsing.24- Should be ``False`` in :meth:`NativeEnvironment.render`.25- """26- head = list(islice(nodes, 2))27-28- if not head:29- return None30-31- if len(head) == 1:32- raw = head[0]33- else:34- if isinstance(nodes, types.GeneratorType):35- nodes = chain(head, nodes)36- raw = u"".join([text_type(v) for v in nodes])37-38- try:39- literal = literal_eval(raw)40- except (ValueError, SyntaxError, MemoryError):41- return raw42-43- # If literal_eval returned a string, re-wrap with the original44- # quote character to avoid dropping quotes between expression nodes.45- # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should46- # be ('a', 'b').47- if preserve_quotes and isinstance(literal, str):48- return "{quote}{}{quote}".format(literal, quote=raw[0])49-50- return literal51-52-53-class NativeCodeGenerator(CodeGenerator):54- """A code generator which renders Python types by not adding55- ``to_string()`` around output nodes, and using :func:`native_concat`56- to convert complex strings back to Python types if possible.57- """58-59- @staticmethod60- def _default_finalize(value):61- return value62-63- def _output_const_repr(self, group):64- return repr(native_concat(group))65-66- def _output_child_to_const(self, node, frame, finalize):67- const = node.as_const(frame.eval_ctx)68-69- if not has_safe_repr(const):70- raise nodes.Impossible()71-72- if isinstance(node, nodes.TemplateData):73- return const74-75- return finalize.const(const)76-77- def _output_child_pre(self, node, frame, finalize):78- if finalize.src is not None:79- self.write(finalize.src)80-81- def _output_child_post(self, node, frame, finalize):82- if finalize.src is not None:83- self.write(")")84-85-86-class NativeEnvironment(Environment):87- """An environment that renders templates to native Python types."""88-89- code_generator_class = NativeCodeGenerator90-91-92-class NativeTemplate(Template):93- environment_class = NativeEnvironment94-95- def render(self, *args, **kwargs):96- """Render the template to produce a native Python type. If the97- result is a single node, its value is returned. Otherwise, the98- nodes are concatenated as strings. If the result can be parsed99- with :func:`ast.literal_eval`, the parsed value is returned.100- Otherwise, the string is returned.101- """102- vars = dict(*args, **kwargs)103- try:104- return native_concat(105- self.root_render_func(self.new_context(vars)), preserve_quotes=False106- )107- except Exception:108- return self.environment.handle_exception()109-110-111-NativeEnvironment.template_class = NativeTemplatedeleted:src/jinja2/nodes.py-1087 removed
1-# -*- coding: utf-8 -*-2-"""AST nodes generated by the parser for the compiler. Also provides3-some node tree helper functions used by the parser and compiler in order4-to normalize nodes.5-"""6-import operator7-from collections import deque8-9-from ._compat import izip10-from ._compat import PY211-from ._compat import text_type12-from ._compat import with_metaclass13-from .utils import Markup14-15-_binop_to_func = {16- "*": operator.mul,17- "/": operator.truediv,18- "//": operator.floordiv,19- "**": operator.pow,20- "%": operator.mod,21- "+": operator.add,22- "-": operator.sub,23-}24-25-_uaop_to_func = {"not": operator.not_, "+": operator.pos, "-": operator.neg}26-27-_cmpop_to_func = {28- "eq": operator.eq,29- "ne": operator.ne,30- "gt": operator.gt,31- "gteq": operator.ge,32- "lt": operator.lt,33- "lteq": operator.le,34- "in": lambda a, b: a in b,35- "notin": lambda a, b: a not in b,36-}37-38-39-class Impossible(Exception):40- """Raised if the node could not perform a requested action."""41-42-43-class NodeType(type):44- """A metaclass for nodes that handles the field and attribute45- inheritance. fields and attributes from the parent class are46- automatically forwarded to the child."""47-48- def __new__(mcs, name, bases, d):49- for attr in "fields", "attributes":50- storage = []51- storage.extend(getattr(bases[0], attr, ()))52- storage.extend(d.get(attr, ()))53- assert len(bases) == 1, "multiple inheritance not allowed"54- assert len(storage) == len(set(storage)), "layout conflict"55- d[attr] = tuple(storage)56- d.setdefault("abstract", False)57- return type.__new__(mcs, name, bases, d)58-59-60-class EvalContext(object):61- """Holds evaluation time information. Custom attributes can be attached62- to it in extensions.63- """64-65- def __init__(self, environment, template_name=None):66- self.environment = environment67- if callable(environment.autoescape):68- self.autoescape = environment.autoescape(template_name)69- else:70- self.autoescape = environment.autoescape71- self.volatile = False72-73- def save(self):74- return self.__dict__.copy()75-76- def revert(self, old):77- self.__dict__.clear()78- self.__dict__.update(old)79-80-81-def get_eval_context(node, ctx):82- if ctx is None:83- if node.environment is None:84- raise RuntimeError(85- "if no eval context is passed, the "86- "node must have an attached "87- "environment."88- )89- return EvalContext(node.environment)90- return ctx91-92-93-class Node(with_metaclass(NodeType, object)):94- """Baseclass for all Jinja nodes. There are a number of nodes available95- of different types. There are four major types:96-97- - :class:`Stmt`: statements98- - :class:`Expr`: expressions99- - :class:`Helper`: helper nodes100- - :class:`Template`: the outermost wrapper node101-102- All nodes have fields and attributes. Fields may be other nodes, lists,103- or arbitrary values. Fields are passed to the constructor as regular104- positional arguments, attributes as keyword arguments. Each node has105- two attributes: `lineno` (the line number of the node) and `environment`.106- The `environment` attribute is set at the end of the parsing process for107- all nodes automatically.108- """109-110- fields = ()111- attributes = ("lineno", "environment")112- abstract = True113-114- def __init__(self, *fields, **attributes):115- if self.abstract:116- raise TypeError("abstract nodes are not instantiable")117- if fields:118- if len(fields) != len(self.fields):119- if not self.fields:120- raise TypeError("%r takes 0 arguments" % self.__class__.__name__)121- raise TypeError(122- "%r takes 0 or %d argument%s"123- % (124- self.__class__.__name__,125- len(self.fields),126- len(self.fields) != 1 and "s" or "",127- )128- )129- for name, arg in izip(self.fields, fields):130- setattr(self, name, arg)131- for attr in self.attributes:132- setattr(self, attr, attributes.pop(attr, None))133- if attributes:134- raise TypeError("unknown attribute %r" % next(iter(attributes)))135-136- def iter_fields(self, exclude=None, only=None):137- """This method iterates over all fields that are defined and yields138- ``(key, value)`` tuples. Per default all fields are returned, but139- it's possible to limit that to some fields by providing the `only`140- parameter or to exclude some using the `exclude` parameter. Both141- should be sets or tuples of field names.142- """143- for name in self.fields:144- if (145- (exclude is only is None)146- or (exclude is not None and name not in exclude)147- or (only is not None and name in only)148- ):149- try:150- yield name, getattr(self, name)151- except AttributeError:152- pass153-154- def iter_child_nodes(self, exclude=None, only=None):155- """Iterates over all direct child nodes of the node. This iterates156- over all fields and yields the values of they are nodes. If the value157- of a field is a list all the nodes in that list are returned.158- """159- for _, item in self.iter_fields(exclude, only):160- if isinstance(item, list):161- for n in item:162- if isinstance(n, Node):163- yield n164- elif isinstance(item, Node):165- yield item166-167- def find(self, node_type):168- """Find the first node of a given type. If no such node exists the169- return value is `None`.170- """171- for result in self.find_all(node_type):172- return result173-174- def find_all(self, node_type):175- """Find all the nodes of a given type. If the type is a tuple,176- the check is performed for any of the tuple items.177- """178- for child in self.iter_child_nodes():179- if isinstance(child, node_type):180- yield child181- for result in child.find_all(node_type):182- yield result183-184- def set_ctx(self, ctx):185- """Reset the context of a node and all child nodes. Per default the186- parser will all generate nodes that have a 'load' context as it's the187- most common one. This method is used in the parser to set assignment188- targets and other nodes to a store context.189- """190- todo = deque([self])191- while todo:192- node = todo.popleft()193- if "ctx" in node.fields:194- node.ctx = ctx195- todo.extend(node.iter_child_nodes())196- return self197-198- def set_lineno(self, lineno, override=False):199- """Set the line numbers of the node and children."""200- todo = deque([self])201- while todo:202- node = todo.popleft()203- if "lineno" in node.attributes:204- if node.lineno is None or override:205- node.lineno = lineno206- todo.extend(node.iter_child_nodes())207- return self208-209- def set_environment(self, environment):210- """Set the environment for all nodes."""211- todo = deque([self])212- while todo:213- node = todo.popleft()214- node.environment = environment215- todo.extend(node.iter_child_nodes())216- return self217-218- def __eq__(self, other):219- return type(self) is type(other) and tuple(self.iter_fields()) == tuple(220- other.iter_fields()221- )222-223- def __ne__(self, other):224- return not self.__eq__(other)225-226- # Restore Python 2 hashing behavior on Python 3227- __hash__ = object.__hash__228-229- def __repr__(self):230- return "%s(%s)" % (231- self.__class__.__name__,232- ", ".join("%s=%r" % (arg, getattr(self, arg, None)) for arg in self.fields),233- )234-235- def dump(self):236- def _dump(node):237- if not isinstance(node, Node):238- buf.append(repr(node))239- return240-241- buf.append("nodes.%s(" % node.__class__.__name__)242- if not node.fields:243- buf.append(")")244- return245- for idx, field in enumerate(node.fields):246- if idx:247- buf.append(", ")248- value = getattr(node, field)249- if isinstance(value, list):250- buf.append("[")251- for idx, item in enumerate(value):252- if idx:253- buf.append(", ")254- _dump(item)255- buf.append("]")256- else:257- _dump(value)258- buf.append(")")259-260- buf = []261- _dump(self)262- return "".join(buf)263-264-265-class Stmt(Node):266- """Base node for all statements."""267-268- abstract = True269-270-271-class Helper(Node):272- """Nodes that exist in a specific context only."""273-274- abstract = True275-276-277-class Template(Node):278- """Node that represents a template. This must be the outermost node that279- is passed to the compiler.280- """281-282- fields = ("body",)283-284-285-class Output(Stmt):286- """A node that holds multiple expressions which are then printed out.287- This is used both for the `print` statement and the regular template data.288- """289-290- fields = ("nodes",)291-292-293-class Extends(Stmt):294- """Represents an extends statement."""295-296- fields = ("template",)297-298-299-class For(Stmt):300- """The for loop. `target` is the target for the iteration (usually a301- :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list302- of nodes that are used as loop-body, and `else_` a list of nodes for the303- `else` block. If no else node exists it has to be an empty list.304-305- For filtered nodes an expression can be stored as `test`, otherwise `None`.306- """307-308- fields = ("target", "iter", "body", "else_", "test", "recursive")309-310-311-class If(Stmt):312- """If `test` is true, `body` is rendered, else `else_`."""313-314- fields = ("test", "body", "elif_", "else_")315-316-317-class Macro(Stmt):318- """A macro definition. `name` is the name of the macro, `args` a list of319- arguments and `defaults` a list of defaults if there are any. `body` is320- a list of nodes for the macro body.321- """322-323- fields = ("name", "args", "defaults", "body")324-325-326-class CallBlock(Stmt):327- """Like a macro without a name but a call instead. `call` is called with328- the unnamed macro as `caller` argument this node holds.329- """330-331- fields = ("call", "args", "defaults", "body")332-333-334-class FilterBlock(Stmt):335- """Node for filter sections."""336-337- fields = ("body", "filter")338-339-340-class With(Stmt):341- """Specific node for with statements. In older versions of Jinja the342- with statement was implemented on the base of the `Scope` node instead.343-344- .. versionadded:: 2.9.3345- """346-347- fields = ("targets", "values", "body")348-349-350-class Block(Stmt):351- """A node that represents a block."""352-353- fields = ("name", "body", "scoped")354-355-356-class Include(Stmt):357- """A node that represents the include tag."""358-359- fields = ("template", "with_context", "ignore_missing")360-361-362-class Import(Stmt):363- """A node that represents the import tag."""364-365- fields = ("template", "target", "with_context")366-367-368-class FromImport(Stmt):369- """A node that represents the from import tag. It's important to not370- pass unsafe names to the name attribute. The compiler translates the371- attribute lookups directly into getattr calls and does *not* use the372- subscript callback of the interface. As exported variables may not373- start with double underscores (which the parser asserts) this is not a374- problem for regular Jinja code, but if this node is used in an extension375- extra care must be taken.376-377- The list of names may contain tuples if aliases are wanted.378- """379-380- fields = ("template", "names", "with_context")381-382-383-class ExprStmt(Stmt):384- """A statement that evaluates an expression and discards the result."""385-386- fields = ("node",)387-388-389-class Assign(Stmt):390- """Assigns an expression to a target."""391-392- fields = ("target", "node")393-394-395-class AssignBlock(Stmt):396- """Assigns a block to a target."""397-398- fields = ("target", "filter", "body")399-400-401-class Expr(Node):402- """Baseclass for all expressions."""403-404- abstract = True405-406- def as_const(self, eval_ctx=None):407- """Return the value of the expression as constant or raise408- :exc:`Impossible` if this was not possible.409-410- An :class:`EvalContext` can be provided, if none is given411- a default context is created which requires the nodes to have412- an attached environment.413-414- .. versionchanged:: 2.4415- the `eval_ctx` parameter was added.416- """417- raise Impossible()418-419- def can_assign(self):420- """Check if it's possible to assign something to this node."""421- return False422-423-424-class BinExpr(Expr):425- """Baseclass for all binary expressions."""426-427- fields = ("left", "right")428- operator = None429- abstract = True430-431- def as_const(self, eval_ctx=None):432- eval_ctx = get_eval_context(self, eval_ctx)433- # intercepted operators cannot be folded at compile time434- if (435- self.environment.sandboxed436- and self.operator in self.environment.intercepted_binops437- ):438- raise Impossible()439- f = _binop_to_func[self.operator]440- try:441- return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))442- except Exception:443- raise Impossible()444-445-446-class UnaryExpr(Expr):447- """Baseclass for all unary expressions."""448-449- fields = ("node",)450- operator = None451- abstract = True452-453- def as_const(self, eval_ctx=None):454- eval_ctx = get_eval_context(self, eval_ctx)455- # intercepted operators cannot be folded at compile time456- if (457- self.environment.sandboxed458- and self.operator in self.environment.intercepted_unops459- ):460- raise Impossible()461- f = _uaop_to_func[self.operator]462- try:463- return f(self.node.as_const(eval_ctx))464- except Exception:465- raise Impossible()466-467-468-class Name(Expr):469- """Looks up a name or stores a value in a name.470- The `ctx` of the node can be one of the following values:471-472- - `store`: store a value in the name473- - `load`: load that name474- - `param`: like `store` but if the name was defined as function parameter.475- """476-477- fields = ("name", "ctx")478-479- def can_assign(self):480- return self.name not in ("true", "false", "none", "True", "False", "None")481-482-483-class NSRef(Expr):484- """Reference to a namespace value assignment"""485-486- fields = ("name", "attr")487-488- def can_assign(self):489- # We don't need any special checks here; NSRef assignments have a490- # runtime check to ensure the target is a namespace object which will491- # have been checked already as it is created using a normal assignment492- # which goes through a `Name` node.493- return True494-495-496-class Literal(Expr):497- """Baseclass for literals."""498-499- abstract = True500-501-502-class Const(Literal):503- """All constant values. The parser will return this node for simple504- constants such as ``42`` or ``"foo"`` but it can be used to store more505- complex values such as lists too. Only constants with a safe506- representation (objects where ``eval(repr(x)) == x`` is true).507- """508-509- fields = ("value",)510-511- def as_const(self, eval_ctx=None):512- rv = self.value513- if (514- PY2515- and type(rv) is text_type516- and self.environment.policies["compiler.ascii_str"]517- ):518- try:519- rv = rv.encode("ascii")520- except UnicodeError:521- pass522- return rv523-524- @classmethod525- def from_untrusted(cls, value, lineno=None, environment=None):526- """Return a const object if the value is representable as527- constant value in the generated code, otherwise it will raise528- an `Impossible` exception.529- """530- from .compiler import has_safe_repr531-532- if not has_safe_repr(value):533- raise Impossible()534- return cls(value, lineno=lineno, environment=environment)535-536-537-class TemplateData(Literal):538- """A constant template string."""539-540- fields = ("data",)541-542- def as_const(self, eval_ctx=None):543- eval_ctx = get_eval_context(self, eval_ctx)544- if eval_ctx.volatile:545- raise Impossible()546- if eval_ctx.autoescape:547- return Markup(self.data)548- return self.data549-550-551-class Tuple(Literal):552- """For loop unpacking and some other things like multiple arguments553- for subscripts. Like for :class:`Name` `ctx` specifies if the tuple554- is used for loading the names or storing.555- """556-557- fields = ("items", "ctx")558-559- def as_const(self, eval_ctx=None):560- eval_ctx = get_eval_context(self, eval_ctx)561- return tuple(x.as_const(eval_ctx) for x in self.items)562-563- def can_assign(self):564- for item in self.items:565- if not item.can_assign():566- return False567- return True568-569-570-class List(Literal):571- """Any list literal such as ``[1, 2, 3]``"""572-573- fields = ("items",)574-575- def as_const(self, eval_ctx=None):576- eval_ctx = get_eval_context(self, eval_ctx)577- return [x.as_const(eval_ctx) for x in self.items]578-579-580-class Dict(Literal):581- """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of582- :class:`Pair` nodes.583- """584-585- fields = ("items",)586-587- def as_const(self, eval_ctx=None):588- eval_ctx = get_eval_context(self, eval_ctx)589- return dict(x.as_const(eval_ctx) for x in self.items)590-591-592-class Pair(Helper):593- """A key, value pair for dicts."""594-595- fields = ("key", "value")596-597- def as_const(self, eval_ctx=None):598- eval_ctx = get_eval_context(self, eval_ctx)599- return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)600-601-602-class Keyword(Helper):603- """A key, value pair for keyword arguments where key is a string."""604-605- fields = ("key", "value")606-607- def as_const(self, eval_ctx=None):608- eval_ctx = get_eval_context(self, eval_ctx)609- return self.key, self.value.as_const(eval_ctx)610-611-612-class CondExpr(Expr):613- """A conditional expression (inline if expression). (``{{614- foo if bar else baz }}``)615- """616-617- fields = ("test", "expr1", "expr2")618-619- def as_const(self, eval_ctx=None):620- eval_ctx = get_eval_context(self, eval_ctx)621- if self.test.as_const(eval_ctx):622- return self.expr1.as_const(eval_ctx)623-624- # if we evaluate to an undefined object, we better do that at runtime625- if self.expr2 is None:626- raise Impossible()627-628- return self.expr2.as_const(eval_ctx)629-630-631-def args_as_const(node, eval_ctx):632- args = [x.as_const(eval_ctx) for x in node.args]633- kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)634-635- if node.dyn_args is not None:636- try:637- args.extend(node.dyn_args.as_const(eval_ctx))638- except Exception:639- raise Impossible()640-641- if node.dyn_kwargs is not None:642- try:643- kwargs.update(node.dyn_kwargs.as_const(eval_ctx))644- except Exception:645- raise Impossible()646-647- return args, kwargs648-649-650-class Filter(Expr):651- """This node applies a filter on an expression. `name` is the name of652- the filter, the rest of the fields are the same as for :class:`Call`.653-654- If the `node` of a filter is `None` the contents of the last buffer are655- filtered. Buffers are created by macros and filter blocks.656- """657-658- fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")659-660- def as_const(self, eval_ctx=None):661- eval_ctx = get_eval_context(self, eval_ctx)662-663- if eval_ctx.volatile or self.node is None:664- raise Impossible()665-666- # we have to be careful here because we call filter_ below.667- # if this variable would be called filter, 2to3 would wrap the668- # call in a list because it is assuming we are talking about the669- # builtin filter function here which no longer returns a list in670- # python 3. because of that, do not rename filter_ to filter!671- filter_ = self.environment.filters.get(self.name)672-673- if filter_ is None or getattr(filter_, "contextfilter", False):674- raise Impossible()675-676- # We cannot constant handle async filters, so we need to make sure677- # to not go down this path.678- if eval_ctx.environment.is_async and getattr(679- filter_, "asyncfiltervariant", False680- ):681- raise Impossible()682-683- args, kwargs = args_as_const(self, eval_ctx)684- args.insert(0, self.node.as_const(eval_ctx))685-686- if getattr(filter_, "evalcontextfilter", False):687- args.insert(0, eval_ctx)688- elif getattr(filter_, "environmentfilter", False):689- args.insert(0, self.environment)690-691- try:692- return filter_(*args, **kwargs)693- except Exception:694- raise Impossible()695-696-697-class Test(Expr):698- """Applies a test on an expression. `name` is the name of the test, the699- rest of the fields are the same as for :class:`Call`.700- """701-702- fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")703-704- def as_const(self, eval_ctx=None):705- test = self.environment.tests.get(self.name)706-707- if test is None:708- raise Impossible()709-710- eval_ctx = get_eval_context(self, eval_ctx)711- args, kwargs = args_as_const(self, eval_ctx)712- args.insert(0, self.node.as_const(eval_ctx))713-714- try:715- return test(*args, **kwargs)716- except Exception:717- raise Impossible()718-719-720-class Call(Expr):721- """Calls an expression. `args` is a list of arguments, `kwargs` a list722- of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`723- and `dyn_kwargs` has to be either `None` or a node that is used as724- node for dynamic positional (``*args``) or keyword (``**kwargs``)725- arguments.726- """727-728- fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")729-730-731-class Getitem(Expr):732- """Get an attribute or item from an expression and prefer the item."""733-734- fields = ("node", "arg", "ctx")735-736- def as_const(self, eval_ctx=None):737- eval_ctx = get_eval_context(self, eval_ctx)738- if self.ctx != "load":739- raise Impossible()740- try:741- return self.environment.getitem(742- self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)743- )744- except Exception:745- raise Impossible()746-747- def can_assign(self):748- return False749-750-751-class Getattr(Expr):752- """Get an attribute or item from an expression that is a ascii-only753- bytestring and prefer the attribute.754- """755-756- fields = ("node", "attr", "ctx")757-758- def as_const(self, eval_ctx=None):759- if self.ctx != "load":760- raise Impossible()761- try:762- eval_ctx = get_eval_context(self, eval_ctx)763- return self.environment.getattr(self.node.as_const(eval_ctx), self.attr)764- except Exception:765- raise Impossible()766-767- def can_assign(self):768- return False769-770-771-class Slice(Expr):772- """Represents a slice object. This must only be used as argument for773- :class:`Subscript`.774- """775-776- fields = ("start", "stop", "step")777-778- def as_const(self, eval_ctx=None):779- eval_ctx = get_eval_context(self, eval_ctx)780-781- def const(obj):782- if obj is None:783- return None784- return obj.as_const(eval_ctx)785-786- return slice(const(self.start), const(self.stop), const(self.step))787-788-789-class Concat(Expr):790- """Concatenates the list of expressions provided after converting them to791- unicode.792- """793-794- fields = ("nodes",)795-796- def as_const(self, eval_ctx=None):797- eval_ctx = get_eval_context(self, eval_ctx)798- return "".join(text_type(x.as_const(eval_ctx)) for x in self.nodes)799-800-801-class Compare(Expr):802- """Compares an expression with some other expressions. `ops` must be a803- list of :class:`Operand`\\s.804- """805-806- fields = ("expr", "ops")807-808- def as_const(self, eval_ctx=None):809- eval_ctx = get_eval_context(self, eval_ctx)810- result = value = self.expr.as_const(eval_ctx)811-812- try:813- for op in self.ops:814- new_value = op.expr.as_const(eval_ctx)815- result = _cmpop_to_func[op.op](value, new_value)816-817- if not result:818- return False819-820- value = new_value821- except Exception:822- raise Impossible()823-824- return result825-826-827-class Operand(Helper):828- """Holds an operator and an expression."""829-830- fields = ("op", "expr")831-832-833-if __debug__:834- Operand.__doc__ += "\nThe following operators are available: " + ", ".join(835- sorted(836- "``%s``" % x837- for x in set(_binop_to_func) | set(_uaop_to_func) | set(_cmpop_to_func)838- )839- )840-841-842-class Mul(BinExpr):843- """Multiplies the left with the right node."""844-845- operator = "*"846-847-848-class Div(BinExpr):849- """Divides the left by the right node."""850-851- operator = "/"852-853-854-class FloorDiv(BinExpr):855- """Divides the left by the right node and truncates conver the856- result into an integer by truncating.857- """858-859- operator = "//"860-861-862-class Add(BinExpr):863- """Add the left to the right node."""864-865- operator = "+"866-867-868-class Sub(BinExpr):869- """Subtract the right from the left node."""870-871- operator = "-"872-873-874-class Mod(BinExpr):875- """Left modulo right."""876-877- operator = "%"878-879-880-class Pow(BinExpr):881- """Left to the power of right."""882-883- operator = "**"884-885-886-class And(BinExpr):887- """Short circuited AND."""888-889- operator = "and"890-891- def as_const(self, eval_ctx=None):892- eval_ctx = get_eval_context(self, eval_ctx)893- return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)894-895-896-class Or(BinExpr):897- """Short circuited OR."""898-899- operator = "or"900-901- def as_const(self, eval_ctx=None):902- eval_ctx = get_eval_context(self, eval_ctx)903- return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)904-905-906-class Not(UnaryExpr):907- """Negate the expression."""908-909- operator = "not"910-911-912-class Neg(UnaryExpr):913- """Make the expression negative."""914-915- operator = "-"916-917-918-class Pos(UnaryExpr):919- """Make the expression positive (noop for most expressions)"""920-921- operator = "+"922-923-924-# Helpers for extensions925-926-927-class EnvironmentAttribute(Expr):928- """Loads an attribute from the environment object. This is useful for929- extensions that want to call a callback stored on the environment.930- """931-932- fields = ("name",)933-934-935-class ExtensionAttribute(Expr):936- """Returns the attribute of an extension bound to the environment.937- The identifier is the identifier of the :class:`Extension`.938-939- This node is usually constructed by calling the940- :meth:`~jinja2.ext.Extension.attr` method on an extension.941- """942-943- fields = ("identifier", "name")944-945-946-class ImportedName(Expr):947- """If created with an import name the import name is returned on node948- access. For example ``ImportedName('cgi.escape')`` returns the `escape`949- function from the cgi module on evaluation. Imports are optimized by the950- compiler so there is no need to assign them to local variables.951- """952-953- fields = ("importname",)954-955-956-class InternalName(Expr):957- """An internal name in the compiler. You cannot create these nodes958- yourself but the parser provides a959- :meth:`~jinja2.parser.Parser.free_identifier` method that creates960- a new identifier for you. This identifier is not available from the961- template and is not threated specially by the compiler.962- """963-964- fields = ("name",)965-966- def __init__(self):967- raise TypeError(968- "Can't create internal names. Use the "969- "`free_identifier` method on a parser."970- )971-972-973-class MarkSafe(Expr):974- """Mark the wrapped expression as safe (wrap it as `Markup`)."""975-976- fields = ("expr",)977-978- def as_const(self, eval_ctx=None):979- eval_ctx = get_eval_context(self, eval_ctx)980- return Markup(self.expr.as_const(eval_ctx))981-982-983-class MarkSafeIfAutoescape(Expr):984- """Mark the wrapped expression as safe (wrap it as `Markup`) but985- only if autoescaping is active.986-987- .. versionadded:: 2.5988- """989-990- fields = ("expr",)991-992- def as_const(self, eval_ctx=None):993- eval_ctx = get_eval_context(self, eval_ctx)994- if eval_ctx.volatile:995- raise Impossible()996- expr = self.expr.as_const(eval_ctx)997- if eval_ctx.autoescape:998- return Markup(expr)999- return expr1000-1001-1002-class ContextReference(Expr):1003- """Returns the current template context. It can be used like a1004- :class:`Name` node, with a ``'load'`` ctx and will return the1005- current :class:`~jinja2.runtime.Context` object.1006-1007- Here an example that assigns the current template name to a1008- variable named `foo`::1009-1010- Assign(Name('foo', ctx='store'),1011- Getattr(ContextReference(), 'name'))1012-1013- This is basically equivalent to using the1014- :func:`~jinja2.contextfunction` decorator when using the1015- high-level API, which causes a reference to the context to be passed1016- as the first argument to a function.1017- """1018-1019-1020-class DerivedContextReference(Expr):1021- """Return the current template context including locals. Behaves1022- exactly like :class:`ContextReference`, but includes local1023- variables, such as from a ``for`` loop.1024-1025- .. versionadded:: 2.111026- """1027-1028-1029-class Continue(Stmt):1030- """Continue a loop."""1031-1032-1033-class Break(Stmt):1034- """Break a loop."""1035-1036-1037-class Scope(Stmt):1038- """An artificial scope."""1039-1040- fields = ("body",)1041-1042-1043-class OverlayScope(Stmt):1044- """An overlay scope for extensions. This is a largely unoptimized scope1045- that however can be used to introduce completely arbitrary variables into1046- a sub scope from a dictionary or dictionary like object. The `context`1047- field has to evaluate to a dictionary object.1048-1049- Example usage::1050-1051- OverlayScope(context=self.call_method('get_context'),1052- body=[...])1053-1054- .. versionadded:: 2.101055- """1056-1057- fields = ("context", "body")1058-1059-1060-class EvalContextModifier(Stmt):1061- """Modifies the eval context. For each option that should be modified,1062- a :class:`Keyword` has to be added to the :attr:`options` list.1063-1064- Example to change the `autoescape` setting::1065-1066- EvalContextModifier(options=[Keyword('autoescape', Const(True))])1067- """1068-1069- fields = ("options",)1070-1071-1072-class ScopedEvalContextModifier(EvalContextModifier):1073- """Modifies the eval context and reverts it later. Works exactly like1074- :class:`EvalContextModifier` but will only modify the1075- :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.1076- """1077-1078- fields = ("body",)1079-1080-1081-# make sure nobody creates custom nodes1082-def _failing_new(*args, **kwargs):1083- raise TypeError("can't create custom node types")1084-1085-1086-NodeType.__new__ = staticmethod(_failing_new)1087-del _failing_newdeleted:src/jinja2/optimizer.py-41 removed
1-# -*- coding: utf-8 -*-2-"""The optimizer tries to constant fold expressions and modify the AST3-in place so that it should be faster to evaluate.4-5-Because the AST does not contain all the scoping information and the6-compiler has to find that out, we cannot do all the optimizations we7-want. For example, loop unrolling doesn't work because unrolled loops8-would have a different scope. The solution would be a second syntax tree9-that stored the scoping rules.10-"""11-from . import nodes12-from .visitor import NodeTransformer13-14-15-def optimize(node, environment):16- """The context hint can be used to perform an static optimization17- based on the context given."""18- optimizer = Optimizer(environment)19- return optimizer.visit(node)20-21-22-class Optimizer(NodeTransformer):23- def __init__(self, environment):24- self.environment = environment25-26- def generic_visit(self, node, *args, **kwargs):27- node = super(Optimizer, self).generic_visit(node, *args, **kwargs)28-29- # Do constant folding. Some other nodes besides Expr have30- # as_const, but folding them causes errors later on.31- if isinstance(node, nodes.Expr):32- try:33- return nodes.Const.from_untrusted(34- node.as_const(args[0] if args else None),35- lineno=node.lineno,36- environment=self.environment,37- )38- except nodes.Impossible:39- pass40-41- return nodedeleted:src/jinja2/parser.py-939 removed
1-# -*- coding: utf-8 -*-2-"""Parse tokens from the lexer into nodes for the compiler."""3-from . import nodes4-from ._compat import imap5-from .exceptions import TemplateAssertionError6-from .exceptions import TemplateSyntaxError7-from .lexer import describe_token8-from .lexer import describe_token_expr9-10-_statement_keywords = frozenset(11- [12- "for",13- "if",14- "block",15- "extends",16- "print",17- "macro",18- "include",19- "from",20- "import",21- "set",22- "with",23- "autoescape",24- ]25-)26-_compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])27-28-_math_nodes = {29- "add": nodes.Add,30- "sub": nodes.Sub,31- "mul": nodes.Mul,32- "div": nodes.Div,33- "floordiv": nodes.FloorDiv,34- "mod": nodes.Mod,35-}36-37-38-class Parser(object):39- """This is the central parsing class Jinja uses. It's passed to40- extensions and can be used to parse expressions or statements.41- """42-43- def __init__(self, environment, source, name=None, filename=None, state=None):44- self.environment = environment45- self.stream = environment._tokenize(source, name, filename, state)46- self.name = name47- self.filename = filename48- self.closed = False49- self.extensions = {}50- for extension in environment.iter_extensions():51- for tag in extension.tags:52- self.extensions[tag] = extension.parse53- self._last_identifier = 054- self._tag_stack = []55- self._end_token_stack = []56-57- def fail(self, msg, lineno=None, exc=TemplateSyntaxError):58- """Convenience method that raises `exc` with the message, passed59- line number or last line number as well as the current name and60- filename.61- """62- if lineno is None:63- lineno = self.stream.current.lineno64- raise exc(msg, lineno, self.name, self.filename)65-66- def _fail_ut_eof(self, name, end_token_stack, lineno):67- expected = []68- for exprs in end_token_stack:69- expected.extend(imap(describe_token_expr, exprs))70- if end_token_stack:71- currently_looking = " or ".join(72- "'%s'" % describe_token_expr(expr) for expr in end_token_stack[-1]73- )74- else:75- currently_looking = None76-77- if name is None:78- message = ["Unexpected end of template."]79- else:80- message = ["Encountered unknown tag '%s'." % name]81-82- if currently_looking:83- if name is not None and name in expected:84- message.append(85- "You probably made a nesting mistake. Jinja "86- "is expecting this tag, but currently looking "87- "for %s." % currently_looking88- )89- else:90- message.append(91- "Jinja was looking for the following tags: "92- "%s." % currently_looking93- )94-95- if self._tag_stack:96- message.append(97- "The innermost block that needs to be "98- "closed is '%s'." % self._tag_stack[-1]99- )100-101- self.fail(" ".join(message), lineno)102-103- def fail_unknown_tag(self, name, lineno=None):104- """Called if the parser encounters an unknown tag. Tries to fail105- with a human readable error message that could help to identify106- the problem.107- """108- return self._fail_ut_eof(name, self._end_token_stack, lineno)109-110- def fail_eof(self, end_tokens=None, lineno=None):111- """Like fail_unknown_tag but for end of template situations."""112- stack = list(self._end_token_stack)113- if end_tokens is not None:114- stack.append(end_tokens)115- return self._fail_ut_eof(None, stack, lineno)116-117- def is_tuple_end(self, extra_end_rules=None):118- """Are we at the end of a tuple?"""119- if self.stream.current.type in ("variable_end", "block_end", "rparen"):120- return True121- elif extra_end_rules is not None:122- return self.stream.current.test_any(extra_end_rules)123- return False124-125- def free_identifier(self, lineno=None):126- """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""127- self._last_identifier += 1128- rv = object.__new__(nodes.InternalName)129- nodes.Node.__init__(rv, "fi%d" % self._last_identifier, lineno=lineno)130- return rv131-132- def parse_statement(self):133- """Parse a single statement."""134- token = self.stream.current135- if token.type != "name":136- self.fail("tag name expected", token.lineno)137- self._tag_stack.append(token.value)138- pop_tag = True139- try:140- if token.value in _statement_keywords:141- return getattr(self, "parse_" + self.stream.current.value)()142- if token.value == "call":143- return self.parse_call_block()144- if token.value == "filter":145- return self.parse_filter_block()146- ext = self.extensions.get(token.value)147- if ext is not None:148- return ext(self)149-150- # did not work out, remove the token we pushed by accident151- # from the stack so that the unknown tag fail function can152- # produce a proper error message.153- self._tag_stack.pop()154- pop_tag = False155- self.fail_unknown_tag(token.value, token.lineno)156- finally:157- if pop_tag:158- self._tag_stack.pop()159-160- def parse_statements(self, end_tokens, drop_needle=False):161- """Parse multiple statements into a list until one of the end tokens162- is reached. This is used to parse the body of statements as it also163- parses template data if appropriate. The parser checks first if the164- current token is a colon and skips it if there is one. Then it checks165- for the block end and parses until if one of the `end_tokens` is166- reached. Per default the active token in the stream at the end of167- the call is the matched end token. If this is not wanted `drop_needle`168- can be set to `True` and the end token is removed.169- """170- # the first token may be a colon for python compatibility171- self.stream.skip_if("colon")172-173- # in the future it would be possible to add whole code sections174- # by adding some sort of end of statement token and parsing those here.175- self.stream.expect("block_end")176- result = self.subparse(end_tokens)177-178- # we reached the end of the template too early, the subparser179- # does not check for this, so we do that now180- if self.stream.current.type == "eof":181- self.fail_eof(end_tokens)182-183- if drop_needle:184- next(self.stream)185- return result186-187- def parse_set(self):188- """Parse an assign statement."""189- lineno = next(self.stream).lineno190- target = self.parse_assign_target(with_namespace=True)191- if self.stream.skip_if("assign"):192- expr = self.parse_tuple()193- return nodes.Assign(target, expr, lineno=lineno)194- filter_node = self.parse_filter(None)195- body = self.parse_statements(("name:endset",), drop_needle=True)196- return nodes.AssignBlock(target, filter_node, body, lineno=lineno)197-198- def parse_for(self):199- """Parse a for loop."""200- lineno = self.stream.expect("name:for").lineno201- target = self.parse_assign_target(extra_end_rules=("name:in",))202- self.stream.expect("name:in")203- iter = self.parse_tuple(204- with_condexpr=False, extra_end_rules=("name:recursive",)205- )206- test = None207- if self.stream.skip_if("name:if"):208- test = self.parse_expression()209- recursive = self.stream.skip_if("name:recursive")210- body = self.parse_statements(("name:endfor", "name:else"))211- if next(self.stream).value == "endfor":212- else_ = []213- else:214- else_ = self.parse_statements(("name:endfor",), drop_needle=True)215- return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)216-217- def parse_if(self):218- """Parse an if construct."""219- node = result = nodes.If(lineno=self.stream.expect("name:if").lineno)220- while 1:221- node.test = self.parse_tuple(with_condexpr=False)222- node.body = self.parse_statements(("name:elif", "name:else", "name:endif"))223- node.elif_ = []224- node.else_ = []225- token = next(self.stream)226- if token.test("name:elif"):227- node = nodes.If(lineno=self.stream.current.lineno)228- result.elif_.append(node)229- continue230- elif token.test("name:else"):231- result.else_ = self.parse_statements(("name:endif",), drop_needle=True)232- break233- return result234-235- def parse_with(self):236- node = nodes.With(lineno=next(self.stream).lineno)237- targets = []238- values = []239- while self.stream.current.type != "block_end":240- if targets:241- self.stream.expect("comma")242- target = self.parse_assign_target()243- target.set_ctx("param")244- targets.append(target)245- self.stream.expect("assign")246- values.append(self.parse_expression())247- node.targets = targets248- node.values = values249- node.body = self.parse_statements(("name:endwith",), drop_needle=True)250- return node251-252- def parse_autoescape(self):253- node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)254- node.options = [nodes.Keyword("autoescape", self.parse_expression())]255- node.body = self.parse_statements(("name:endautoescape",), drop_needle=True)256- return nodes.Scope([node])257-258- def parse_block(self):259- node = nodes.Block(lineno=next(self.stream).lineno)260- node.name = self.stream.expect("name").value261- node.scoped = self.stream.skip_if("name:scoped")262-263- # common problem people encounter when switching from django264- # to jinja. we do not support hyphens in block names, so let's265- # raise a nicer error message in that case.266- if self.stream.current.type == "sub":267- self.fail(268- "Block names in Jinja have to be valid Python "269- "identifiers and may not contain hyphens, use an "270- "underscore instead."271- )272-273- node.body = self.parse_statements(("name:endblock",), drop_needle=True)274- self.stream.skip_if("name:" + node.name)275- return node276-277- def parse_extends(self):278- node = nodes.Extends(lineno=next(self.stream).lineno)279- node.template = self.parse_expression()280- return node281-282- def parse_import_context(self, node, default):283- if self.stream.current.test_any(284- "name:with", "name:without"285- ) and self.stream.look().test("name:context"):286- node.with_context = next(self.stream).value == "with"287- self.stream.skip()288- else:289- node.with_context = default290- return node291-292- def parse_include(self):293- node = nodes.Include(lineno=next(self.stream).lineno)294- node.template = self.parse_expression()295- if self.stream.current.test("name:ignore") and self.stream.look().test(296- "name:missing"297- ):298- node.ignore_missing = True299- self.stream.skip(2)300- else:301- node.ignore_missing = False302- return self.parse_import_context(node, True)303-304- def parse_import(self):305- node = nodes.Import(lineno=next(self.stream).lineno)306- node.template = self.parse_expression()307- self.stream.expect("name:as")308- node.target = self.parse_assign_target(name_only=True).name309- return self.parse_import_context(node, False)310-311- def parse_from(self):312- node = nodes.FromImport(lineno=next(self.stream).lineno)313- node.template = self.parse_expression()314- self.stream.expect("name:import")315- node.names = []316-317- def parse_context():318- if self.stream.current.value in (319- "with",320- "without",321- ) and self.stream.look().test("name:context"):322- node.with_context = next(self.stream).value == "with"323- self.stream.skip()324- return True325- return False326-327- while 1:328- if node.names:329- self.stream.expect("comma")330- if self.stream.current.type == "name":331- if parse_context():332- break333- target = self.parse_assign_target(name_only=True)334- if target.name.startswith("_"):335- self.fail(336- "names starting with an underline can not be imported",337- target.lineno,338- exc=TemplateAssertionError,339- )340- if self.stream.skip_if("name:as"):341- alias = self.parse_assign_target(name_only=True)342- node.names.append((target.name, alias.name))343- else:344- node.names.append(target.name)345- if parse_context() or self.stream.current.type != "comma":346- break347- else:348- self.stream.expect("name")349- if not hasattr(node, "with_context"):350- node.with_context = False351- return node352-353- def parse_signature(self, node):354- node.args = args = []355- node.defaults = defaults = []356- self.stream.expect("lparen")357- while self.stream.current.type != "rparen":358- if args:359- self.stream.expect("comma")360- arg = self.parse_assign_target(name_only=True)361- arg.set_ctx("param")362- if self.stream.skip_if("assign"):363- defaults.append(self.parse_expression())364- elif defaults:365- self.fail("non-default argument follows default argument")366- args.append(arg)367- self.stream.expect("rparen")368-369- def parse_call_block(self):370- node = nodes.CallBlock(lineno=next(self.stream).lineno)371- if self.stream.current.type == "lparen":372- self.parse_signature(node)373- else:374- node.args = []375- node.defaults = []376-377- node.call = self.parse_expression()378- if not isinstance(node.call, nodes.Call):379- self.fail("expected call", node.lineno)380- node.body = self.parse_statements(("name:endcall",), drop_needle=True)381- return node382-383- def parse_filter_block(self):384- node = nodes.FilterBlock(lineno=next(self.stream).lineno)385- node.filter = self.parse_filter(None, start_inline=True)386- node.body = self.parse_statements(("name:endfilter",), drop_needle=True)387- return node388-389- def parse_macro(self):390- node = nodes.Macro(lineno=next(self.stream).lineno)391- node.name = self.parse_assign_target(name_only=True).name392- self.parse_signature(node)393- node.body = self.parse_statements(("name:endmacro",), drop_needle=True)394- return node395-396- def parse_print(self):397- node = nodes.Output(lineno=next(self.stream).lineno)398- node.nodes = []399- while self.stream.current.type != "block_end":400- if node.nodes:401- self.stream.expect("comma")402- node.nodes.append(self.parse_expression())403- return node404-405- def parse_assign_target(406- self,407- with_tuple=True,408- name_only=False,409- extra_end_rules=None,410- with_namespace=False,411- ):412- """Parse an assignment target. As Jinja allows assignments to413- tuples, this function can parse all allowed assignment targets. Per414- default assignments to tuples are parsed, that can be disable however415- by setting `with_tuple` to `False`. If only assignments to names are416- wanted `name_only` can be set to `True`. The `extra_end_rules`417- parameter is forwarded to the tuple parsing function. If418- `with_namespace` is enabled, a namespace assignment may be parsed.419- """420- if with_namespace and self.stream.look().type == "dot":421- token = self.stream.expect("name")422- next(self.stream) # dot423- attr = self.stream.expect("name")424- target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)425- elif name_only:426- token = self.stream.expect("name")427- target = nodes.Name(token.value, "store", lineno=token.lineno)428- else:429- if with_tuple:430- target = self.parse_tuple(431- simplified=True, extra_end_rules=extra_end_rules432- )433- else:434- target = self.parse_primary()435- target.set_ctx("store")436- if not target.can_assign():437- self.fail(438- "can't assign to %r" % target.__class__.__name__.lower(), target.lineno439- )440- return target441-442- def parse_expression(self, with_condexpr=True):443- """Parse an expression. Per default all expressions are parsed, if444- the optional `with_condexpr` parameter is set to `False` conditional445- expressions are not parsed.446- """447- if with_condexpr:448- return self.parse_condexpr()449- return self.parse_or()450-451- def parse_condexpr(self):452- lineno = self.stream.current.lineno453- expr1 = self.parse_or()454- while self.stream.skip_if("name:if"):455- expr2 = self.parse_or()456- if self.stream.skip_if("name:else"):457- expr3 = self.parse_condexpr()458- else:459- expr3 = None460- expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)461- lineno = self.stream.current.lineno462- return expr1463-464- def parse_or(self):465- lineno = self.stream.current.lineno466- left = self.parse_and()467- while self.stream.skip_if("name:or"):468- right = self.parse_and()469- left = nodes.Or(left, right, lineno=lineno)470- lineno = self.stream.current.lineno471- return left472-473- def parse_and(self):474- lineno = self.stream.current.lineno475- left = self.parse_not()476- while self.stream.skip_if("name:and"):477- right = self.parse_not()478- left = nodes.And(left, right, lineno=lineno)479- lineno = self.stream.current.lineno480- return left481-482- def parse_not(self):483- if self.stream.current.test("name:not"):484- lineno = next(self.stream).lineno485- return nodes.Not(self.parse_not(), lineno=lineno)486- return self.parse_compare()487-488- def parse_compare(self):489- lineno = self.stream.current.lineno490- expr = self.parse_math1()491- ops = []492- while 1:493- token_type = self.stream.current.type494- if token_type in _compare_operators:495- next(self.stream)496- ops.append(nodes.Operand(token_type, self.parse_math1()))497- elif self.stream.skip_if("name:in"):498- ops.append(nodes.Operand("in", self.parse_math1()))499- elif self.stream.current.test("name:not") and self.stream.look().test(500- "name:in"501- ):502- self.stream.skip(2)503- ops.append(nodes.Operand("notin", self.parse_math1()))504- else:505- break506- lineno = self.stream.current.lineno507- if not ops:508- return expr509- return nodes.Compare(expr, ops, lineno=lineno)510-511- def parse_math1(self):512- lineno = self.stream.current.lineno513- left = self.parse_concat()514- while self.stream.current.type in ("add", "sub"):515- cls = _math_nodes[self.stream.current.type]516- next(self.stream)517- right = self.parse_concat()518- left = cls(left, right, lineno=lineno)519- lineno = self.stream.current.lineno520- return left521-522- def parse_concat(self):523- lineno = self.stream.current.lineno524- args = [self.parse_math2()]525- while self.stream.current.type == "tilde":526- next(self.stream)527- args.append(self.parse_math2())528- if len(args) == 1:529- return args[0]530- return nodes.Concat(args, lineno=lineno)531-532- def parse_math2(self):533- lineno = self.stream.current.lineno534- left = self.parse_pow()535- while self.stream.current.type in ("mul", "div", "floordiv", "mod"):536- cls = _math_nodes[self.stream.current.type]537- next(self.stream)538- right = self.parse_pow()539- left = cls(left, right, lineno=lineno)540- lineno = self.stream.current.lineno541- return left542-543- def parse_pow(self):544- lineno = self.stream.current.lineno545- left = self.parse_unary()546- while self.stream.current.type == "pow":547- next(self.stream)548- right = self.parse_unary()549- left = nodes.Pow(left, right, lineno=lineno)550- lineno = self.stream.current.lineno551- return left552-553- def parse_unary(self, with_filter=True):554- token_type = self.stream.current.type555- lineno = self.stream.current.lineno556- if token_type == "sub":557- next(self.stream)558- node = nodes.Neg(self.parse_unary(False), lineno=lineno)559- elif token_type == "add":560- next(self.stream)561- node = nodes.Pos(self.parse_unary(False), lineno=lineno)562- else:563- node = self.parse_primary()564- node = self.parse_postfix(node)565- if with_filter:566- node = self.parse_filter_expr(node)567- return node568-569- def parse_primary(self):570- token = self.stream.current571- if token.type == "name":572- if token.value in ("true", "false", "True", "False"):573- node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)574- elif token.value in ("none", "None"):575- node = nodes.Const(None, lineno=token.lineno)576- else:577- node = nodes.Name(token.value, "load", lineno=token.lineno)578- next(self.stream)579- elif token.type == "string":580- next(self.stream)581- buf = [token.value]582- lineno = token.lineno583- while self.stream.current.type == "string":584- buf.append(self.stream.current.value)585- next(self.stream)586- node = nodes.Const("".join(buf), lineno=lineno)587- elif token.type in ("integer", "float"):588- next(self.stream)589- node = nodes.Const(token.value, lineno=token.lineno)590- elif token.type == "lparen":591- next(self.stream)592- node = self.parse_tuple(explicit_parentheses=True)593- self.stream.expect("rparen")594- elif token.type == "lbracket":595- node = self.parse_list()596- elif token.type == "lbrace":597- node = self.parse_dict()598- else:599- self.fail("unexpected '%s'" % describe_token(token), token.lineno)600- return node601-602- def parse_tuple(603- self,604- simplified=False,605- with_condexpr=True,606- extra_end_rules=None,607- explicit_parentheses=False,608- ):609- """Works like `parse_expression` but if multiple expressions are610- delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.611- This method could also return a regular expression instead of a tuple612- if no commas where found.613-614- The default parsing mode is a full tuple. If `simplified` is `True`615- only names and literals are parsed. The `no_condexpr` parameter is616- forwarded to :meth:`parse_expression`.617-618- Because tuples do not require delimiters and may end in a bogus comma619- an extra hint is needed that marks the end of a tuple. For example620- for loops support tuples between `for` and `in`. In that case the621- `extra_end_rules` is set to ``['name:in']``.622-623- `explicit_parentheses` is true if the parsing was triggered by an624- expression in parentheses. This is used to figure out if an empty625- tuple is a valid expression or not.626- """627- lineno = self.stream.current.lineno628- if simplified:629- parse = self.parse_primary630- elif with_condexpr:631- parse = self.parse_expression632- else:633-634- def parse():635- return self.parse_expression(with_condexpr=False)636-637- args = []638- is_tuple = False639- while 1:640- if args:641- self.stream.expect("comma")642- if self.is_tuple_end(extra_end_rules):643- break644- args.append(parse())645- if self.stream.current.type == "comma":646- is_tuple = True647- else:648- break649- lineno = self.stream.current.lineno650-651- if not is_tuple:652- if args:653- return args[0]654-655- # if we don't have explicit parentheses, an empty tuple is656- # not a valid expression. This would mean nothing (literally657- # nothing) in the spot of an expression would be an empty658- # tuple.659- if not explicit_parentheses:660- self.fail(661- "Expected an expression, got '%s'"662- % describe_token(self.stream.current)663- )664-665- return nodes.Tuple(args, "load", lineno=lineno)666-667- def parse_list(self):668- token = self.stream.expect("lbracket")669- items = []670- while self.stream.current.type != "rbracket":671- if items:672- self.stream.expect("comma")673- if self.stream.current.type == "rbracket":674- break675- items.append(self.parse_expression())676- self.stream.expect("rbracket")677- return nodes.List(items, lineno=token.lineno)678-679- def parse_dict(self):680- token = self.stream.expect("lbrace")681- items = []682- while self.stream.current.type != "rbrace":683- if items:684- self.stream.expect("comma")685- if self.stream.current.type == "rbrace":686- break687- key = self.parse_expression()688- self.stream.expect("colon")689- value = self.parse_expression()690- items.append(nodes.Pair(key, value, lineno=key.lineno))691- self.stream.expect("rbrace")692- return nodes.Dict(items, lineno=token.lineno)693-694- def parse_postfix(self, node):695- while 1:696- token_type = self.stream.current.type697- if token_type == "dot" or token_type == "lbracket":698- node = self.parse_subscript(node)699- # calls are valid both after postfix expressions (getattr700- # and getitem) as well as filters and tests701- elif token_type == "lparen":702- node = self.parse_call(node)703- else:704- break705- return node706-707- def parse_filter_expr(self, node):708- while 1:709- token_type = self.stream.current.type710- if token_type == "pipe":711- node = self.parse_filter(node)712- elif token_type == "name" and self.stream.current.value == "is":713- node = self.parse_test(node)714- # calls are valid both after postfix expressions (getattr715- # and getitem) as well as filters and tests716- elif token_type == "lparen":717- node = self.parse_call(node)718- else:719- break720- return node721-722- def parse_subscript(self, node):723- token = next(self.stream)724- if token.type == "dot":725- attr_token = self.stream.current726- next(self.stream)727- if attr_token.type == "name":728- return nodes.Getattr(729- node, attr_token.value, "load", lineno=token.lineno730- )731- elif attr_token.type != "integer":732- self.fail("expected name or number", attr_token.lineno)733- arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)734- return nodes.Getitem(node, arg, "load", lineno=token.lineno)735- if token.type == "lbracket":736- args = []737- while self.stream.current.type != "rbracket":738- if args:739- self.stream.expect("comma")740- args.append(self.parse_subscribed())741- self.stream.expect("rbracket")742- if len(args) == 1:743- arg = args[0]744- else:745- arg = nodes.Tuple(args, "load", lineno=token.lineno)746- return nodes.Getitem(node, arg, "load", lineno=token.lineno)747- self.fail("expected subscript expression", token.lineno)748-749- def parse_subscribed(self):750- lineno = self.stream.current.lineno751-752- if self.stream.current.type == "colon":753- next(self.stream)754- args = [None]755- else:756- node = self.parse_expression()757- if self.stream.current.type != "colon":758- return node759- next(self.stream)760- args = [node]761-762- if self.stream.current.type == "colon":763- args.append(None)764- elif self.stream.current.type not in ("rbracket", "comma"):765- args.append(self.parse_expression())766- else:767- args.append(None)768-769- if self.stream.current.type == "colon":770- next(self.stream)771- if self.stream.current.type not in ("rbracket", "comma"):772- args.append(self.parse_expression())773- else:774- args.append(None)775- else:776- args.append(None)777-778- return nodes.Slice(lineno=lineno, *args)779-780- def parse_call(self, node):781- token = self.stream.expect("lparen")782- args = []783- kwargs = []784- dyn_args = dyn_kwargs = None785- require_comma = False786-787- def ensure(expr):788- if not expr:789- self.fail("invalid syntax for function call expression", token.lineno)790-791- while self.stream.current.type != "rparen":792- if require_comma:793- self.stream.expect("comma")794- # support for trailing comma795- if self.stream.current.type == "rparen":796- break797- if self.stream.current.type == "mul":798- ensure(dyn_args is None and dyn_kwargs is None)799- next(self.stream)800- dyn_args = self.parse_expression()801- elif self.stream.current.type == "pow":802- ensure(dyn_kwargs is None)803- next(self.stream)804- dyn_kwargs = self.parse_expression()805- else:806- if (807- self.stream.current.type == "name"808- and self.stream.look().type == "assign"809- ):810- # Parsing a kwarg811- ensure(dyn_kwargs is None)812- key = self.stream.current.value813- self.stream.skip(2)814- value = self.parse_expression()815- kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))816- else:817- # Parsing an arg818- ensure(dyn_args is None and dyn_kwargs is None and not kwargs)819- args.append(self.parse_expression())820-821- require_comma = True822- self.stream.expect("rparen")823-824- if node is None:825- return args, kwargs, dyn_args, dyn_kwargs826- return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)827-828- def parse_filter(self, node, start_inline=False):829- while self.stream.current.type == "pipe" or start_inline:830- if not start_inline:831- next(self.stream)832- token = self.stream.expect("name")833- name = token.value834- while self.stream.current.type == "dot":835- next(self.stream)836- name += "." + self.stream.expect("name").value837- if self.stream.current.type == "lparen":838- args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)839- else:840- args = []841- kwargs = []842- dyn_args = dyn_kwargs = None843- node = nodes.Filter(844- node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno845- )846- start_inline = False847- return node848-849- def parse_test(self, node):850- token = next(self.stream)851- if self.stream.current.test("name:not"):852- next(self.stream)853- negated = True854- else:855- negated = False856- name = self.stream.expect("name").value857- while self.stream.current.type == "dot":858- next(self.stream)859- name += "." + self.stream.expect("name").value860- dyn_args = dyn_kwargs = None861- kwargs = []862- if self.stream.current.type == "lparen":863- args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)864- elif self.stream.current.type in (865- "name",866- "string",867- "integer",868- "float",869- "lparen",870- "lbracket",871- "lbrace",872- ) and not self.stream.current.test_any("name:else", "name:or", "name:and"):873- if self.stream.current.test("name:is"):874- self.fail("You cannot chain multiple tests with is")875- arg_node = self.parse_primary()876- arg_node = self.parse_postfix(arg_node)877- args = [arg_node]878- else:879- args = []880- node = nodes.Test(881- node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno882- )883- if negated:884- node = nodes.Not(node, lineno=token.lineno)885- return node886-887- def subparse(self, end_tokens=None):888- body = []889- data_buffer = []890- add_data = data_buffer.append891-892- if end_tokens is not None:893- self._end_token_stack.append(end_tokens)894-895- def flush_data():896- if data_buffer:897- lineno = data_buffer[0].lineno898- body.append(nodes.Output(data_buffer[:], lineno=lineno))899- del data_buffer[:]900-901- try:902- while self.stream:903- token = self.stream.current904- if token.type == "data":905- if token.value:906- add_data(nodes.TemplateData(token.value, lineno=token.lineno))907- next(self.stream)908- elif token.type == "variable_begin":909- next(self.stream)910- add_data(self.parse_tuple(with_condexpr=True))911- self.stream.expect("variable_end")912- elif token.type == "block_begin":913- flush_data()914- next(self.stream)915- if end_tokens is not None and self.stream.current.test_any(916- *end_tokens917- ):918- return body919- rv = self.parse_statement()920- if isinstance(rv, list):921- body.extend(rv)922- else:923- body.append(rv)924- self.stream.expect("block_end")925- else:926- raise AssertionError("internal parsing error")927-928- flush_data()929- finally:930- if end_tokens is not None:931- self._end_token_stack.pop()932-933- return body934-935- def parse(self):936- """Parse the whole template into a `Template` node."""937- result = nodes.Template(self.subparse(), lineno=1)938- result.set_environment(self.environment)939- return resultdeleted:src/jinja2/runtime.py-1011 removed
1-# -*- coding: utf-8 -*-2-"""The runtime functions and state used by compiled templates."""3-import sys4-from itertools import chain5-from types import MethodType6-7-from markupsafe import escape8-from markupsafe import Markup9-from markupsafe import soft_unicode10-11-from ._compat import abc12-from ._compat import imap13-from ._compat import implements_iterator14-from ._compat import implements_to_string15-from ._compat import iteritems16-from ._compat import PY217-from ._compat import string_types18-from ._compat import text_type19-from ._compat import with_metaclass20-from .exceptions import TemplateNotFound21-from .exceptions import TemplateRuntimeError22-from .exceptions import UndefinedError23-from .nodes import EvalContext24-from .utils import concat25-from .utils import evalcontextfunction26-from .utils import internalcode27-from .utils import missing28-from .utils import Namespace29-from .utils import object_type_repr30-31-# these variables are exported to the template runtime32-__all__ = [33- "LoopContext",34- "TemplateReference",35- "Macro",36- "Markup",37- "TemplateRuntimeError",38- "missing",39- "concat",40- "escape",41- "markup_join",42- "unicode_join",43- "to_string",44- "identity",45- "TemplateNotFound",46- "Namespace",47- "Undefined",48-]49-50-#: the name of the function that is used to convert something into51-#: a string. We can just use the text type here.52-to_string = text_type53-54-55-def identity(x):56- """Returns its argument. Useful for certain things in the57- environment.58- """59- return x60-61-62-def markup_join(seq):63- """Concatenation that escapes if necessary and converts to unicode."""64- buf = []65- iterator = imap(soft_unicode, seq)66- for arg in iterator:67- buf.append(arg)68- if hasattr(arg, "__html__"):69- return Markup(u"").join(chain(buf, iterator))70- return concat(buf)71-72-73-def unicode_join(seq):74- """Simple args to unicode conversion and concatenation."""75- return concat(imap(text_type, seq))76-77-78-def new_context(79- environment,80- template_name,81- blocks,82- vars=None,83- shared=None,84- globals=None,85- locals=None,86-):87- """Internal helper for context creation."""88- if vars is None:89- vars = {}90- if shared:91- parent = vars92- else:93- parent = dict(globals or (), **vars)94- if locals:95- # if the parent is shared a copy should be created because96- # we don't want to modify the dict passed97- if shared:98- parent = dict(parent)99- for key, value in iteritems(locals):100- if value is not missing:101- parent[key] = value102- return environment.context_class(environment, parent, template_name, blocks)103-104-105-class TemplateReference(object):106- """The `self` in templates."""107-108- def __init__(self, context):109- self.__context = context110-111- def __getitem__(self, name):112- blocks = self.__context.blocks[name]113- return BlockReference(name, self.__context, blocks, 0)114-115- def __repr__(self):116- return "<%s %r>" % (self.__class__.__name__, self.__context.name)117-118-119-def _get_func(x):120- return getattr(x, "__func__", x)121-122-123-class ContextMeta(type):124- def __new__(mcs, name, bases, d):125- rv = type.__new__(mcs, name, bases, d)126- if bases == ():127- return rv128-129- resolve = _get_func(rv.resolve)130- default_resolve = _get_func(Context.resolve)131- resolve_or_missing = _get_func(rv.resolve_or_missing)132- default_resolve_or_missing = _get_func(Context.resolve_or_missing)133-134- # If we have a changed resolve but no changed default or missing135- # resolve we invert the call logic.136- if (137- resolve is not default_resolve138- and resolve_or_missing is default_resolve_or_missing139- ):140- rv._legacy_resolve_mode = True141- elif (142- resolve is default_resolve143- and resolve_or_missing is default_resolve_or_missing144- ):145- rv._fast_resolve_mode = True146-147- return rv148-149-150-def resolve_or_missing(context, key, missing=missing):151- if key in context.vars:152- return context.vars[key]153- if key in context.parent:154- return context.parent[key]155- return missing156-157-158-class Context(with_metaclass(ContextMeta)):159- """The template context holds the variables of a template. It stores the160- values passed to the template and also the names the template exports.161- Creating instances is neither supported nor useful as it's created162- automatically at various stages of the template evaluation and should not163- be created by hand.164-165- The context is immutable. Modifications on :attr:`parent` **must not**166- happen and modifications on :attr:`vars` are allowed from generated167- template code only. Template filters and global functions marked as168- :func:`contextfunction`\\s get the active context passed as first argument169- and are allowed to access the context read-only.170-171- The template context supports read only dict operations (`get`,172- `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,173- `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`174- method that doesn't fail with a `KeyError` but returns an175- :class:`Undefined` object for missing variables.176- """177-178- # XXX: we want to eventually make this be a deprecation warning and179- # remove it.180- _legacy_resolve_mode = False181- _fast_resolve_mode = False182-183- def __init__(self, environment, parent, name, blocks):184- self.parent = parent185- self.vars = {}186- self.environment = environment187- self.eval_ctx = EvalContext(self.environment, name)188- self.exported_vars = set()189- self.name = name190-191- # create the initial mapping of blocks. Whenever template inheritance192- # takes place the runtime will update this mapping with the new blocks193- # from the template.194- self.blocks = dict((k, [v]) for k, v in iteritems(blocks))195-196- # In case we detect the fast resolve mode we can set up an alias197- # here that bypasses the legacy code logic.198- if self._fast_resolve_mode:199- self.resolve_or_missing = MethodType(resolve_or_missing, self)200-201- def super(self, name, current):202- """Render a parent block."""203- try:204- blocks = self.blocks[name]205- index = blocks.index(current) + 1206- blocks[index]207- except LookupError:208- return self.environment.undefined(209- "there is no parent block called %r." % name, name="super"210- )211- return BlockReference(name, self, blocks, index)212-213- def get(self, key, default=None):214- """Returns an item from the template context, if it doesn't exist215- `default` is returned.216- """217- try:218- return self[key]219- except KeyError:220- return default221-222- def resolve(self, key):223- """Looks up a variable like `__getitem__` or `get` but returns an224- :class:`Undefined` object with the name of the name looked up.225- """226- if self._legacy_resolve_mode:227- rv = resolve_or_missing(self, key)228- else:229- rv = self.resolve_or_missing(key)230- if rv is missing:231- return self.environment.undefined(name=key)232- return rv233-234- def resolve_or_missing(self, key):235- """Resolves a variable like :meth:`resolve` but returns the236- special `missing` value if it cannot be found.237- """238- if self._legacy_resolve_mode:239- rv = self.resolve(key)240- if isinstance(rv, Undefined):241- rv = missing242- return rv243- return resolve_or_missing(self, key)244-245- def get_exported(self):246- """Get a new dict with the exported variables."""247- return dict((k, self.vars[k]) for k in self.exported_vars)248-249- def get_all(self):250- """Return the complete context as dict including the exported251- variables. For optimizations reasons this might not return an252- actual copy so be careful with using it.253- """254- if not self.vars:255- return self.parent256- if not self.parent:257- return self.vars258- return dict(self.parent, **self.vars)259-260- @internalcode261- def call(__self, __obj, *args, **kwargs): # noqa: B902262- """Call the callable with the arguments and keyword arguments263- provided but inject the active context or environment as first264- argument if the callable is a :func:`contextfunction` or265- :func:`environmentfunction`.266- """267- if __debug__:268- __traceback_hide__ = True # noqa269-270- # Allow callable classes to take a context271- if hasattr(__obj, "__call__"): # noqa: B004272- fn = __obj.__call__273- for fn_type in (274- "contextfunction",275- "evalcontextfunction",276- "environmentfunction",277- ):278- if hasattr(fn, fn_type):279- __obj = fn280- break281-282- if callable(__obj):283- if getattr(__obj, "contextfunction", 0):284- args = (__self,) + args285- elif getattr(__obj, "evalcontextfunction", 0):286- args = (__self.eval_ctx,) + args287- elif getattr(__obj, "environmentfunction", 0):288- args = (__self.environment,) + args289- try:290- return __obj(*args, **kwargs)291- except StopIteration:292- return __self.environment.undefined(293- "value was undefined because "294- "a callable raised a "295- "StopIteration exception"296- )297-298- def derived(self, locals=None):299- """Internal helper function to create a derived context. This is300- used in situations where the system needs a new context in the same301- template that is independent.302- """303- context = new_context(304- self.environment, self.name, {}, self.get_all(), True, None, locals305- )306- context.eval_ctx = self.eval_ctx307- context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))308- return context309-310- def _all(meth): # noqa: B902311- def proxy(self):312- return getattr(self.get_all(), meth)()313-314- proxy.__doc__ = getattr(dict, meth).__doc__315- proxy.__name__ = meth316- return proxy317-318- keys = _all("keys")319- values = _all("values")320- items = _all("items")321-322- # not available on python 3323- if PY2:324- iterkeys = _all("iterkeys")325- itervalues = _all("itervalues")326- iteritems = _all("iteritems")327- del _all328-329- def __contains__(self, name):330- return name in self.vars or name in self.parent331-332- def __getitem__(self, key):333- """Lookup a variable or raise `KeyError` if the variable is334- undefined.335- """336- item = self.resolve_or_missing(key)337- if item is missing:338- raise KeyError(key)339- return item340-341- def __repr__(self):342- return "<%s %s of %r>" % (343- self.__class__.__name__,344- repr(self.get_all()),345- self.name,346- )347-348-349-abc.Mapping.register(Context)350-351-352-class BlockReference(object):353- """One block on a template reference."""354-355- def __init__(self, name, context, stack, depth):356- self.name = name357- self._context = context358- self._stack = stack359- self._depth = depth360-361- @property362- def super(self):363- """Super the block."""364- if self._depth + 1 >= len(self._stack):365- return self._context.environment.undefined(366- "there is no parent block called %r." % self.name, name="super"367- )368- return BlockReference(self.name, self._context, self._stack, self._depth + 1)369-370- @internalcode371- def __call__(self):372- rv = concat(self._stack[self._depth](self._context))373- if self._context.eval_ctx.autoescape:374- rv = Markup(rv)375- return rv376-377-378-@implements_iterator379-class LoopContext:380- """A wrapper iterable for dynamic ``for`` loops, with information381- about the loop and iteration.382- """383-384- #: Current iteration of the loop, starting at 0.385- index0 = -1386-387- _length = None388- _after = missing389- _current = missing390- _before = missing391- _last_changed_value = missing392-393- def __init__(self, iterable, undefined, recurse=None, depth0=0):394- """395- :param iterable: Iterable to wrap.396- :param undefined: :class:`Undefined` class to use for next and397- previous items.398- :param recurse: The function to render the loop body when the399- loop is marked recursive.400- :param depth0: Incremented when looping recursively.401- """402- self._iterable = iterable403- self._iterator = self._to_iterator(iterable)404- self._undefined = undefined405- self._recurse = recurse406- #: How many levels deep a recursive loop currently is, starting at 0.407- self.depth0 = depth0408-409- @staticmethod410- def _to_iterator(iterable):411- return iter(iterable)412-413- @property414- def length(self):415- """Length of the iterable.416-417- If the iterable is a generator or otherwise does not have a418- size, it is eagerly evaluated to get a size.419- """420- if self._length is not None:421- return self._length422-423- try:424- self._length = len(self._iterable)425- except TypeError:426- iterable = list(self._iterator)427- self._iterator = self._to_iterator(iterable)428- self._length = len(iterable) + self.index + (self._after is not missing)429-430- return self._length431-432- def __len__(self):433- return self.length434-435- @property436- def depth(self):437- """How many levels deep a recursive loop currently is, starting at 1."""438- return self.depth0 + 1439-440- @property441- def index(self):442- """Current iteration of the loop, starting at 1."""443- return self.index0 + 1444-445- @property446- def revindex0(self):447- """Number of iterations from the end of the loop, ending at 0.448-449- Requires calculating :attr:`length`.450- """451- return self.length - self.index452-453- @property454- def revindex(self):455- """Number of iterations from the end of the loop, ending at 1.456-457- Requires calculating :attr:`length`.458- """459- return self.length - self.index0460-461- @property462- def first(self):463- """Whether this is the first iteration of the loop."""464- return self.index0 == 0465-466- def _peek_next(self):467- """Return the next element in the iterable, or :data:`missing`468- if the iterable is exhausted. Only peeks one item ahead, caching469- the result in :attr:`_last` for use in subsequent checks. The470- cache is reset when :meth:`__next__` is called.471- """472- if self._after is not missing:473- return self._after474-475- self._after = next(self._iterator, missing)476- return self._after477-478- @property479- def last(self):480- """Whether this is the last iteration of the loop.481-482- Causes the iterable to advance early. See483- :func:`itertools.groupby` for issues this can cause.484- The :func:`groupby` filter avoids that issue.485- """486- return self._peek_next() is missing487-488- @property489- def previtem(self):490- """The item in the previous iteration. Undefined during the491- first iteration.492- """493- if self.first:494- return self._undefined("there is no previous item")495-496- return self._before497-498- @property499- def nextitem(self):500- """The item in the next iteration. Undefined during the last501- iteration.502-503- Causes the iterable to advance early. See504- :func:`itertools.groupby` for issues this can cause.505- The :func:`groupby` filter avoids that issue.506- """507- rv = self._peek_next()508-509- if rv is missing:510- return self._undefined("there is no next item")511-512- return rv513-514- def cycle(self, *args):515- """Return a value from the given args, cycling through based on516- the current :attr:`index0`.517-518- :param args: One or more values to cycle through.519- """520- if not args:521- raise TypeError("no items for cycling given")522-523- return args[self.index0 % len(args)]524-525- def changed(self, *value):526- """Return ``True`` if previously called with a different value527- (including when called for the first time).528-529- :param value: One or more values to compare to the last call.530- """531- if self._last_changed_value != value:532- self._last_changed_value = value533- return True534-535- return False536-537- def __iter__(self):538- return self539-540- def __next__(self):541- if self._after is not missing:542- rv = self._after543- self._after = missing544- else:545- rv = next(self._iterator)546-547- self.index0 += 1548- self._before = self._current549- self._current = rv550- return rv, self551-552- @internalcode553- def __call__(self, iterable):554- """When iterating over nested data, render the body of the loop555- recursively with the given inner iterable data.556-557- The loop must have the ``recursive`` marker for this to work.558- """559- if self._recurse is None:560- raise TypeError(561- "The loop must have the 'recursive' marker to be called recursively."562- )563-564- return self._recurse(iterable, self._recurse, depth=self.depth)565-566- def __repr__(self):567- return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)568-569-570-class Macro(object):571- """Wraps a macro function."""572-573- def __init__(574- self,575- environment,576- func,577- name,578- arguments,579- catch_kwargs,580- catch_varargs,581- caller,582- default_autoescape=None,583- ):584- self._environment = environment585- self._func = func586- self._argument_count = len(arguments)587- self.name = name588- self.arguments = arguments589- self.catch_kwargs = catch_kwargs590- self.catch_varargs = catch_varargs591- self.caller = caller592- self.explicit_caller = "caller" in arguments593- if default_autoescape is None:594- default_autoescape = environment.autoescape595- self._default_autoescape = default_autoescape596-597- @internalcode598- @evalcontextfunction599- def __call__(self, *args, **kwargs):600- # This requires a bit of explanation, In the past we used to601- # decide largely based on compile-time information if a macro is602- # safe or unsafe. While there was a volatile mode it was largely603- # unused for deciding on escaping. This turns out to be604- # problematic for macros because whether a macro is safe depends not605- # on the escape mode when it was defined, but rather when it was used.606- #607- # Because however we export macros from the module system and608- # there are historic callers that do not pass an eval context (and609- # will continue to not pass one), we need to perform an instance610- # check here.611- #612- # This is considered safe because an eval context is not a valid613- # argument to callables otherwise anyway. Worst case here is614- # that if no eval context is passed we fall back to the compile615- # time autoescape flag.616- if args and isinstance(args[0], EvalContext):617- autoescape = args[0].autoescape618- args = args[1:]619- else:620- autoescape = self._default_autoescape621-622- # try to consume the positional arguments623- arguments = list(args[: self._argument_count])624- off = len(arguments)625-626- # For information why this is necessary refer to the handling627- # of caller in the `macro_body` handler in the compiler.628- found_caller = False629-630- # if the number of arguments consumed is not the number of631- # arguments expected we start filling in keyword arguments632- # and defaults.633- if off != self._argument_count:634- for name in self.arguments[len(arguments) :]:635- try:636- value = kwargs.pop(name)637- except KeyError:638- value = missing639- if name == "caller":640- found_caller = True641- arguments.append(value)642- else:643- found_caller = self.explicit_caller644-645- # it's important that the order of these arguments does not change646- # if not also changed in the compiler's `function_scoping` method.647- # the order is caller, keyword arguments, positional arguments!648- if self.caller and not found_caller:649- caller = kwargs.pop("caller", None)650- if caller is None:651- caller = self._environment.undefined("No caller defined", name="caller")652- arguments.append(caller)653-654- if self.catch_kwargs:655- arguments.append(kwargs)656- elif kwargs:657- if "caller" in kwargs:658- raise TypeError(659- "macro %r was invoked with two values for "660- "the special caller argument. This is "661- "most likely a bug." % self.name662- )663- raise TypeError(664- "macro %r takes no keyword argument %r"665- % (self.name, next(iter(kwargs)))666- )667- if self.catch_varargs:668- arguments.append(args[self._argument_count :])669- elif len(args) > self._argument_count:670- raise TypeError(671- "macro %r takes not more than %d argument(s)"672- % (self.name, len(self.arguments))673- )674-675- return self._invoke(arguments, autoescape)676-677- def _invoke(self, arguments, autoescape):678- """This method is being swapped out by the async implementation."""679- rv = self._func(*arguments)680- if autoescape:681- rv = Markup(rv)682- return rv683-684- def __repr__(self):685- return "<%s %s>" % (686- self.__class__.__name__,687- self.name is None and "anonymous" or repr(self.name),688- )689-690-691-@implements_to_string692-class Undefined(object):693- """The default undefined type. This undefined type can be printed and694- iterated over, but every other access will raise an :exc:`UndefinedError`:695-696- >>> foo = Undefined(name='foo')697- >>> str(foo)698- ''699- >>> not foo700- True701- >>> foo + 42702- Traceback (most recent call last):703- ...704- jinja2.exceptions.UndefinedError: 'foo' is undefined705- """706-707- __slots__ = (708- "_undefined_hint",709- "_undefined_obj",710- "_undefined_name",711- "_undefined_exception",712- )713-714- def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):715- self._undefined_hint = hint716- self._undefined_obj = obj717- self._undefined_name = name718- self._undefined_exception = exc719-720- @property721- def _undefined_message(self):722- """Build a message about the undefined value based on how it was723- accessed.724- """725- if self._undefined_hint:726- return self._undefined_hint727-728- if self._undefined_obj is missing:729- return "%r is undefined" % self._undefined_name730-731- if not isinstance(self._undefined_name, string_types):732- return "%s has no element %r" % (733- object_type_repr(self._undefined_obj),734- self._undefined_name,735- )736-737- return "%r has no attribute %r" % (738- object_type_repr(self._undefined_obj),739- self._undefined_name,740- )741-742- @internalcode743- def _fail_with_undefined_error(self, *args, **kwargs):744- """Raise an :exc:`UndefinedError` when operations are performed745- on the undefined value.746- """747- raise self._undefined_exception(self._undefined_message)748-749- @internalcode750- def __getattr__(self, name):751- if name[:2] == "__":752- raise AttributeError(name)753- return self._fail_with_undefined_error()754-755- __add__ = (756- __radd__757- ) = (758- __mul__759- ) = (760- __rmul__761- ) = (762- __div__763- ) = (764- __rdiv__765- ) = (766- __truediv__767- ) = (768- __rtruediv__769- ) = (770- __floordiv__771- ) = (772- __rfloordiv__773- ) = (774- __mod__775- ) = (776- __rmod__777- ) = (778- __pos__779- ) = (780- __neg__781- ) = (782- __call__783- ) = (784- __getitem__785- ) = (786- __lt__787- ) = (788- __le__789- ) = (790- __gt__791- ) = (792- __ge__793- ) = (794- __int__795- ) = (796- __float__797- ) = (798- __complex__799- ) = __pow__ = __rpow__ = __sub__ = __rsub__ = _fail_with_undefined_error800-801- def __eq__(self, other):802- return type(self) is type(other)803-804- def __ne__(self, other):805- return not self.__eq__(other)806-807- def __hash__(self):808- return id(type(self))809-810- def __str__(self):811- return u""812-813- def __len__(self):814- return 0815-816- def __iter__(self):817- if 0:818- yield None819-820- def __nonzero__(self):821- return False822-823- __bool__ = __nonzero__824-825- def __repr__(self):826- return "Undefined"827-828-829-def make_logging_undefined(logger=None, base=None):830- """Given a logger object this returns a new undefined class that will831- log certain failures. It will log iterations and printing. If no832- logger is given a default logger is created.833-834- Example::835-836- logger = logging.getLogger(__name__)837- LoggingUndefined = make_logging_undefined(838- logger=logger,839- base=Undefined840- )841-842- .. versionadded:: 2.8843-844- :param logger: the logger to use. If not provided, a default logger845- is created.846- :param base: the base class to add logging functionality to. This847- defaults to :class:`Undefined`.848- """849- if logger is None:850- import logging851-852- logger = logging.getLogger(__name__)853- logger.addHandler(logging.StreamHandler(sys.stderr))854- if base is None:855- base = Undefined856-857- def _log_message(undef):858- if undef._undefined_hint is None:859- if undef._undefined_obj is missing:860- hint = "%s is undefined" % undef._undefined_name861- elif not isinstance(undef._undefined_name, string_types):862- hint = "%s has no element %s" % (863- object_type_repr(undef._undefined_obj),864- undef._undefined_name,865- )866- else:867- hint = "%s has no attribute %s" % (868- object_type_repr(undef._undefined_obj),869- undef._undefined_name,870- )871- else:872- hint = undef._undefined_hint873- logger.warning("Template variable warning: %s", hint)874-875- class LoggingUndefined(base):876- def _fail_with_undefined_error(self, *args, **kwargs):877- try:878- return base._fail_with_undefined_error(self, *args, **kwargs)879- except self._undefined_exception as e:880- logger.error("Template variable error: %s", str(e))881- raise e882-883- def __str__(self):884- rv = base.__str__(self)885- _log_message(self)886- return rv887-888- def __iter__(self):889- rv = base.__iter__(self)890- _log_message(self)891- return rv892-893- if PY2:894-895- def __nonzero__(self):896- rv = base.__nonzero__(self)897- _log_message(self)898- return rv899-900- def __unicode__(self):901- rv = base.__unicode__(self)902- _log_message(self)903- return rv904-905- else:906-907- def __bool__(self):908- rv = base.__bool__(self)909- _log_message(self)910- return rv911-912- return LoggingUndefined913-914-915-# No @implements_to_string decorator here because __str__916-# is not overwritten from Undefined in this class.917-# This would cause a recursion error in Python 2.918-class ChainableUndefined(Undefined):919- """An undefined that is chainable, where both ``__getattr__`` and920- ``__getitem__`` return itself rather than raising an921- :exc:`UndefinedError`.922-923- >>> foo = ChainableUndefined(name='foo')924- >>> str(foo.bar['baz'])925- ''926- >>> foo.bar['baz'] + 42927- Traceback (most recent call last):928- ...929- jinja2.exceptions.UndefinedError: 'foo' is undefined930-931- .. versionadded:: 2.11.0932- """933-934- __slots__ = ()935-936- def __html__(self):937- return self.__str__()938-939- def __getattr__(self, _):940- return self941-942- __getitem__ = __getattr__943-944-945-@implements_to_string946-class DebugUndefined(Undefined):947- """An undefined that returns the debug info when printed.948-949- >>> foo = DebugUndefined(name='foo')950- >>> str(foo)951- '{{ foo }}'952- >>> not foo953- True954- >>> foo + 42955- Traceback (most recent call last):956- ...957- jinja2.exceptions.UndefinedError: 'foo' is undefined958- """959-960- __slots__ = ()961-962- def __str__(self):963- if self._undefined_hint is None:964- if self._undefined_obj is missing:965- return u"{{ %s }}" % self._undefined_name966- return "{{ no such element: %s[%r] }}" % (967- object_type_repr(self._undefined_obj),968- self._undefined_name,969- )970- return u"{{ undefined value printed: %s }}" % self._undefined_hint971-972-973-@implements_to_string974-class StrictUndefined(Undefined):975- """An undefined that barks on print and iteration as well as boolean976- tests and all kinds of comparisons. In other words: you can do nothing977- with it except checking if it's defined using the `defined` test.978-979- >>> foo = StrictUndefined(name='foo')980- >>> str(foo)981- Traceback (most recent call last):982- ...983- jinja2.exceptions.UndefinedError: 'foo' is undefined984- >>> not foo985- Traceback (most recent call last):986- ...987- jinja2.exceptions.UndefinedError: 'foo' is undefined988- >>> foo + 42989- Traceback (most recent call last):990- ...991- jinja2.exceptions.UndefinedError: 'foo' is undefined992- """993-994- __slots__ = ()995- __iter__ = (996- __str__997- ) = (998- __len__999- ) = (1000- __nonzero__1001- ) = __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error1002-1003-1004-# remove remaining slots attributes, after the metaclass did the magic they1005-# are unneeded and irritating as they contain wrong data for the subclasses.1006-del (1007- Undefined.__slots__,1008- ChainableUndefined.__slots__,1009- DebugUndefined.__slots__,1010- StrictUndefined.__slots__,1011-)deleted:src/jinja2/sandbox.py-510 removed
1-# -*- coding: utf-8 -*-2-"""A sandbox layer that ensures unsafe operations cannot be performed.3-Useful when the template itself comes from an untrusted source.4-"""5-import operator6-import types7-import warnings8-from collections import deque9-from string import Formatter10-11-from markupsafe import EscapeFormatter12-13-from ._compat import abc14-from ._compat import PY215-from ._compat import range_type16-from ._compat import string_types17-from .environment import Environment18-from .exceptions import SecurityError19-from .utils import Markup20-21-#: maximum number of items a range may produce22-MAX_RANGE = 10000023-24-#: attributes of function objects that are considered unsafe.25-if PY2:26- UNSAFE_FUNCTION_ATTRIBUTES = {27- "func_closure",28- "func_code",29- "func_dict",30- "func_defaults",31- "func_globals",32- }33-else:34- # On versions > python 2 the special attributes on functions are gone,35- # but they remain on methods and generators for whatever reason.36- UNSAFE_FUNCTION_ATTRIBUTES = set()37-38-#: unsafe method attributes. function attributes are unsafe for methods too39-UNSAFE_METHOD_ATTRIBUTES = {"im_class", "im_func", "im_self"}40-41-#: unsafe generator attributes.42-UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}43-44-#: unsafe attributes on coroutines45-UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}46-47-#: unsafe attributes on async generators48-UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}49-50-# make sure we don't warn in python 2.6 about stuff we don't care about51-warnings.filterwarnings(52- "ignore", "the sets module", DeprecationWarning, module=__name__53-)54-55-_mutable_set_types = (set,)56-_mutable_mapping_types = (dict,)57-_mutable_sequence_types = (list,)58-59-# on python 2.x we can register the user collection types60-try:61- from UserDict import UserDict, DictMixin62- from UserList import UserList63-64- _mutable_mapping_types += (UserDict, DictMixin)65- _mutable_set_types += (UserList,)66-except ImportError:67- pass68-69-# if sets is still available, register the mutable set from there as well70-try:71- from sets import Set72-73- _mutable_set_types += (Set,)74-except ImportError:75- pass76-77-#: register Python 2.6 abstract base classes78-_mutable_set_types += (abc.MutableSet,)79-_mutable_mapping_types += (abc.MutableMapping,)80-_mutable_sequence_types += (abc.MutableSequence,)81-82-_mutable_spec = (83- (84- _mutable_set_types,85- frozenset(86- [87- "add",88- "clear",89- "difference_update",90- "discard",91- "pop",92- "remove",93- "symmetric_difference_update",94- "update",95- ]96- ),97- ),98- (99- _mutable_mapping_types,100- frozenset(["clear", "pop", "popitem", "setdefault", "update"]),101- ),102- (103- _mutable_sequence_types,104- frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),105- ),106- (107- deque,108- frozenset(109- [110- "append",111- "appendleft",112- "clear",113- "extend",114- "extendleft",115- "pop",116- "popleft",117- "remove",118- "rotate",119- ]120- ),121- ),122-)123-124-125-class _MagicFormatMapping(abc.Mapping):126- """This class implements a dummy wrapper to fix a bug in the Python127- standard library for string formatting.128-129- See https://bugs.python.org/issue13598 for information about why130- this is necessary.131- """132-133- def __init__(self, args, kwargs):134- self._args = args135- self._kwargs = kwargs136- self._last_index = 0137-138- def __getitem__(self, key):139- if key == "":140- idx = self._last_index141- self._last_index += 1142- try:143- return self._args[idx]144- except LookupError:145- pass146- key = str(idx)147- return self._kwargs[key]148-149- def __iter__(self):150- return iter(self._kwargs)151-152- def __len__(self):153- return len(self._kwargs)154-155-156-def inspect_format_method(callable):157- if not isinstance(158- callable, (types.MethodType, types.BuiltinMethodType)159- ) or callable.__name__ not in ("format", "format_map"):160- return None161- obj = callable.__self__162- if isinstance(obj, string_types):163- return obj164-165-166-def safe_range(*args):167- """A range that can't generate ranges with a length of more than168- MAX_RANGE items.169- """170- rng = range_type(*args)171-172- if len(rng) > MAX_RANGE:173- raise OverflowError(174- "Range too big. The sandbox blocks ranges larger than"175- " MAX_RANGE (%d)." % MAX_RANGE176- )177-178- return rng179-180-181-def unsafe(f):182- """Marks a function or method as unsafe.183-184- ::185-186- @unsafe187- def delete(self):188- pass189- """190- f.unsafe_callable = True191- return f192-193-194-def is_internal_attribute(obj, attr):195- """Test if the attribute given is an internal python attribute. For196- example this function returns `True` for the `func_code` attribute of197- python objects. This is useful if the environment method198- :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.199-200- >>> from jinja2.sandbox import is_internal_attribute201- >>> is_internal_attribute(str, "mro")202- True203- >>> is_internal_attribute(str, "upper")204- False205- """206- if isinstance(obj, types.FunctionType):207- if attr in UNSAFE_FUNCTION_ATTRIBUTES:208- return True209- elif isinstance(obj, types.MethodType):210- if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:211- return True212- elif isinstance(obj, type):213- if attr == "mro":214- return True215- elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):216- return True217- elif isinstance(obj, types.GeneratorType):218- if attr in UNSAFE_GENERATOR_ATTRIBUTES:219- return True220- elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):221- if attr in UNSAFE_COROUTINE_ATTRIBUTES:222- return True223- elif hasattr(types, "AsyncGeneratorType") and isinstance(224- obj, types.AsyncGeneratorType225- ):226- if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:227- return True228- return attr.startswith("__")229-230-231-def modifies_known_mutable(obj, attr):232- """This function checks if an attribute on a builtin mutable object233- (list, dict, set or deque) would modify it if called. It also supports234- the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and235- with Python 2.6 onwards the abstract base classes `MutableSet`,236- `MutableMapping`, and `MutableSequence`.237-238- >>> modifies_known_mutable({}, "clear")239- True240- >>> modifies_known_mutable({}, "keys")241- False242- >>> modifies_known_mutable([], "append")243- True244- >>> modifies_known_mutable([], "index")245- False246-247- If called with an unsupported object (such as unicode) `False` is248- returned.249-250- >>> modifies_known_mutable("foo", "upper")251- False252- """253- for typespec, unsafe in _mutable_spec:254- if isinstance(obj, typespec):255- return attr in unsafe256- return False257-258-259-class SandboxedEnvironment(Environment):260- """The sandboxed environment. It works like the regular environment but261- tells the compiler to generate sandboxed code. Additionally subclasses of262- this environment may override the methods that tell the runtime what263- attributes or functions are safe to access.264-265- If the template tries to access insecure code a :exc:`SecurityError` is266- raised. However also other exceptions may occur during the rendering so267- the caller has to ensure that all exceptions are caught.268- """269-270- sandboxed = True271-272- #: default callback table for the binary operators. A copy of this is273- #: available on each instance of a sandboxed environment as274- #: :attr:`binop_table`275- default_binop_table = {276- "+": operator.add,277- "-": operator.sub,278- "*": operator.mul,279- "/": operator.truediv,280- "//": operator.floordiv,281- "**": operator.pow,282- "%": operator.mod,283- }284-285- #: default callback table for the unary operators. A copy of this is286- #: available on each instance of a sandboxed environment as287- #: :attr:`unop_table`288- default_unop_table = {"+": operator.pos, "-": operator.neg}289-290- #: a set of binary operators that should be intercepted. Each operator291- #: that is added to this set (empty by default) is delegated to the292- #: :meth:`call_binop` method that will perform the operator. The default293- #: operator callback is specified by :attr:`binop_table`.294- #:295- #: The following binary operators are interceptable:296- #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``297- #:298- #: The default operation form the operator table corresponds to the299- #: builtin function. Intercepted calls are always slower than the native300- #: operator call, so make sure only to intercept the ones you are301- #: interested in.302- #:303- #: .. versionadded:: 2.6304- intercepted_binops = frozenset()305-306- #: a set of unary operators that should be intercepted. Each operator307- #: that is added to this set (empty by default) is delegated to the308- #: :meth:`call_unop` method that will perform the operator. The default309- #: operator callback is specified by :attr:`unop_table`.310- #:311- #: The following unary operators are interceptable: ``+``, ``-``312- #:313- #: The default operation form the operator table corresponds to the314- #: builtin function. Intercepted calls are always slower than the native315- #: operator call, so make sure only to intercept the ones you are316- #: interested in.317- #:318- #: .. versionadded:: 2.6319- intercepted_unops = frozenset()320-321- def intercept_unop(self, operator):322- """Called during template compilation with the name of a unary323- operator to check if it should be intercepted at runtime. If this324- method returns `True`, :meth:`call_unop` is executed for this unary325- operator. The default implementation of :meth:`call_unop` will use326- the :attr:`unop_table` dictionary to perform the operator with the327- same logic as the builtin one.328-329- The following unary operators are interceptable: ``+`` and ``-``330-331- Intercepted calls are always slower than the native operator call,332- so make sure only to intercept the ones you are interested in.333-334- .. versionadded:: 2.6335- """336- return False337-338- def __init__(self, *args, **kwargs):339- Environment.__init__(self, *args, **kwargs)340- self.globals["range"] = safe_range341- self.binop_table = self.default_binop_table.copy()342- self.unop_table = self.default_unop_table.copy()343-344- def is_safe_attribute(self, obj, attr, value):345- """The sandboxed environment will call this method to check if the346- attribute of an object is safe to access. Per default all attributes347- starting with an underscore are considered private as well as the348- special attributes of internal python objects as returned by the349- :func:`is_internal_attribute` function.350- """351- return not (attr.startswith("_") or is_internal_attribute(obj, attr))352-353- def is_safe_callable(self, obj):354- """Check if an object is safely callable. Per default a function is355- considered safe unless the `unsafe_callable` attribute exists and is356- True. Override this method to alter the behavior, but this won't357- affect the `unsafe` decorator from this module.358- """359- return not (360- getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)361- )362-363- def call_binop(self, context, operator, left, right):364- """For intercepted binary operator calls (:meth:`intercepted_binops`)365- this function is executed instead of the builtin operator. This can366- be used to fine tune the behavior of certain operators.367-368- .. versionadded:: 2.6369- """370- return self.binop_table[operator](left, right)371-372- def call_unop(self, context, operator, arg):373- """For intercepted unary operator calls (:meth:`intercepted_unops`)374- this function is executed instead of the builtin operator. This can375- be used to fine tune the behavior of certain operators.376-377- .. versionadded:: 2.6378- """379- return self.unop_table[operator](arg)380-381- def getitem(self, obj, argument):382- """Subscribe an object from sandboxed code."""383- try:384- return obj[argument]385- except (TypeError, LookupError):386- if isinstance(argument, string_types):387- try:388- attr = str(argument)389- except Exception:390- pass391- else:392- try:393- value = getattr(obj, attr)394- except AttributeError:395- pass396- else:397- if self.is_safe_attribute(obj, argument, value):398- return value399- return self.unsafe_undefined(obj, argument)400- return self.undefined(obj=obj, name=argument)401-402- def getattr(self, obj, attribute):403- """Subscribe an object from sandboxed code and prefer the404- attribute. The attribute passed *must* be a bytestring.405- """406- try:407- value = getattr(obj, attribute)408- except AttributeError:409- try:410- return obj[attribute]411- except (TypeError, LookupError):412- pass413- else:414- if self.is_safe_attribute(obj, attribute, value):415- return value416- return self.unsafe_undefined(obj, attribute)417- return self.undefined(obj=obj, name=attribute)418-419- def unsafe_undefined(self, obj, attribute):420- """Return an undefined object for unsafe attributes."""421- return self.undefined(422- "access to attribute %r of %r "423- "object is unsafe." % (attribute, obj.__class__.__name__),424- name=attribute,425- obj=obj,426- exc=SecurityError,427- )428-429- def format_string(self, s, args, kwargs, format_func=None):430- """If a format call is detected, then this is routed through this431- method so that our safety sandbox can be used for it.432- """433- if isinstance(s, Markup):434- formatter = SandboxedEscapeFormatter(self, s.escape)435- else:436- formatter = SandboxedFormatter(self)437-438- if format_func is not None and format_func.__name__ == "format_map":439- if len(args) != 1 or kwargs:440- raise TypeError(441- "format_map() takes exactly one argument %d given"442- % (len(args) + (kwargs is not None))443- )444-445- kwargs = args[0]446- args = None447-448- kwargs = _MagicFormatMapping(args, kwargs)449- rv = formatter.vformat(s, args, kwargs)450- return type(s)(rv)451-452- def call(__self, __context, __obj, *args, **kwargs): # noqa: B902453- """Call an object from sandboxed code."""454- fmt = inspect_format_method(__obj)455- if fmt is not None:456- return __self.format_string(fmt, args, kwargs, __obj)457-458- # the double prefixes are to avoid double keyword argument459- # errors when proxying the call.460- if not __self.is_safe_callable(__obj):461- raise SecurityError("%r is not safely callable" % (__obj,))462- return __context.call(__obj, *args, **kwargs)463-464-465-class ImmutableSandboxedEnvironment(SandboxedEnvironment):466- """Works exactly like the regular `SandboxedEnvironment` but does not467- permit modifications on the builtin mutable objects `list`, `set`, and468- `dict` by using the :func:`modifies_known_mutable` function.469- """470-471- def is_safe_attribute(self, obj, attr, value):472- if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):473- return False474- return not modifies_known_mutable(obj, attr)475-476-477-# This really is not a public API apparently.478-try:479- from _string import formatter_field_name_split480-except ImportError:481-482- def formatter_field_name_split(field_name):483- return field_name._formatter_field_name_split()484-485-486-class SandboxedFormatterMixin(object):487- def __init__(self, env):488- self._env = env489-490- def get_field(self, field_name, args, kwargs):491- first, rest = formatter_field_name_split(field_name)492- obj = self.get_value(first, args, kwargs)493- for is_attr, i in rest:494- if is_attr:495- obj = self._env.getattr(obj, i)496- else:497- obj = self._env.getitem(obj, i)498- return obj, first499-500-501-class SandboxedFormatter(SandboxedFormatterMixin, Formatter):502- def __init__(self, env):503- SandboxedFormatterMixin.__init__(self, env)504- Formatter.__init__(self)505-506-507-class SandboxedEscapeFormatter(SandboxedFormatterMixin, EscapeFormatter):508- def __init__(self, env, escape):509- SandboxedFormatterMixin.__init__(self, env)510- EscapeFormatter.__init__(self, escape)deleted:src/jinja2/tests.py-215 removed
1-# -*- coding: utf-8 -*-2-"""Built-in template tests used with the ``is`` operator."""3-import decimal4-import operator5-import re6-7-from ._compat import abc8-from ._compat import integer_types9-from ._compat import string_types10-from ._compat import text_type11-from .runtime import Undefined12-13-number_re = re.compile(r"^-?\d+(\.\d+)?$")14-regex_type = type(number_re)15-test_callable = callable16-17-18-def test_odd(value):19- """Return true if the variable is odd."""20- return value % 2 == 121-22-23-def test_even(value):24- """Return true if the variable is even."""25- return value % 2 == 026-27-28-def test_divisibleby(value, num):29- """Check if a variable is divisible by a number."""30- return value % num == 031-32-33-def test_defined(value):34- """Return true if the variable is defined:35-36- .. sourcecode:: jinja37-38- {% if variable is defined %}39- value of variable: {{ variable }}40- {% else %}41- variable is not defined42- {% endif %}43-44- See the :func:`default` filter for a simple way to set undefined45- variables.46- """47- return not isinstance(value, Undefined)48-49-50-def test_undefined(value):51- """Like :func:`defined` but the other way round."""52- return isinstance(value, Undefined)53-54-55-def test_none(value):56- """Return true if the variable is none."""57- return value is None58-59-60-def test_boolean(value):61- """Return true if the object is a boolean value.62-63- .. versionadded:: 2.1164- """65- return value is True or value is False66-67-68-def test_false(value):69- """Return true if the object is False.70-71- .. versionadded:: 2.1172- """73- return value is False74-75-76-def test_true(value):77- """Return true if the object is True.78-79- .. versionadded:: 2.1180- """81- return value is True82-83-84-# NOTE: The existing 'number' test matches booleans and floats85-def test_integer(value):86- """Return true if the object is an integer.87-88- .. versionadded:: 2.1189- """90- return isinstance(value, integer_types) and value is not True and value is not False91-92-93-# NOTE: The existing 'number' test matches booleans and integers94-def test_float(value):95- """Return true if the object is a float.96-97- .. versionadded:: 2.1198- """99- return isinstance(value, float)100-101-102-def test_lower(value):103- """Return true if the variable is lowercased."""104- return text_type(value).islower()105-106-107-def test_upper(value):108- """Return true if the variable is uppercased."""109- return text_type(value).isupper()110-111-112-def test_string(value):113- """Return true if the object is a string."""114- return isinstance(value, string_types)115-116-117-def test_mapping(value):118- """Return true if the object is a mapping (dict etc.).119-120- .. versionadded:: 2.6121- """122- return isinstance(value, abc.Mapping)123-124-125-def test_number(value):126- """Return true if the variable is a number."""127- return isinstance(value, integer_types + (float, complex, decimal.Decimal))128-129-130-def test_sequence(value):131- """Return true if the variable is a sequence. Sequences are variables132- that are iterable.133- """134- try:135- len(value)136- value.__getitem__137- except Exception:138- return False139- return True140-141-142-def test_sameas(value, other):143- """Check if an object points to the same memory address than another144- object:145-146- .. sourcecode:: jinja147-148- {% if foo.attribute is sameas false %}149- the foo attribute really is the `False` singleton150- {% endif %}151- """152- return value is other153-154-155-def test_iterable(value):156- """Check if it's possible to iterate over an object."""157- try:158- iter(value)159- except TypeError:160- return False161- return True162-163-164-def test_escaped(value):165- """Check if the value is escaped."""166- return hasattr(value, "__html__")167-168-169-def test_in(value, seq):170- """Check if value is in seq.171-172- .. versionadded:: 2.10173- """174- return value in seq175-176-177-TESTS = {178- "odd": test_odd,179- "even": test_even,180- "divisibleby": test_divisibleby,181- "defined": test_defined,182- "undefined": test_undefined,183- "none": test_none,184- "boolean": test_boolean,185- "false": test_false,186- "true": test_true,187- "integer": test_integer,188- "float": test_float,189- "lower": test_lower,190- "upper": test_upper,191- "string": test_string,192- "mapping": test_mapping,193- "number": test_number,194- "sequence": test_sequence,195- "iterable": test_iterable,196- "callable": test_callable,197- "sameas": test_sameas,198- "escaped": test_escaped,199- "in": test_in,200- "==": operator.eq,201- "eq": operator.eq,202- "equalto": operator.eq,203- "!=": operator.ne,204- "ne": operator.ne,205- ">": operator.gt,206- "gt": operator.gt,207- "greaterthan": operator.gt,208- "ge": operator.ge,209- ">=": operator.ge,210- "<": operator.lt,211- "lt": operator.lt,212- "lessthan": operator.lt,213- "<=": operator.le,214- "le": operator.le,215-}deleted:src/jinja2/utils.py-727 removed
1-# -*- coding: utf-8 -*-2-import json3-import os4-import re5-import warnings6-from collections import deque7-from random import choice8-from random import randrange9-from threading import Lock10-11-from markupsafe import escape12-from markupsafe import Markup13-14-from ._compat import abc15-from ._compat import string_types16-from ._compat import text_type17-from ._compat import url_quote18-19-_word_split_re = re.compile(r"(\s+)")20-_punctuation_re = re.compile(21- "^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$"22- % (23- "|".join(map(re.escape, ("(", "<", "<"))),24- "|".join(map(re.escape, (".", ",", ")", ">", "\n", ">"))),25- )26-)27-_simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")28-_striptags_re = re.compile(r"(<!--.*?-->|<[^>]*>)")29-_entity_re = re.compile(r"&([^;]+);")30-_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"31-_digits = "0123456789"32-33-# special singleton representing missing values for the runtime34-missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()35-36-# internal code37-internal_code = set()38-39-concat = u"".join40-41-_slash_escape = "\\/" not in json.dumps("/")42-43-44-def contextfunction(f):45- """This decorator can be used to mark a function or method context callable.46- A context callable is passed the active :class:`Context` as first argument when47- called from the template. This is useful if a function wants to get access48- to the context or functions provided on the context object. For example49- a function that returns a sorted list of template variables the current50- template exports could look like this::51-52- @contextfunction53- def get_exported_names(context):54- return sorted(context.exported_vars)55- """56- f.contextfunction = True57- return f58-59-60-def evalcontextfunction(f):61- """This decorator can be used to mark a function or method as an eval62- context callable. This is similar to the :func:`contextfunction`63- but instead of passing the context, an evaluation context object is64- passed. For more information about the eval context, see65- :ref:`eval-context`.66-67- .. versionadded:: 2.468- """69- f.evalcontextfunction = True70- return f71-72-73-def environmentfunction(f):74- """This decorator can be used to mark a function or method as environment75- callable. This decorator works exactly like the :func:`contextfunction`76- decorator just that the first argument is the active :class:`Environment`77- and not context.78- """79- f.environmentfunction = True80- return f81-82-83-def internalcode(f):84- """Marks the function as internally used"""85- internal_code.add(f.__code__)86- return f87-88-89-def is_undefined(obj):90- """Check if the object passed is undefined. This does nothing more than91- performing an instance check against :class:`Undefined` but looks nicer.92- This can be used for custom filters or tests that want to react to93- undefined variables. For example a custom default filter can look like94- this::95-96- def default(var, default=''):97- if is_undefined(var):98- return default99- return var100- """101- from .runtime import Undefined102-103- return isinstance(obj, Undefined)104-105-106-def consume(iterable):107- """Consumes an iterable without doing anything with it."""108- for _ in iterable:109- pass110-111-112-def clear_caches():113- """Jinja keeps internal caches for environments and lexers. These are114- used so that Jinja doesn't have to recreate environments and lexers all115- the time. Normally you don't have to care about that but if you are116- measuring memory consumption you may want to clean the caches.117- """118- from .environment import _spontaneous_environments119- from .lexer import _lexer_cache120-121- _spontaneous_environments.clear()122- _lexer_cache.clear()123-124-125-def import_string(import_name, silent=False):126- """Imports an object based on a string. This is useful if you want to127- use import paths as endpoints or something similar. An import path can128- be specified either in dotted notation (``xml.sax.saxutils.escape``)129- or with a colon as object delimiter (``xml.sax.saxutils:escape``).130-131- If the `silent` is True the return value will be `None` if the import132- fails.133-134- :return: imported object135- """136- try:137- if ":" in import_name:138- module, obj = import_name.split(":", 1)139- elif "." in import_name:140- module, _, obj = import_name.rpartition(".")141- else:142- return __import__(import_name)143- return getattr(__import__(module, None, None, [obj]), obj)144- except (ImportError, AttributeError):145- if not silent:146- raise147-148-149-def open_if_exists(filename, mode="rb"):150- """Returns a file descriptor for the filename if that file exists,151- otherwise ``None``.152- """153- if not os.path.isfile(filename):154- return None155-156- return open(filename, mode)157-158-159-def object_type_repr(obj):160- """Returns the name of the object's type. For some recognized161- singletons the name of the object is returned instead. (For162- example for `None` and `Ellipsis`).163- """164- if obj is None:165- return "None"166- elif obj is Ellipsis:167- return "Ellipsis"168- # __builtin__ in 2.x, builtins in 3.x169- if obj.__class__.__module__ in ("__builtin__", "builtins"):170- name = obj.__class__.__name__171- else:172- name = obj.__class__.__module__ + "." + obj.__class__.__name__173- return "%s object" % name174-175-176-def pformat(obj, verbose=False):177- """Prettyprint an object. Either use the `pretty` library or the178- builtin `pprint`.179- """180- try:181- from pretty import pretty182-183- return pretty(obj, verbose=verbose)184- except ImportError:185- from pprint import pformat186-187- return pformat(obj)188-189-190-def urlize(text, trim_url_limit=None, rel=None, target=None):191- """Converts any URLs in text into clickable links. Works on http://,192- https:// and www. links. Links can have trailing punctuation (periods,193- commas, close-parens) and leading punctuation (opening parens) and194- it'll still do the right thing.195-196- If trim_url_limit is not None, the URLs in link text will be limited197- to trim_url_limit characters.198-199- If nofollow is True, the URLs in link text will get a rel="nofollow"200- attribute.201-202- If target is not None, a target attribute will be added to the link.203- """204- trim_url = (205- lambda x, limit=trim_url_limit: limit is not None206- and (x[:limit] + (len(x) >= limit and "..." or ""))207- or x208- )209- words = _word_split_re.split(text_type(escape(text)))210- rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ""211- target_attr = target and ' target="%s"' % escape(target) or ""212-213- for i, word in enumerate(words):214- match = _punctuation_re.match(word)215- if match:216- lead, middle, trail = match.groups()217- if middle.startswith("www.") or (218- "@" not in middle219- and not middle.startswith("http://")220- and not middle.startswith("https://")221- and len(middle) > 0222- and middle[0] in _letters + _digits223- and (224- middle.endswith(".org")225- or middle.endswith(".net")226- or middle.endswith(".com")227- )228- ):229- middle = '<a href="http://%s"%s%s>%s</a>' % (230- middle,231- rel_attr,232- target_attr,233- trim_url(middle),234- )235- if middle.startswith("http://") or middle.startswith("https://"):236- middle = '<a href="%s"%s%s>%s</a>' % (237- middle,238- rel_attr,239- target_attr,240- trim_url(middle),241- )242- if (243- "@" in middle244- and not middle.startswith("www.")245- and ":" not in middle246- and _simple_email_re.match(middle)247- ):248- middle = '<a href="mailto:%s">%s</a>' % (middle, middle)249- if lead + middle + trail != word:250- words[i] = lead + middle + trail251- return u"".join(words)252-253-254-def generate_lorem_ipsum(n=5, html=True, min=20, max=100):255- """Generate some lorem ipsum for the template."""256- from .constants import LOREM_IPSUM_WORDS257-258- words = LOREM_IPSUM_WORDS.split()259- result = []260-261- for _ in range(n):262- next_capitalized = True263- last_comma = last_fullstop = 0264- word = None265- last = None266- p = []267-268- # each paragraph contains out of 20 to 100 words.269- for idx, _ in enumerate(range(randrange(min, max))):270- while True:271- word = choice(words)272- if word != last:273- last = word274- break275- if next_capitalized:276- word = word.capitalize()277- next_capitalized = False278- # add commas279- if idx - randrange(3, 8) > last_comma:280- last_comma = idx281- last_fullstop += 2282- word += ","283- # add end of sentences284- if idx - randrange(10, 20) > last_fullstop:285- last_comma = last_fullstop = idx286- word += "."287- next_capitalized = True288- p.append(word)289-290- # ensure that the paragraph ends with a dot.291- p = u" ".join(p)292- if p.endswith(","):293- p = p[:-1] + "."294- elif not p.endswith("."):295- p += "."296- result.append(p)297-298- if not html:299- return u"\n\n".join(result)300- return Markup(u"\n".join(u"<p>%s</p>" % escape(x) for x in result))301-302-303-def unicode_urlencode(obj, charset="utf-8", for_qs=False):304- """Quote a string for use in a URL using the given charset.305-306- This function is misnamed, it is a wrapper around307- :func:`urllib.parse.quote`.308-309- :param obj: String or bytes to quote. Other types are converted to310- string then encoded to bytes using the given charset.311- :param charset: Encode text to bytes using this charset.312- :param for_qs: Quote "/" and use "+" for spaces.313- """314- if not isinstance(obj, string_types):315- obj = text_type(obj)316-317- if isinstance(obj, text_type):318- obj = obj.encode(charset)319-320- safe = b"" if for_qs else b"/"321- rv = url_quote(obj, safe)322-323- if not isinstance(rv, text_type):324- rv = rv.decode("utf-8")325-326- if for_qs:327- rv = rv.replace("%20", "+")328-329- return rv330-331-332-class LRUCache(object):333- """A simple LRU Cache implementation."""334-335- # this is fast for small capacities (something below 1000) but doesn't336- # scale. But as long as it's only used as storage for templates this337- # won't do any harm.338-339- def __init__(self, capacity):340- self.capacity = capacity341- self._mapping = {}342- self._queue = deque()343- self._postinit()344-345- def _postinit(self):346- # alias all queue methods for faster lookup347- self._popleft = self._queue.popleft348- self._pop = self._queue.pop349- self._remove = self._queue.remove350- self._wlock = Lock()351- self._append = self._queue.append352-353- def __getstate__(self):354- return {355- "capacity": self.capacity,356- "_mapping": self._mapping,357- "_queue": self._queue,358- }359-360- def __setstate__(self, d):361- self.__dict__.update(d)362- self._postinit()363-364- def __getnewargs__(self):365- return (self.capacity,)366-367- def copy(self):368- """Return a shallow copy of the instance."""369- rv = self.__class__(self.capacity)370- rv._mapping.update(self._mapping)371- rv._queue.extend(self._queue)372- return rv373-374- def get(self, key, default=None):375- """Return an item from the cache dict or `default`"""376- try:377- return self[key]378- except KeyError:379- return default380-381- def setdefault(self, key, default=None):382- """Set `default` if the key is not in the cache otherwise383- leave unchanged. Return the value of this key.384- """385- try:386- return self[key]387- except KeyError:388- self[key] = default389- return default390-391- def clear(self):392- """Clear the cache."""393- self._wlock.acquire()394- try:395- self._mapping.clear()396- self._queue.clear()397- finally:398- self._wlock.release()399-400- def __contains__(self, key):401- """Check if a key exists in this cache."""402- return key in self._mapping403-404- def __len__(self):405- """Return the current size of the cache."""406- return len(self._mapping)407-408- def __repr__(self):409- return "<%s %r>" % (self.__class__.__name__, self._mapping)410-411- def __getitem__(self, key):412- """Get an item from the cache. Moves the item up so that it has the413- highest priority then.414-415- Raise a `KeyError` if it does not exist.416- """417- self._wlock.acquire()418- try:419- rv = self._mapping[key]420- if self._queue[-1] != key:421- try:422- self._remove(key)423- except ValueError:424- # if something removed the key from the container425- # when we read, ignore the ValueError that we would426- # get otherwise.427- pass428- self._append(key)429- return rv430- finally:431- self._wlock.release()432-433- def __setitem__(self, key, value):434- """Sets the value for an item. Moves the item up so that it435- has the highest priority then.436- """437- self._wlock.acquire()438- try:439- if key in self._mapping:440- self._remove(key)441- elif len(self._mapping) == self.capacity:442- del self._mapping[self._popleft()]443- self._append(key)444- self._mapping[key] = value445- finally:446- self._wlock.release()447-448- def __delitem__(self, key):449- """Remove an item from the cache dict.450- Raise a `KeyError` if it does not exist.451- """452- self._wlock.acquire()453- try:454- del self._mapping[key]455- try:456- self._remove(key)457- except ValueError:458- pass459- finally:460- self._wlock.release()461-462- def items(self):463- """Return a list of items."""464- result = [(key, self._mapping[key]) for key in list(self._queue)]465- result.reverse()466- return result467-468- def iteritems(self):469- """Iterate over all items."""470- warnings.warn(471- "'iteritems()' will be removed in version 3.0. Use"472- " 'iter(cache.items())' instead.",473- DeprecationWarning,474- stacklevel=2,475- )476- return iter(self.items())477-478- def values(self):479- """Return a list of all values."""480- return [x[1] for x in self.items()]481-482- def itervalue(self):483- """Iterate over all values."""484- warnings.warn(485- "'itervalue()' will be removed in version 3.0. Use"486- " 'iter(cache.values())' instead.",487- DeprecationWarning,488- stacklevel=2,489- )490- return iter(self.values())491-492- def itervalues(self):493- """Iterate over all values."""494- warnings.warn(495- "'itervalues()' will be removed in version 3.0. Use"496- " 'iter(cache.values())' instead.",497- DeprecationWarning,498- stacklevel=2,499- )500- return iter(self.values())501-502- def keys(self):503- """Return a list of all keys ordered by most recent usage."""504- return list(self)505-506- def iterkeys(self):507- """Iterate over all keys in the cache dict, ordered by508- the most recent usage.509- """510- warnings.warn(511- "'iterkeys()' will be removed in version 3.0. Use"512- " 'iter(cache.keys())' instead.",513- DeprecationWarning,514- stacklevel=2,515- )516- return iter(self)517-518- def __iter__(self):519- return reversed(tuple(self._queue))520-521- def __reversed__(self):522- """Iterate over the keys in the cache dict, oldest items523- coming first.524- """525- return iter(tuple(self._queue))526-527- __copy__ = copy528-529-530-abc.MutableMapping.register(LRUCache)531-532-533-def select_autoescape(534- enabled_extensions=("html", "htm", "xml"),535- disabled_extensions=(),536- default_for_string=True,537- default=False,538-):539- """Intelligently sets the initial value of autoescaping based on the540- filename of the template. This is the recommended way to configure541- autoescaping if you do not want to write a custom function yourself.542-543- If you want to enable it for all templates created from strings or544- for all templates with `.html` and `.xml` extensions::545-546- from jinja2 import Environment, select_autoescape547- env = Environment(autoescape=select_autoescape(548- enabled_extensions=('html', 'xml'),549- default_for_string=True,550- ))551-552- Example configuration to turn it on at all times except if the template553- ends with `.txt`::554-555- from jinja2 import Environment, select_autoescape556- env = Environment(autoescape=select_autoescape(557- disabled_extensions=('txt',),558- default_for_string=True,559- default=True,560- ))561-562- The `enabled_extensions` is an iterable of all the extensions that563- autoescaping should be enabled for. Likewise `disabled_extensions` is564- a list of all templates it should be disabled for. If a template is565- loaded from a string then the default from `default_for_string` is used.566- If nothing matches then the initial value of autoescaping is set to the567- value of `default`.568-569- For security reasons this function operates case insensitive.570-571- .. versionadded:: 2.9572- """573- enabled_patterns = tuple("." + x.lstrip(".").lower() for x in enabled_extensions)574- disabled_patterns = tuple("." + x.lstrip(".").lower() for x in disabled_extensions)575-576- def autoescape(template_name):577- if template_name is None:578- return default_for_string579- template_name = template_name.lower()580- if template_name.endswith(enabled_patterns):581- return True582- if template_name.endswith(disabled_patterns):583- return False584- return default585-586- return autoescape587-588-589-def htmlsafe_json_dumps(obj, dumper=None, **kwargs):590- """Works exactly like :func:`dumps` but is safe for use in ``<script>``591- tags. It accepts the same arguments and returns a JSON string. Note that592- this is available in templates through the ``|tojson`` filter which will593- also mark the result as safe. Due to how this function escapes certain594- characters this is safe even if used outside of ``<script>`` tags.595-596- The following characters are escaped in strings:597-598- - ``<``599- - ``>``600- - ``&``601- - ``'``602-603- This makes it safe to embed such strings in any place in HTML with the604- notable exception of double quoted attributes. In that case single605- quote your attributes or HTML escape it in addition.606- """607- if dumper is None:608- dumper = json.dumps609- rv = (610- dumper(obj, **kwargs)611- .replace(u"<", u"\\u003c")612- .replace(u">", u"\\u003e")613- .replace(u"&", u"\\u0026")614- .replace(u"'", u"\\u0027")615- )616- return Markup(rv)617-618-619-class Cycler(object):620- """Cycle through values by yield them one at a time, then restarting621- once the end is reached. Available as ``cycler`` in templates.622-623- Similar to ``loop.cycle``, but can be used outside loops or across624- multiple loops. For example, render a list of folders and files in a625- list, alternating giving them "odd" and "even" classes.626-627- .. code-block:: html+jinja628-629- {% set row_class = cycler("odd", "even") %}630- <ul class="browser">631- {% for folder in folders %}632- <li class="folder {{ row_class.next() }}">{{ folder }}633- {% endfor %}634- {% for file in files %}635- <li class="file {{ row_class.next() }}">{{ file }}636- {% endfor %}637- </ul>638-639- :param items: Each positional argument will be yielded in the order640- given for each cycle.641-642- .. versionadded:: 2.1643- """644-645- def __init__(self, *items):646- if not items:647- raise RuntimeError("at least one item has to be provided")648- self.items = items649- self.pos = 0650-651- def reset(self):652- """Resets the current item to the first item."""653- self.pos = 0654-655- @property656- def current(self):657- """Return the current item. Equivalent to the item that will be658- returned next time :meth:`next` is called.659- """660- return self.items[self.pos]661-662- def next(self):663- """Return the current item, then advance :attr:`current` to the664- next item.665- """666- rv = self.current667- self.pos = (self.pos + 1) % len(self.items)668- return rv669-670- __next__ = next671-672-673-class Joiner(object):674- """A joining helper for templates."""675-676- def __init__(self, sep=u", "):677- self.sep = sep678- self.used = False679-680- def __call__(self):681- if not self.used:682- self.used = True683- return u""684- return self.sep685-686-687-class Namespace(object):688- """A namespace object that can hold arbitrary attributes. It may be689- initialized from a dictionary or with keyword arguments."""690-691- def __init__(*args, **kwargs): # noqa: B902692- self, args = args[0], args[1:]693- self.__attrs = dict(*args, **kwargs)694-695- def __getattribute__(self, name):696- if name == "_Namespace__attrs":697- return object.__getattribute__(self, name)698- try:699- return self.__attrs[name]700- except KeyError:701- raise AttributeError(name)702-703- def __setitem__(self, name, value):704- self.__attrs[name] = value705-706- def __repr__(self):707- return "<Namespace %r>" % self.__attrs708-709-710-# does this python version support async for in and async generators?711-try:712- exec("async def _():\n async for _ in ():\n yield _")713- have_async_gen = True714-except SyntaxError:715- have_async_gen = False716-717-718-def soft_unicode(s):719- from markupsafe import soft_unicode720-721- warnings.warn(722- "'jinja2.utils.soft_unicode' will be removed in version 3.0."723- " Use 'markupsafe.soft_unicode' instead.",724- DeprecationWarning,725- stacklevel=2,726- )727- return soft_unicode(s)deleted:src/jinja2/visitor.py-81 removed
1-# -*- coding: utf-8 -*-2-"""API for traversing the AST nodes. Implemented by the compiler and3-meta introspection.4-"""5-from .nodes import Node6-7-8-class NodeVisitor(object):9- """Walks the abstract syntax tree and call visitor functions for every10- node found. The visitor functions may return values which will be11- forwarded by the `visit` method.12-13- Per default the visitor functions for the nodes are ``'visit_'`` +14- class name of the node. So a `TryFinally` node visit function would15- be `visit_TryFinally`. This behavior can be changed by overriding16- the `get_visitor` function. If no visitor function exists for a node17- (return value `None`) the `generic_visit` visitor is used instead.18- """19-20- def get_visitor(self, node):21- """Return the visitor function for this node or `None` if no visitor22- exists for this node. In that case the generic visit function is23- used instead.24- """25- method = "visit_" + node.__class__.__name__26- return getattr(self, method, None)27-28- def visit(self, node, *args, **kwargs):29- """Visit a node."""30- f = self.get_visitor(node)31- if f is not None:32- return f(node, *args, **kwargs)33- return self.generic_visit(node, *args, **kwargs)34-35- def generic_visit(self, node, *args, **kwargs):36- """Called if no explicit visitor function exists for a node."""37- for node in node.iter_child_nodes():38- self.visit(node, *args, **kwargs)39-40-41-class NodeTransformer(NodeVisitor):42- """Walks the abstract syntax tree and allows modifications of nodes.43-44- The `NodeTransformer` will walk the AST and use the return value of the45- visitor functions to replace or remove the old node. If the return46- value of the visitor function is `None` the node will be removed47- from the previous location otherwise it's replaced with the return48- value. The return value may be the original node in which case no49- replacement takes place.50- """51-52- def generic_visit(self, node, *args, **kwargs):53- for field, old_value in node.iter_fields():54- if isinstance(old_value, list):55- new_values = []56- for value in old_value:57- if isinstance(value, Node):58- value = self.visit(value, *args, **kwargs)59- if value is None:60- continue61- elif not isinstance(value, Node):62- new_values.extend(value)63- continue64- new_values.append(value)65- old_value[:] = new_values66- elif isinstance(old_value, Node):67- new_node = self.visit(old_value, *args, **kwargs)68- if new_node is None:69- delattr(node, field)70- else:71- setattr(node, field, new_node)72- return node73-74- def visit_list(self, node, *args, **kwargs):75- """As transformers may return lists in some places this method76- can be used to enforce a list as return value.77- """78- rv = self.visit(node, *args, **kwargs)79- if not isinstance(rv, list):80- rv = [rv]81- return rv