This is called with the stream as returned by `tokenize` and wraps every token in a :class:`Token` and converts the value.
(
self,
stream: t.Iterable[t.Tuple[int, str, str]],
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
)
| 613 | return TokenStream(self.wrap(stream, name, filename), name, filename) |
| 614 | |
| 615 | def wrap( |
| 616 | self, |
| 617 | stream: t.Iterable[t.Tuple[int, str, str]], |
| 618 | name: t.Optional[str] = None, |
| 619 | filename: t.Optional[str] = None, |
| 620 | ) -> t.Iterator[Token]: |
| 621 | """This is called with the stream as returned by `tokenize` and wraps |
| 622 | every token in a :class:`Token` and converts the value. |
| 623 | """ |
| 624 | for lineno, token, value_str in stream: |
| 625 | if token in ignored_tokens: |
| 626 | continue |
| 627 | |
| 628 | value: t.Any = value_str |
| 629 | |
| 630 | if token == TOKEN_LINESTATEMENT_BEGIN: |
| 631 | token = TOKEN_BLOCK_BEGIN |
| 632 | elif token == TOKEN_LINESTATEMENT_END: |
| 633 | token = TOKEN_BLOCK_END |
| 634 | # we are not interested in those tokens in the parser |
| 635 | elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END): |
| 636 | continue |
| 637 | elif token == TOKEN_DATA: |
| 638 | value = self._normalize_newlines(value_str) |
| 639 | elif token == "keyword": |
| 640 | token = value_str |
| 641 | elif token == TOKEN_NAME: |
| 642 | value = value_str |
| 643 | |
| 644 | if not value.isidentifier(): |
| 645 | raise TemplateSyntaxError( |
| 646 | "Invalid character in identifier", lineno, name, filename |
| 647 | ) |
| 648 | elif token == TOKEN_STRING: |
| 649 | # try to unescape string |
| 650 | try: |
| 651 | value = ( |
| 652 | self._normalize_newlines(value_str[1:-1]) |
| 653 | .encode("ascii", "backslashreplace") |
| 654 | .decode("unicode-escape") |
| 655 | ) |
| 656 | except Exception as e: |
| 657 | msg = str(e).split(":")[-1].strip() |
| 658 | raise TemplateSyntaxError(msg, lineno, name, filename) from e |
| 659 | elif token == TOKEN_INTEGER: |
| 660 | value = int(value_str.replace("_", ""), 0) |
| 661 | elif token == TOKEN_FLOAT: |
| 662 | # remove all "_" first to support more Python versions |
| 663 | value = literal_eval(value_str.replace("_", "")) |
| 664 | elif token == TOKEN_OPERATOR: |
| 665 | token = operators[value_str] |
| 666 | |
| 667 | yield Token(lineno, token, value) |
| 668 | |
| 669 | def tokeniter( |
| 670 | self, |
no test coverage detected