added support for new call statement
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 bf7c4ad · Browse files · 5 files·+121 added−75 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+121 added−75 removed
- other:+121 added−75 removed
Provenance
- Commit
7108207- Tree
36b8e37- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
bf7c4ad
5 files changed+121 added−75 removed
modified:jinja2/compiler.py+73 added-41 removed
256 unmodified lines257 self.write('# line: %s' % node.lineno)258 self.new_lines = 1259 self._last_line = node.lineno260 261- def signature(self, node, frame, have_comma=True):261+ def signature(self, node, frame, have_comma=True, extra_kwargs=None):262 have_comma = have_comma and [True] or []263 def touch_comma():264 if have_comma:265 self.write(', ')5 unmodified lines271 self.visit(arg, frame)272 for kwarg in node.kwargs:273 touch_comma()274 self.visit(kwarg, frame)275+ if extra_kwargs is not None:276+ touch_comma()277+ self.write(extra_kwargs)278 if node.dyn_args:279 touch_comma()280+ self.write('*')281 self.visit(node.dyn_args, frame)282 if node.dyn_kwargs:283 touch_comma()284+ self.write('**')285 self.visit(node.dyn_kwargs, frame)286 287 def pull_locals(self, frame, no_indent=False):288 if not no_indent:6 unmodified lines295 self.writeline('t_%s = environment.tests[%r]' % (name, name))296 if not no_indent:297 self.outdent()298 299+ def function_scoping(self, node, frame):300+ func_frame = frame.inner()301+ func_frame.inspect(node.iter_child_nodes(), hard_scope=True)302+303+ # variables that are undeclared (accessed before declaration) and304+ # declared locally *and* part of an outside scope raise a template305+ # assertion error. Reason: we can't generate reasonable code from306+ # it without aliasing all the variables. XXX: alias them ^^307+ overriden_closure_vars = (308+ func_frame.identifiers.undeclared &309+ func_frame.identifiers.declared &310+ (func_frame.identifiers.declared_locally |311+ func_frame.identifiers.declared_parameter)312+ )313+ if overriden_closure_vars:314+ vars = ', '.join(sorted(overriden_closure_vars))315+ raise TemplateAssertionError('It\'s not possible to set and '316+ 'access variables derived from '317+ 'an outer scope! (affects: %s' %318+ vars, node.lineno, self.filename)319+320+ # remove variables from a closure from the frame's undeclared321+ # identifiers.322+ func_frame.identifiers.undeclared -= (323+ func_frame.identifiers.undeclared &324+ func_frame.identifiers.declared325+ )326+327+ func_frame.accesses_arguments = False328+ func_frame.accesses_caller = False329+ func_frame.arguments = args = ['l_' + x.name for x in node.args]330+331+ if 'arguments' in func_frame.identifiers.undeclared:332+ func_frame.accesses_arguments = True333+ func_frame.identifiers.add_special('arguments')334+ args.append('l_arguments')335+ if 'caller' in func_frame.identifiers.undeclared:336+ func_frame.accesses_caller = True337+ func_frame.identifiers.add_special('caller')338+ args.append('l_caller')339+ return func_frame340+341 # -- Visitors342 343 def visit_Template(self, node, frame=None):344 assert frame is None, 'no root frame allowed'190 unmodified lines535 self.writeline('else:')536 self.blockvisit(node.else_, if_frame)537 538 def visit_Macro(self, node, frame):492- macro_frame = frame.inner()493- macro_frame.inspect(node.iter_child_nodes(), hard_scope=True)494-495- # variables that are undeclared (accessed before declaration) and496- # declared locally *and* part of an outside scope raise a template497- # assertion error. Reason: we can't generate reasonable code from498- # it without aliasing all the variables. XXX: alias them ^^499- overriden_closure_vars = (500- macro_frame.identifiers.undeclared &501- macro_frame.identifiers.declared &502- (macro_frame.identifiers.declared_locally |503- macro_frame.identifiers.declared_parameter)504- )505- if overriden_closure_vars:506- vars = ', '.join(sorted(overriden_closure_vars))507- raise TemplateAssertionError('It\'s not possible to set and '508- 'access variables derived from '509- 'an outer scope! (affects: %s' %510- vars, node.lineno, self.filename)511-512- # remove variables from a closure from the frame's undeclared513- # identifiers.514- macro_frame.identifiers.undeclared -= (515- macro_frame.identifiers.undeclared &516- macro_frame.identifiers.declared517- )518-519- args = ['l_' + x.name for x in node.args]520- if 'arguments' in macro_frame.identifiers.undeclared:521- accesses_arguments = True522- args.append('l_arguments')523- else:524- accesses_arguments = False539+ macro_frame = self.function_scoping(node, frame)540+ args = macro_frame.arguments541 self.writeline('def macro(%s):' % ', '.join(args), node)526- self.indent()527- self.writeline('if 0: yield None')528- self.outdent()542 self.pull_locals(macro_frame)530- self.blockvisit(node.body, macro_frame)543+ self.blockvisit(node.body, macro_frame, True)544 self.newline()545 if frame.toplevel:546 self.write('context[%r] = ' % node.name)547 arg_tuple = ', '.join(repr(x.name) for x in node.args)3 unmodified lines551 arg_tuple))552 for arg in node.defaults:553 self.visit(arg)554 self.write(', ')542- self.write('), %r)' % accesses_arguments)555+ self.write('), %r, %r)' % (556+ macro_frame.accesses_arguments,557+ macro_frame.accesses_caller558+ ))559 560+ def visit_CallBlock(self, node, frame):561+ call_frame = self.function_scoping(node, frame)562+ args = call_frame.arguments563+ self.writeline('def call(%s):' % ', '.join(args), node)564+ self.blockvisit(node.body, call_frame, node)565+ arg_tuple = ', '.join(repr(x.name) for x in node.args)566+ if len(node.args) == 1:567+ arg_tuple += ','568+ self.writeline('caller = Macro(call, None, (%s), (' % arg_tuple)569+ for arg in node.defaults:570+ self.visit(arg)571+ self.write(', ')572+ self.write('), %r, False)' % call_frame.accesses_arguments)573+ self.writeline('yield ', node)574+ self.visit_Call(node.call, call_frame, extra_kwargs='caller=caller')575+576 def visit_ExprStmt(self, node, frame):577 self.newline(node)578 self.visit(node, frame)579 221 unmodified lines801 self.visit(node.node, frame)802 self.signature(node, frame)803 self.write(')')804 773- def visit_Call(self, node, frame):805+ def visit_Call(self, node, frame, extra_kwargs=None):806 self.visit(node.node, frame)807 self.write('(')776- self.signature(node, frame, False)808+ self.signature(node, frame, False, extra_kwargs)809 self.write(')')810 811 def visit_Keyword(self, node, frame):812 self.visit(node.key, frame)2 unmodified linesmodified:jinja2/lexer.py+8 added-12 removed
31 unmodified lines32 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')33 integer_re = re.compile(r'\d+')34 name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')35 float_re = re.compile(r'\d+\.\d+')36-eol_re = re.compile(r'(\s*$\s*)+(?m)')36 37 38 # set of used keywords39 keywords = set(['and', 'block', 'elif', 'else', 'endblock', 'print',298 unmodified lines338 (c(r'\s*(\n|$)'), 'linestatement_end', '#pop')339 ] + tag_rules340 341 def tokenize(self, source, filename=None):343- """344- Works like `tokeniter` but returns a tokenstream of tokens and not a345- generator or token tuples. Additionally all token values are already342+ """Works like `tokeniter` but returns a tokenstream of tokens and not343+ a generator or token tuples. Additionally all token values are already344 converted into types and postprocessed. For example keywords are345 already keyword tokens, not named tokens, comments are removed,346 integers and floats converted, strings unescaped etc.347 """26 unmodified lines374 elif token == 'float':375 value = float(value)376 elif token == 'operator':377 token = operators[value]380- value = ''378 yield Token(lineno, token, value)379 return TokenStream(generate(), filename)380 381 def tokeniter(self, source, filename=None):12 unmodified lines394 source_length = len(source)395 396 balancing_stack = []397 401- while True:398+ while 1:399 # tokenizer loop400 for regex, tokens, new_state in statetokens:401 m = regex.match(source, pos)402 # if no match we try again with the next rule406- if not m:403+ if m is None:404 continue405 406 # we only match blocks and variables if brances / parentheses407 # are balanced. continue parsing with the lower rule which408 # is the operator rule. do this only if the end tags look409 # like operators410 if balancing_stack and \414- tokens in ('variable_end', 'block_end'):411+ tokens in ('variable_end', 'block_end',412+ 'linestatement_end'):413 continue414 415 # tuples support more options416 if isinstance(tokens, tuple):27 unmodified lines444 if data:445 yield lineno, token, data446 lineno += data.count('\n')447 450- # strings as token just are yielded as it, but just451- # if the data is not empty448+ # strings as token just are yielded as it.449 else:450 data = m.group()451 # update brace/parentheses balance452 if tokens == 'operator':15 unmodified lines468 (data, expected_op),469 lineno, filename)470 # yield items471 if tokens is not None:475- if data:476- yield lineno, tokens, data472+ yield lineno, tokens, data473 lineno += data.count('\n')474 475 # fetch new position into new variable so that we can check476 # if there is a internal parsing error which would result42 unmodified linesmodified:jinja2/nodes.py+1 added-1 removed
220 unmodified lines221 222 223 class CallBlock(Stmt):224 """A node that represents am extended macro call."""225- fields = ('call', 'body')225+ fields = ('call', 'args', 'defaults', 'body')226 227 228 class Set(Stmt):229 """Allows defining own variables."""324 unmodified linesmodified:jinja2/parser.py+23 added-17 removed
173 unmodified lines174 node.template = expr175 self.end_statement()176 return node177 178+ def parse_signature(self, node):179+ node.args = args = []180+ node.defaults = defaults = []181+ self.stream.expect('lparen')182+ while self.stream.current.type is not 'rparen':183+ if args:184+ self.stream.expect('comma')185+ token = self.stream.expect('name')186+ arg = nodes.Name(token.value, 'param', lineno=token.lineno)187+ if not arg.can_assign():188+ raise TemplateSyntaxError("can't assign to '%s'" %189+ arg.name, arg.lineno,190+ self.filename)191+ if self.stream.current.type is 'assign':192+ self.stream.next()193+ defaults.append(self.parse_expression())194+ args.append(arg)195+ self.stream.expect('rparen')196+197 def parse_call_block(self):198 node = nodes.CallBlock(lineno=self.stream.expect('call').lineno)199+ if self.stream.current.type is 'lparen':200+ self.parse_signature(node)201+202 node.call = self.parse_expression()203 if not isinstance(node.call, nodes.Call):204 raise TemplateSyntaxError('expected call', node.lineno,205 self.filename)7 unmodified lines213 if not nodes.Name(node.name, 'store').can_assign():214 raise TemplateSyntaxError('can\'t assign macro to %r' %215 node.target, node.lineno,216 self.filename)195- self.stream.expect('lparen')196- node.args = args = []197- node.defaults = defaults = []198- while self.stream.current.type is not 'rparen':199- if args:200- self.stream.expect('comma')201- token = self.stream.expect('name')202- arg = nodes.Name(token.value, 'param', lineno=token.lineno)203- if not arg.can_assign():204- raise TemplateSyntaxError("can't assign to '%s'" %205- arg.name, arg.lineno,206- self.filename)207- if self.stream.current.type is 'assign':208- self.stream.next()209- defaults.append(self.parse_expression())210- args.append(arg)211- self.stream.expect('rparen')217+ self.parse_signature(node)218 node.body = self.parse_statements(('endmacro',), drop_needle=True)219 return node220 221 def parse_print(self):446 unmodified linesmodified:jinja2/runtime.py+16 added-4 removed
191 unmodified lines192 193 class Macro(object):194 """Wraps a macro."""195 196- def __init__(self, func, name, arguments, defaults, catch_all):197- self.func = func196+ def __init__(self, func, name, arguments, defaults, catch_all, caller):197+ self._func = func198 self.name = name199 self.arguments = arguments200 self.defaults = defaults201 self.catch_all = catch_all202+ self.caller = caller203 204 def __call__(self, *args, **kwargs):205 arg_count = len(self.arguments)206 if len(args) > arg_count:11 unmodified lines218 value = self.defaults[idx - arg_count]219 except IndexError:220 value = Undefined(name)221 arguments['l_' + name] = value222+ if self.caller:223+ caller = kwargs.pop('caller', None)224+ if caller is None:225+ caller = Undefined('caller')226+ arguments['l_caller'] = caller227 if self.catch_all:228 arguments['l_arguments'] = kwargs223- return TemplateData(u''.join(self.func(**arguments)))229+ return TemplateData(u''.join(self._func(**arguments)))230 231+ def __repr__(self):232+ return '<%s %s>' % (233+ self.__class__.__name__,234+ self.name is None and 'anonymous' or repr(self.name)235+ )236 237+238 class Undefined(object):239 """The object for undefined values."""240 241 def __init__(self, name=None, attr=None):242 if attr is None:231- self._undefined_hint = '%r is undefined' % attr243+ self._undefined_hint = '%r is undefined' % name244 elif name is None:245 self._undefined_hint = 'attribute %r is undefined' % name246 else:247 self._undefined_hint = 'attribute %r of %r is undefined' \21 unmodified lines