-
Notifications
You must be signed in to change notification settings - Fork 192
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[RemoveUnusedImports] Support string type annotations (#353)
* [RemoveUnusedImports] Support string type annotations This PR adds support for detecting imports being used by string type annotations, as well as imports suppressed by comments. It breaks up the existing visitor into multiple smaller, single-purpose visitors, and composes them together.
- Loading branch information
Showing
12 changed files
with
640 additions
and
61 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
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
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,51 @@ | ||
# Copyright (c) Facebook, Inc. and its affiliates. | ||
# | ||
# This source code is licensed under the MIT license found in the | ||
# LICENSE file in the root directory of this source tree. | ||
|
||
import re | ||
from typing import Dict, Pattern, Union | ||
|
||
import libcst as cst | ||
import libcst.matchers as m | ||
from libcst.codemod._context import CodemodContext | ||
from libcst.codemod._visitor import ContextAwareVisitor | ||
from libcst.metadata import PositionProvider | ||
|
||
|
||
class GatherCommentsVisitor(ContextAwareVisitor): | ||
""" | ||
Collects all comments matching a certain regex and their line numbers. | ||
This visitor is useful for capturing special-purpose comments, for example | ||
``noqa`` style lint suppression annotations. | ||
Standalone comments are assumed to affect the line following them, and | ||
inline ones are recorded with the line they are on. | ||
After visiting a CST, matching comments are collected in the ``comments`` | ||
attribute. | ||
""" | ||
|
||
METADATA_DEPENDENCIES = (PositionProvider,) | ||
|
||
def __init__(self, context: CodemodContext, comment_regex: str) -> None: | ||
super().__init__(context) | ||
|
||
#: Dictionary of comments found in the CST. Keys are line numbers, | ||
#: values are comment nodes. | ||
self.comments: Dict[int, cst.Comment] = {} | ||
|
||
self._comment_matcher: Pattern[str] = re.compile(comment_regex) | ||
|
||
@m.visit(m.EmptyLine(comment=m.DoesNotMatch(None))) | ||
@m.visit(m.TrailingWhitespace(comment=m.DoesNotMatch(None))) | ||
def visit_comment(self, node: Union[cst.EmptyLine, cst.TrailingWhitespace]) -> None: | ||
comment = node.comment | ||
assert comment is not None # hello, type checker | ||
if not self._comment_matcher.match(comment.value): | ||
return | ||
line = self.get_metadata(PositionProvider, comment).start.line | ||
if isinstance(node, cst.EmptyLine): | ||
# Standalone comments refer to the next line | ||
line += 1 | ||
self.comments[line] = comment |
81 changes: 81 additions & 0 deletions
81
libcst/codemod/visitors/_gather_string_annotation_names.py
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,81 @@ | ||
# Copyright (c) Facebook, Inc. and its affiliates. | ||
# | ||
# This source code is licensed under the MIT license found in the | ||
# LICENSE file in the root directory of this source tree. | ||
|
||
from typing import Set, Union, cast | ||
|
||
import libcst as cst | ||
import libcst.matchers as m | ||
from libcst.codemod._context import CodemodContext | ||
from libcst.codemod._visitor import ContextAwareVisitor | ||
from libcst.metadata import MetadataWrapper, QualifiedNameProvider | ||
|
||
|
||
FUNCS_CONSIDERED_AS_STRING_ANNOTATIONS = {"typing.TypeVar"} | ||
ANNOTATION_MATCHER: m.BaseMatcherNode = m.Annotation() | m.Call( | ||
metadata=m.MatchMetadataIfTrue( | ||
QualifiedNameProvider, | ||
lambda qualnames: any( | ||
qn.name in FUNCS_CONSIDERED_AS_STRING_ANNOTATIONS for qn in qualnames | ||
), | ||
) | ||
) | ||
|
||
|
||
class GatherNamesFromStringAnnotationsVisitor(ContextAwareVisitor): | ||
""" | ||
Collects all names from string literals used for typing purposes. | ||
This includes annotations like ``foo: "SomeType"``, and parameters to | ||
special functions related to typing (currently only `typing.TypeVar`). | ||
After visiting, a set of all found names will be available on the ``names`` | ||
attribute of this visitor. | ||
""" | ||
|
||
METADATA_DEPENDENCIES = (QualifiedNameProvider,) | ||
|
||
def __init__(self, context: CodemodContext) -> None: | ||
super().__init__(context) | ||
|
||
#: The set of names collected from string literals. | ||
self.names: Set[str] = set() | ||
|
||
@m.call_if_inside(ANNOTATION_MATCHER) | ||
@m.visit(m.ConcatenatedString()) | ||
def handle_any_string( | ||
self, node: Union[cst.SimpleString, cst.ConcatenatedString] | ||
) -> None: | ||
value = node.evaluated_value | ||
if value is None: | ||
return | ||
mod = cst.parse_module(value) | ||
extracted_nodes = m.extractall( | ||
mod, | ||
m.Name( | ||
value=m.SaveMatchedNode(m.DoNotCare(), "name"), | ||
metadata=m.MatchMetadataIfTrue( | ||
cst.metadata.ParentNodeProvider, | ||
lambda parent: not isinstance(parent, cst.Attribute), | ||
), | ||
) | ||
| m.SaveMatchedNode(m.Attribute(), "attribute"), | ||
metadata_resolver=MetadataWrapper(mod, unsafe_skip_copy=True), | ||
) | ||
names = { | ||
cast(str, values["name"]) for values in extracted_nodes if "name" in values | ||
} | { | ||
name | ||
for values in extracted_nodes | ||
if "attribute" in values | ||
for name, _ in cst.metadata.scope_provider._gen_dotted_names( | ||
cast(cst.Attribute, values["attribute"]) | ||
) | ||
} | ||
self.names.update(names) | ||
|
||
@m.call_if_inside(ANNOTATION_MATCHER) | ||
@m.call_if_not_inside(m.ConcatenatedString()) | ||
@m.visit(m.SimpleString()) | ||
def handle_simple_string(self, node: cst.SimpleString) -> None: | ||
self.handle_any_string(node) |
Oops, something went wrong.