Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: transform x.await into await x
- Loading branch information
Showing
5 changed files
with
72 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import ast | ||
import tokenize | ||
from io import BytesIO | ||
|
||
AWAIT_REPLACEMENT_ATTRIBUTE = '__tgpy_await__' | ||
|
||
|
||
def tokenize_string(s: str) -> list[tokenize.TokenInfo]: | ||
return list(tokenize.tokenize(BytesIO(s.encode('utf-8')).readline)) | ||
|
||
|
||
def untokenize_to_string(tokens: list[tokenize.TokenInfo]) -> str: | ||
return tokenize.untokenize(tokens).decode('utf-8') | ||
|
||
|
||
def pre_transform(code: str) -> str: | ||
tokens = tokenize_string(code) | ||
for i, tok in enumerate(tokens): | ||
if i == 0: | ||
continue | ||
prev_tok = tokens[i - 1] | ||
if ( | ||
tok.type == tokenize.NAME | ||
and tok.string == 'await' | ||
and prev_tok.type == tokenize.OP | ||
and prev_tok.string == '.' | ||
): | ||
tokens[i] = tok._replace(string=AWAIT_REPLACEMENT_ATTRIBUTE) | ||
return untokenize_to_string(tokens) | ||
|
||
|
||
class AwaitTransformer(ast.NodeTransformer): | ||
def visit_Attribute(self, node: ast.Attribute): | ||
node = self.generic_visit(node) | ||
if node.attr == AWAIT_REPLACEMENT_ATTRIBUTE: | ||
return ast.Await(value=node.value) | ||
else: | ||
return node | ||
|
||
|
||
transformer = AwaitTransformer() | ||
|
||
__all__ = ['pre_transform', 'transformer'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters