added globals
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 625215e · Browse files · 4 files·+137 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+137 added−31 removed
- other:+137 added−31 removed
Provenance
- Commit
fed44b5- Tree
b70f738- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
625215e
4 files changed+137 added−31 removed
modified:jinja2/compiler.py+89 added-18 removed
37 unmodified lines38 39 40 def generate(node, environment, filename, stream=None):41 """Generate the python source for a node tree."""42- is_child = node.find(nodes.Extends) is not None43- generator = CodeGenerator(environment, is_child, filename, stream)42+ generator = CodeGenerator(environment, filename, stream)43 generator.visit(node)44 if stream is None:45 return generator.stream.getvalue()46 65 unmodified lines112 """Holds compile time information for us."""113 114 def __init__(self, parent=None):115 self.identifiers = Identifiers()116+117 # a toplevel frame is the root + soft frames such as if conditions.118 self.toplevel = False119+120 # the root frame is basically just the outermost frame, so no if121 # conditions. This information is used to optimize inheritance122 # situations.123 self.rootlevel = False123- self.parent = parent124+125+ # inside some tags we are using a buffer rather than yield statements.126+ # this for example affects {% filter %} or {% macro %}. If a frame127+ # is buffered this variable points to the name of the list used as128+ # buffer.129 self.buffer = None130+131+ # if a frame has name_overrides, all read access to a name in this132+ # dict is redirected to a string expression.133 self.name_overrides = {}134+135+ # the name of the block we're in, otherwise None.136 self.block = parent and parent.block or None137+138+ # the parent of this frame139+ self.parent = parent140+141 if parent is not None:142 self.identifiers.declared.update(143 parent.identifiers.declared |144 parent.identifiers.declared_locally |82 unmodified lines227 228 229 class CodeGenerator(NodeVisitor):230 217- def __init__(self, environment, is_child, filename, stream=None):231+ def __init__(self, environment, filename, stream=None):232 if stream is None:233 stream = StringIO()234 self.environment = environment221- self.is_child = is_child235 self.filename = filename236 self.stream = stream237+238+ # a registry for all blocks. Because blocks are moved out239+ # into the global python scope they are registered here240 self.blocks = {}225- self.indentation = 0226- self.new_lines = 0227- self.last_identifier = 0241+242+ # the number of extends statements so far243 self.extends_so_far = 0244+245+ # some templates have a rootlevel extends. In this case we246+ # can safely assume that we're a child template and do some247+ # more optimizations.248 self.has_known_extends = False249+250+ # the number of new lines before the next write()251+ self._new_lines = 0252+253+ # the line number of the last written statement254 self._last_line = 0255+256+ # true if nothing was written so far.257 self._first_write = True258 259+ # used by the `temporary_identifier` method to get new260+ # unique, temporary identifier261+ self._last_identifier = 0262+263+ # the current indentation264+ self._indentation = 0265+266 def temporary_identifier(self):267+ """Get a new unique identifier."""234- self.last_identifier += 1235- return 't%d' % self.last_identifier268+ self._last_identifier += 1269+ return 't%d' % self._last_identifier270 271 def indent(self):272+ """Indent by one."""238- self.indentation += 1273+ self._indentation += 1274 275 def outdent(self, step=1):276+ """Outdent by step."""241- self.indentation -= step277+ self._indentation -= step278 279 def blockvisit(self, nodes, frame, indent=True, force_generator=True):280+ """Visit a list of nodes as block in a frame. Per default the281+ code is indented, but this can be disabled by setting the indent282+ parameter to False. If the current frame is no buffer a dummy283+ ``if 0: yield None`` is written automatically unless the284+ force_generator parameter is set to False.285+ """286 if indent:287 self.indent()288 if frame.buffer is None and force_generator:289 self.writeline('if 0: yield None')5 unmodified lines295 if indent:296 self.outdent()297 298 def write(self, x):299+ """Write a string into the output stream."""257- if self.new_lines:300+ if self._new_lines:301 if not self._first_write:259- self.stream.write('\n' * self.new_lines)302+ self.stream.write('\n' * self._new_lines)303 self._first_write = False261- self.stream.write(' ' * self.indentation)262- self.new_lines = 0304+ self.stream.write(' ' * self._indentation)305+ self._new_lines = 0306 self.stream.write(x)307 308 def writeline(self, x, node=None, extra=0):309+ """Combination of newline and write."""310 self.newline(node, extra)311 self.write(x)312 313 def newline(self, node=None, extra=0):314+ """Add one or more newlines before the next write."""270- self.new_lines = max(self.new_lines, 1 + extra)315+ self._new_lines = max(self._new_lines, 1 + extra)316 if node is not None and node.lineno != self._last_line:317 self.write('# line: %s' % node.lineno)273- self.new_lines = 1318+ self._new_lines = 1319 self._last_line = node.lineno320 321 def signature(self, node, frame, have_comma=True, extra_kwargs=None):322+ """Writes a function call to the stream for the current node.323+ Per default it will write a leading comma but this can be324+ disabled by setting have_comma to False. If extra_kwargs is325+ given it must be a string that represents a single keyword326+ argument call that is inserted at the end of the regular327+ keyword argument calls.328+ """329 have_comma = have_comma and [True] or []330 def touch_comma():331 if have_comma:332 self.write(', ')18 unmodified lines351 self.write('**')352 self.visit(node.dyn_kwargs, frame)353 354 def pull_locals(self, frame, indent=True):355+ """Pull all the references identifiers into the local scope.356+ This affects regular names, filters and tests. If indent is357+ set to False, no automatic indentation will take place.358+ """359 if indent:360 self.indent()361 for name in frame.identifiers.undeclared:362 self.writeline('l_%s = context[%r]' % (name, name))4 unmodified lines367 if indent:368 self.outdent()369 370 def collect_shadowed(self, frame):371+ """This function returns all the shadowed variables in a dict372+ in the form name: alias and will write the required assignments373+ into the current scope. No indentation takes place.374+ """375 # make sure we "backup" overridden, local identifiers376 # TODO: we should probably optimize this and check if the377 # identifier is in use afterwards.378 aliases = {}2 unmodified lines381 self.writeline('%s = l_%s' % (ident, name))382 return aliases383 384 def function_scoping(self, node, frame):385+ """In Jinja a few statements require the help of anonymous386+ functions. Those are currently macros and call blocks and in387+ the future also recursive loops. As there is currently388+ technical limitation that doesn't allow reading and writing a389+ variable in a scope where the initial value is coming from an390+ outer scope, this function tries to fall back with a common391+ error message. Additionally the frame passed is modified so392+ that the argumetns are collected and callers are looked up.393+394+ This will return the modified frame.395+ """396 func_frame = frame.inner()397 func_frame.inspect(node.iter_child_nodes(), hard_scope=True)398 399 # variables that are undeclared (accessed before declaration) and629 unmodified linesmodified:jinja2/environment.py+43 added-9 removed
30 unmodified lines31 comment_start_string='{#',32 comment_end_string='#}',33 line_statement_prefix=None,34 trim_blocks=False,35+ optimized=True,36 loader=None):37 """Here the possible initialization parameters:38 39 ========================= ============================================12 unmodified lines52 documentation for more details.53 `trim_blocks` If this is set to ``True`` the first newline54 after a block is removed (block, not55 variable tag!). Defaults to ``False``.56+ `optimized` should the optimizer be enabled? Default is57+ ``True``.58 `loader` the loader which should be used.59 ========================= ============================================60 """61 5 unmodified lines67 self.comment_start_string = comment_start_string68 self.comment_end_string = comment_end_string69 self.line_statement_prefix = line_statement_prefix70 self.trim_blocks = trim_blocks71+ self.optimized = optimized72 73 # defaults74 self.filters = DEFAULT_FILTERS.copy()75 self.tests = DEFAULT_TESTS.copy()28 unmodified lines104 The tuples are returned in the form ``(lineno, token, value)``.105 """106 return self.lexer.tokeniter(source, filename)107 104- def compile(self, source, filename=None, raw=False):108+ def compile(self, source, filename=None, raw=False, globals=None):109 """Compile a node or source."""110 if isinstance(source, basestring):111 source = self.parse(source, filename)112+ if self.optimized:108- node = optimize(source, self)113+ node = optimize(source, self, globals or {})114 source = generate(node, self, filename)115 if raw:116 return source117 if isinstance(filename, unicode):5 unmodified lines123 relative to the loader root, but if the paths should be relative this124 function can be used to calculate the real filename."""125 return template126 122- def get_template(self, name, parent=None):127+ def get_template(self, name, parent=None, globals=None):128 """Load a template."""129 if self.loader is None:130 raise TypeError('no loader for this environment specified')131 if parent is not None:132 name = self.join_path(name, parent)133+ globals = self.make_globals(globals)128- return self.loader.load(self, name)134+ return self.loader.load(self, name, globals)135 130- def from_string(self, source, filename='<string>'):136+ def from_string(self, source, filename='<string>', globals=None):137 """Load a template from a string."""138+ globals = self.make_globals(globals)132- return Template(self, self.compile(source, filename))139+ return Template(self, self.compile(source, filename), globals)140 141+ def make_globals(self, d):142+ """Return a dict for the globals."""143+ if d is None:144+ return self.globals145+ return dict(self.globals, **d)146 147+148 class Template(object):149 """Represents a template."""150 138- def __init__(self, environment, code):151+ def __init__(self, environment, code, globals):152 namespace = {'environment': environment}153 exec code in namespace154 self.environment = environment155 self.name = namespace['filename']156 self.root_render_func = namespace['root']157 self.blocks = namespace['blocks']158+ self.globals = globals159 160 def render(self, *args, **kwargs):147- return u''.join(self.stream(*args, **kwargs))161+ return u''.join(self.generate(*args, **kwargs))162 163 def stream(self, *args, **kwargs):150- gen = self.root_render_func(dict(*args, **kwargs))164+ return TemplateStream(self.generate(*args, **kwargs))165+166+ def generate(self, *args, **kwargs):167+ # assemble the context168+ context = self.globals.copy()169+ context.update(*args, **kwargs)170+171+ # if the environment is using the optimizer locals may never172+ # override globals as optimizations might have happened173+ # depending on values of certain globals. This assertion goes174+ # away if the python interpreter is started with -O175+ if __debug__ and self.environment.optimized:176+ overrides = set(context) & set(self.globals)177+ if overrides:178+ plural = len(overrides) != 1 and 's' or ''179+ raise AssertionError('the per template variable%s %s '180+ 'override%s global variable%s. '181+ 'With an enabled optimizer this '182+ 'will lead to unexpected results.' %183+ (plural, ', '.join(overrides), plural or ' a', plural))184+ gen = self.root_render_func(context)185 # skip the first item which is a reference to the stream186 gen.next()187 return genmodified:jinja2/loaders.py+3 added-3 removed
17 unmodified lines18 19 def get_source(self, environment, template):20 raise TemplateNotFound()21 22- def load(self, environment, template):22+ def load(self, environment, template, globals=None):23 source, filename = self.get_source(environment, template)24- code = environment.compile(source, filename)25- return Template(environment, code)24+ code = environment.compile(source, filename, globals=globals)25+ return Template(environment, code, globals or {})26 27 28 class FileSystemLoader(BaseLoader):29 30 unmodified linesmodified:jinja2/optimizer.py+2 added-1 removed
247 unmodified lines248 lineno=node.lineno,249 environment=self.environment)250 except nodes.Impossible:251 return node252+253 visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \254 visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \255 visit_Not = visit_Compare = visit_Subscript = visit_Call = \255- visit_Filter = visit_Test = fold256+ visit_Filter = visit_Test = visit_CondExpr = fold257 del fold