Skip to content
Myr

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

5 files+121 added−75 removed

modified:jinja2/compiler.py+73 added-41 removed
256 unmodified lines
257 self.write('# line: %s' % node.lineno)258 self.new_lines = 1259 self._last_line = node.lineno260261 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 lines
271 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)286287 def pull_locals(self, frame, no_indent=False):288 if not no_indent:
6 unmodified lines
295 self.writeline('t_%s = environment.tests[%r]' % (name, name))296 if not no_indent:297 self.outdent()298299 def function_scoping(self, node, frame):300 func_frame = frame.inner()301 func_frame.inspect(node.iter_child_nodes(), hard_scope=True)302303 # 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)319320 # 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 )326327 func_frame.accesses_arguments = False328 func_frame.accesses_caller = False329 func_frame.arguments = args = ['l_' + x.name for x in node.args]330331 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_frame340341 # -- Visitors342343 def visit_Template(self, node, frame=None):344 assert frame is None, 'no root frame allowed'
190 unmodified lines
535 self.writeline('else:')536 self.blockvisit(node.else_, if_frame)537538 def visit_Macro(self, node, frame):492 macro_frame = frame.inner()493 macro_frame.inspect(node.iter_child_nodes(), hard_scope=True)494495 # 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)511512 # 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 )518519 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 lines
551 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 ))559560 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')575576 def visit_ExprStmt(self, node, frame):577 self.newline(node)578 self.visit(node, frame)579
221 unmodified lines
801 self.visit(node.node, frame)802 self.signature(node, frame)803 self.write(')')804773 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(')')810811 def visit_Keyword(self, node, frame):812 self.visit(node.key, frame)
2 unmodified lines
modified:jinja2/lexer.py+8 added-12 removed
31 unmodified lines
32 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')33integer_re = re.compile(r'\d+')34name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')35float_re = re.compile(r'\d+\.\d+')36eol_re = re.compile(r'(\s*$\s*)+(?m)')363738# set of used keywords39keywords = set(['and', 'block', 'elif', 'else', 'endblock', 'print',
298 unmodified lines
338 (c(r'\s*(\n|$)'), 'linestatement_end', '#pop')339 ] + tag_rules340341 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 lines
374 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)380381 def tokeniter(self, source, filename=None):
12 unmodified lines
394 source_length = len(source)395396 balancing_stack = []397401 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 continue405406 # 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 continue414415 # tuples support more options416 if isinstance(tokens, tuple):
27 unmodified lines
444 if data:445 yield lineno, token, data446 lineno += data.count('\n')447450 # 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 lines
468 (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')474475 # fetch new position into new variable so that we can check476 # if there is a internal parsing error which would result
42 unmodified lines
modified:jinja2/nodes.py+1 added-1 removed
220 unmodified lines
221222223class CallBlock(Stmt):224 """A node that represents am extended macro call."""225 fields = ('call', 'body')225 fields = ('call', 'args', 'defaults', 'body')226227228class Set(Stmt):229 """Allows defining own variables."""
324 unmodified lines
modified:jinja2/parser.py+23 added-17 removed
173 unmodified lines
174 node.template = expr175 self.end_statement()176 return node177178 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')196197 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)201202 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 lines
213 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 node220221 def parse_print(self):
446 unmodified lines
modified:jinja2/runtime.py+16 added-4 removed
191 unmodified lines
192193class Macro(object):194 """Wraps a macro."""195196 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 = caller203204 def __call__(self, *args, **kwargs):205 arg_count = len(self.arguments)206 if len(args) > arg_count:
11 unmodified lines
218 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)))230231 def __repr__(self):232 return '<%s %s>' % (233 self.__class__.__name__,234 self.name is None and 'anonymous' or repr(self.name)235 )236237238class Undefined(object):239 """The object for undefined values."""240241 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