revamped jinja2 import system. the behavior is less confusing now, but it's not backwards compatible. I like it though ;)
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 6ce170c · Browse files · 8 files·+125 added−60 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+125 added−60 removed
- tests:+0 added−6 removed
- other:+125 added−54 removed
Provenance
- Commit
0611e49- Tree
4d66a27- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
6ce170c
8 files changed+125 added−60 removed
modified:jinja2/compiler.py+42 added-32 removed
208 unmodified lines209 self.generic_visit(node)210 self.identifiers.tests.add(node.name)211 212 def visit_Macro(self, node):213- """Macros set local."""213 self.identifiers.declared_locally.add(node.name)214 216- def visit_Include(self, node):217- """Some includes set local."""215+ def visit_Import(self, node):216 self.generic_visit(node)219- if node.target is not None:220- self.identifiers.declared_locally.add(node.target)217+ self.identifiers.declared_locally.add(node.target)218 219+ def visit_FromImport(self, node):220+ self.generic_visit(node)221+ self.identifiers.declared_locally.update(node.names)222+223 def visit_Assign(self, node):224 """Visit assignments in the correct order."""225 self.visit(node.node)226 self.visit(node.target)5 unmodified lines232 233 class CompilerExit(Exception):234 """Raised if the compiler encountered a situation where it just235 doesn't make sense to further process the code. Any block that235- raises such an exception is not further processed."""236+ raises such an exception is not further processed.237+ """238 239 240 class CodeGenerator(NodeVisitor):241 356 unmodified lines598 self.extends_so_far += 1599 600 def visit_Include(self, node, frame):601 """Handles includes."""600- # simpled include is include into a variable. This kind of601- # include works the same on every level, so we handle it first.602- if node.target is not None:603- self.writeline('l_%s = ' % node.target, node)604- if frame.toplevel:605- self.write('context[%r] = ' % node.target)606- self.write('environment.get_template(')607- self.visit(node.template, frame)608- self.write(', %r).include(context)' % self.name)609- return610-602 self.writeline('included_template = environment.get_template(', node)603 self.visit(node.template, frame)604 self.write(', %r)' % self.name)614- if frame.toplevel:615- self.writeline('included_context = included_template.new_context('616- 'context.get_root())')617- self.writeline('for event in included_template.root_render_func('618- 'included_context):')619- else:620- self.writeline('for event in included_template.root_render_func('621- 'included_template.new_context(context.get_root())):')605+ self.writeline('for event in included_template.root_render_func('606+ 'included_template.new_context(context.get_root())):')607 self.indent()608 if frame.buffer is None:609 self.writeline('yield event')610 else:611 self.writeline('%s.append(event)' % frame.buffer)612 self.outdent()613 629- # if we have a toplevel include the exported variables are copied630- # into the current context without exporting them. context.udpate631- # does *not* mark the variables as exported614+ def visit_Import(self, node, frame):615+ """Visit regular imports."""616+ self.writeline('l_%s = ' % node.target, node)617 if frame.toplevel:633- self.writeline('context.update(included_context.get_exported())')618+ self.write('context[%r] = ' % node.target)619+ self.write('environment.get_template(')620+ self.visit(node.template, frame)621+ self.write(', %r).include(context)' % self.name)622 623+ def visit_FromImport(self, node, frame):624+ """Visit named imports."""625+ self.newline(node)626+ self.write('included_template = environment.get_template(')627+ self.visit(node.template, frame)628+ self.write(', %r).include(context)' % self.name)629+ for name in node.names:630+ self.writeline('l_%s = getattr(included_template, '631+ '%r, missing)' % (name, name))632+ self.writeline('if l_%s is missing:' % name)633+ self.indent()634+ self.writeline('l_%s = environment.undefined(%r %% '635+ 'included_template.name)' %636+ (name, 'the template %r does not export '637+ 'the requested name ' + repr(name)))638+ self.outdent()639+ if frame.toplevel:640+ self.writeline('context[%r] = l_%s' % (name, name))641+642 def visit_For(self, node, frame):643 loop_frame = frame.inner()644 loop_frame.inspect(node.iter_child_nodes())645 extended_loop = bool(node.else_) or \382 unmodified lines1028 1029 def visit_Filter(self, node, frame, initial=None):1030 self.write('f_%s(' % node.name)1031 func = self.environment.filters.get(node.name)1032+ if func is None:1033+ raise TemplateAssertionError('no filter named %r' % node.name,1034+ node.lineno, self.filename)1035 if getattr(func, 'contextfilter', False):1036 self.write('context, ')1037 elif getattr(func, 'environmentfilter', False):1038 self.write('environment, ')7 unmodified lines1046 self.write(')')1047 1048 def visit_Test(self, node, frame):1049 self.write('t_%s(' % node.name)1040- func = self.environment.tests.get(node.name)1041- if getattr(func, 'contexttest', False):1042- self.write('context, ')1050+ if node.name not in self.environment.tests:1051+ raise TemplateAssertionError('no test named %r' % node.name,1052+ node.lineno, self.filename)1053 self.visit(node.node, frame)1054 self.signature(node, frame)1055 self.write(')')1056 29 unmodified linesmodified:jinja2/filters.py+2 added-1 removed
631 unmodified lines632 'abs': abs,633 'round': do_round,634 'sort': do_sort,635 'groupby': do_groupby,636- 'safe': Markup636+ 'safe': Markup,637+ 'xmlattr': do_xmlattr638 }modified:jinja2/lexer.py+2 added-1 removed
35 unmodified lines36 # set of used keywords37 keywords = set(['and', 'block', 'elif', 'else', 'endblock', 'print',38 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',39 'extends', 'filter', 'for', 'if', 'in', 'include',40- 'is', 'macro', 'not', 'or', 'raw', 'call', 'endcall'])40+ 'is', 'macro', 'not', 'or', 'raw', 'call', 'endcall',41+ 'from', 'import'])42 43 # bind operators to token types44 operators = {45 '+': 'add',388 unmodified linesmodified:jinja2/nodes.py+17 added
261 unmodified lines262 263 264 class Include(Stmt):265 """A node that represents the include tag."""266+ fields = ('template',)267+268+269+class Import(Stmt):270+ """A node that represents the import tag."""271 fields = ('template', 'target')272 273 274+class FromImport(Stmt):275+ """A node that represents the from import tag. It's important to not276+ pass unsafe names to the name attribute. The compiler translates the277+ attribute lookups directly into getattr calls and does *not* use the278+ subscribe callback of the interface. As exported variables may not279+ start with double underscores (which the parser asserts) this is not a280+ problem for regular Jinja code, but if this node is used in an extension281+ extra care must be taken.282+ """283+ fields = ('template', 'names')284+285+286 class Trans(Stmt):287 """A node for translatable sections."""288 fields = ('singular', 'plural', 'indicator', 'replacements')289 327 unmodified linesmodified:jinja2/optimizer.py+11 added
171 unmodified lines172 except nodes.Impossible:173 return node174 return result175 176+ def visit_Import(self, node, context):177+ rv = self.generic_visit(node, context)178+ context.undef(node.target)179+ return rv180+181+ def visit_FromImport(self, node, context):182+ rv = self.generic_visit(node, context)183+ for name in node.names:184+ context.undef(name)185+ return rv186+187 def fold(self, node, context):188 """Do constant folding."""189 node = self.generic_visit(node, context)190 try:11 unmodified linesmodified:jinja2/parser.py+44 added-18 removed
12 unmodified lines13 from jinja2.exceptions import TemplateSyntaxError14 15 16 _statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',17- 'macro', 'include'])17+ 'macro', 'include', 'from', 'import'])18 _compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])19 statement_end_tokens = set(['variable_end', 'block_end', 'in'])20 _tuple_edge_tokens = set(['rparen']) | statement_end_tokens21 122 unmodified lines144 return node145 146 def parse_include(self):147 node = nodes.Include(lineno=self.stream.expect('include').lineno)148- expr = self.parse_expression()149- if self.stream.current.type is 'assign':148+ node.template = self.parse_expression()149+ return node150+151+ def parse_import(self):152+ node = nodes.Import(lineno=self.stream.expect('import').lineno)153+ node.template = self.parse_expression()154+ self.stream.expect('name:as')155+ node.target = self.stream.expect('name').value156+ if not nodes.Name(node.target, 'store').can_assign():157+ raise TemplateSyntaxError('can\'t assign imported template '158+ 'to %r' % node.target, node.lineno,159+ self.filename)160+ return node161+162+ def parse_from(self):163+ node = nodes.FromImport(lineno=self.stream.expect('from').lineno)164+ node.template = self.parse_expression()165+ self.stream.expect('import')166+ node.names = []167+ while 1:168+ if node.names:169+ self.stream.expect('comma')170+ if self.stream.current.type is 'name':171+ target = nodes.Name(self.stream.current.value, 'store')172+ if not target.can_assign():173+ raise TemplateSyntaxError('can\'t import object named %r'174+ % target.name, target.lineno,175+ self.filename)176+ elif target.name.startswith('__'):177+ raise TemplateAssertionError('names starting with two '178+ 'underscores can not be '179+ 'imported', target.lineno,180+ self.filename)181+ node.names.append(target.name)182+ self.stream.next()183+ if self.stream.current.type is not 'comma':184+ break185+ else:186+ break187+ if self.stream.current.type is 'comma':188 self.stream.next()151- if not isinstance(expr, nodes.Name):152- raise TemplateSyntaxError('must assign imported template to '153- 'variable or current scope',154- expr.lineno, self.filename)155- if not expr.can_assign():156- raise TemplateSyntaxError('can\'t assign imported template '157- 'to %r' % expr, expr.lineno,158- self.filename)159- node.target = expr.name160- node.template = self.parse_expression()161- else:162- node.target = None163- node.template = expr189 return node190 191 def parse_signature(self, node):192 node.args = args = []399 unmodified lines592 if self.stream.current.type is 'name' and \593 self.stream.look().type is 'assign':594 key = self.stream.current.value595 self.stream.skip(2)596+ value = self.parse_expression()571- kwargs.append(nodes.Keyword(key, self.parse_expression(),572- lineno=key.lineno))597+ kwargs.append(nodes.Keyword(key, value,598+ lineno=value.lineno))599 else:600 ensure(not kwargs)601 args.append(self.parse_expression())602 90 unmodified linesmodified:jinja2/runtime.py+7 added-2 removed
12 unmodified lines13 from jinja2.exceptions import UndefinedError14 15 16 __all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',17- 'Macro', 'Markup']17+ 'Macro', 'Markup', 'missing']18 19 20+# special singleton representing missing values for the runtime21+missing = object()22+23+24 class TemplateContext(object):25 """Holds the variables of the local template or of the global one. It's26 not save to use this class outside of the compiled code. For example27 update and other methods will not work as they seem (they don't update44 unmodified lines72 self.vars.update(mapping)73 74 def get_exported(self):75 """Get a new dict with the exported variables."""72- return dict((k, self.vars[k]) for k in self.exported_vars)76+ return dict((k, self.vars[k]) for k in self.exported_vars77+ if not k.startswith('__'))78 79 def get_root(self):80 """Return a new dict with all the non local variables."""81 return dict(self.parent)264 unmodified linesmodified:tests/test_syntax.py-6 removed
12 unmodified lines13 CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''14 SLICING = '''{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}'''15 ATTR = '''{{ foo.bar }}|{{ foo['bar'] }}'''16 SUBSCRIPT = '''{{ foo[0] }}|{{ foo[-1] }}'''17-KEYATTR = '''{{ {'items': 'foo'}.items }}|{{ {}.items() }}'''17 TUPLE = '''{{ () }}|{{ (1,) }}|{{ (1, 2) }}'''18 MATH = '''{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}'''19 DIV = '''{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}'''20 UNARY = '''{{ +3 }}|{{ -3 }}'''41 unmodified lines62 tmpl = env.from_string(SUBSCRIPT)63 assert tmpl.render(foo=[0, 1, 2]) == '0|2'64 65 67-def test_keyattr(env):68- tmpl = env.from_string(KEYATTR)69- assert tmpl.render() == 'foo|[]'70-71-66 def test_tuple(env):67 tmpl = env.from_string(TUPLE)68 assert tmpl.render() == '()|(1,)|(1, 2)'69 93 unmodified lines