|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# |
| 3 | +# This source code is licensed under the MIT license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | +# |
| 6 | + |
| 7 | +from dataclasses import fields, is_dataclass, MISSING |
| 8 | + |
| 9 | +from libcst import matchers |
| 10 | +from libcst._nodes.base import CSTNode |
| 11 | + |
| 12 | + |
| 13 | +def node_to_matcher( |
| 14 | + node: CSTNode, *, match_syntactic_trivia: bool = False |
| 15 | +) -> matchers.BaseMatcherNode: |
| 16 | + """Convert a concrete node to a matcher.""" |
| 17 | + if not is_dataclass(node): |
| 18 | + raise ValueError(f"{node} is not a CSTNode") |
| 19 | + |
| 20 | + attrs = {} |
| 21 | + for field in fields(node): |
| 22 | + name = field.name |
| 23 | + child = getattr(node, name) |
| 24 | + if not match_syntactic_trivia and field.name.startswith("whitespace"): |
| 25 | + # Not all nodes have whitespace fields, some have multiple, but they all |
| 26 | + # start with whitespace* |
| 27 | + child = matchers.DoNotCare() |
| 28 | + elif field.default is not MISSING and child == field.default: |
| 29 | + child = matchers.DoNotCare() |
| 30 | + # pyre-ignore[29]: Union[MISSING_TYPE, ...] is not a function. |
| 31 | + elif field.default_factory is not MISSING and child == field.default_factory(): |
| 32 | + child = matchers.DoNotCare() |
| 33 | + elif isinstance(child, (list, tuple)): |
| 34 | + child = type(child)( |
| 35 | + node_to_matcher(item, match_syntactic_trivia=match_syntactic_trivia) |
| 36 | + for item in child |
| 37 | + ) |
| 38 | + elif hasattr(matchers, type(child).__name__): |
| 39 | + child = node_to_matcher( |
| 40 | + child, match_syntactic_trivia=match_syntactic_trivia |
| 41 | + ) |
| 42 | + attrs[name] = child |
| 43 | + |
| 44 | + matcher = getattr(matchers, type(node).__name__) |
| 45 | + return matcher(**attrs) |
0 commit comments