Skip to content
Myr

consistent use of token constants

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 81d526d · Browse files · 1 file+31 added−25 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+31 added−25 removed

  • other:+31 added−25 removed

1 file+31 added−25 removed

modified:jinja2/lexer.py+31 added-25 removed
180 unmodified lines
181182183def describe_token(token):184 """Returns a description of the token."""185 if token.type == 'name':185 if token.type == TOKEN_NAME:186 return token.value187 return _describe_token_type(token.type)188189190def describe_token_expr(expr):191 """Like `describe_token` but for token expressions."""192 if ':' in expr:193 type, value = expr.split(':', 1)194 if type == 'name':194 if type == TOKEN_NAME:195 return value196 else:197 type = expr198 return _describe_token_type(type)
9 unmodified lines
208def compile_rules(environment):209 """Compiles all the rules from the environment into a list of rules."""210 e = re.escape211 rules = [212 (len(environment.comment_start_string), 'comment',212 (len(environment.comment_start_string), TOKEN_COMMENT_BEGIN,213 e(environment.comment_start_string)),214 (len(environment.block_start_string), 'block',214 (len(environment.block_start_string), TOKEN_BLOCK_BEGIN,215 e(environment.block_start_string)),216 (len(environment.variable_start_string), 'variable',216 (len(environment.variable_start_string), TOKEN_VARIABLE_BEGIN,217 e(environment.variable_start_string))218 ]219220 if environment.line_statement_prefix is not None:221 rules.append((len(environment.line_statement_prefix), 'linestatement',221 rules.append((len(environment.line_statement_prefix), TOKEN_LINESTATEMENT_BEGIN,222 r'^[ \t\v]*' + e(environment.line_statement_prefix)))223 if environment.line_comment_prefix is not None:224 rules.append((len(environment.line_comment_prefix), 'linecomment',224 rules.append((len(environment.line_comment_prefix), TOKEN_LINECOMMENT_BEGIN,225 r'(?:^|(?<=\S))[^\S\r\n]*' +226 e(environment.line_comment_prefix)))227228 return [x[1:] for x in sorted(rules, reverse=True)]
98 unmodified lines
327 def __bool__(self):328 return bool(self._pushed) or self.current.type is not TOKEN_EOF329 __nonzero__ = __bool__ # py2330331 eos = property(lambda x: not x, doc="Are we at the end of the stream?")331 @property332 def eos(self):333 """Are we at the end of the stream?"""334 return not self335336 def push(self, token):337 """Push a token back to the stream."""338 self._pushed.append(token)
148 unmodified lines
487 e(environment.block_start_string),488 e(environment.block_end_string),489 e(environment.block_end_string)490 )] + [488 r'(?P<%s_begin>%s(\-|\+|))' % (n, r)491 r'(?P<%s>%s(\-|\+|))' % (n, r)492 for n, r in root_tag_rules493 ])), OptionalLStrip(TOKEN_DATA, '#bygroup'), '#bygroup'),494 # data495 (c('.+'), TOKEN_DATA, None)
59 unmodified lines
555 """556 for lineno, token, value in stream:557 if token in ignored_tokens:558 continue556 elif token == 'linestatement_begin':557 token = 'block_begin'558 elif token == 'linestatement_end':559 token = 'block_end'559 elif token == TOKEN_LINESTATEMENT_BEGIN:560 token = TOKEN_BLOCK_BEGIN561 elif token == TOKEN_LINESTATEMENT_END:562 token = TOKEN_BLOCK_END563 # we are not interested in those tokens in the parser561 elif token in ('raw_begin', 'raw_end'):564 elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END):565 continue563 elif token == 'data':566 elif token == TOKEN_DATA:567 value = self._normalize_newlines(value)568 elif token == 'keyword':569 token = value567 elif token == 'name':570 elif token == TOKEN_NAME:571 value = str(value)572 if check_ident and not value.isidentifier():573 raise TemplateSyntaxError(574 'Invalid character in identifier',575 lineno, name, filename)573 elif token == 'string':576 elif token == TOKEN_STRING:577 # try to unescape string578 try:579 value = self._normalize_newlines(value[1:-1]) \580 .encode('ascii', 'backslashreplace') \581 .decode('unicode-escape')582 except Exception as e:583 msg = str(e).split(':')[-1].strip()584 raise TemplateSyntaxError(msg, lineno, name, filename)582 elif token == 'integer':585 elif token == TOKEN_INTEGER:586 value = int(value.replace("_", ""))584 elif token == 'float':587 elif token == TOKEN_FLOAT:588 # remove all "_" first to support more Python versions589 value = literal_eval(value.replace("_", ""))587 elif token == 'operator':590 elif token == TOKEN_OPERATOR:591 token = operators[value]592 yield Token(lineno, token, value)593594 def tokeniter(self, source, name, filename=None, state=None):
30 unmodified lines
625 # we only match blocks and variables if braces / parentheses626 # are balanced. continue parsing with the lower rule which627 # is the operator rule. do this only if the end tags look628 # like operators626 if balancing_stack and \627 tokens in ('variable_end', 'block_end',628 'linestatement_end'):629 if (630 balancing_stack631 and tokens in (632 TOKEN_VARIABLE_END, TOKEN_BLOCK_END, TOKEN_LINESTATEMENT_END633 )634 ):635 continue636637 # tuples support more options638 if isinstance(tokens, tuple):
17 unmodified lines
656 strip_sign != "+"657 # lstrip is enabled.658 and lstrip_unless_re is not None659 # Not a variable expression.654 and not m.groupdict().get("variable_begin")660 and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)661 ):662 # The start of text between the last newline and the tag.663 l_pos = text.rfind('\n') + 1664
30 unmodified lines
695 # strings as token just are yielded as it.696 else:697 data = m.group()698 # update brace/parentheses balance693 if tokens == 'operator':699 if tokens == TOKEN_OPERATOR:700 if data == '{':701 balancing_stack.append('}')702 elif data == '(':703 balancing_stack.append(')')
63 unmodified lines