File: graphviz.py

package info (click to toggle)
python-libcst 1.4.0-1.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,928 kB
  • sloc: python: 76,235; makefile: 10; sh: 2
file content (187 lines) | stat: -rw-r--r-- 5,524 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

from __future__ import annotations

import textwrap
from collections.abc import Sequence

from libcst import CSTNode
from libcst.helpers import filter_node_fields


_syntax_style = ', color="#777777", fillcolor="#eeeeee"'
_value_style = ', color="#3e99ed", fillcolor="#b8d9f8"'

node_style: dict[str, str] = {
    "__default__": "",
    "EmptyLine": _syntax_style,
    "IndentedBlock": _syntax_style,
    "SimpleStatementLine": _syntax_style,
    "SimpleWhitespace": _syntax_style,
    "TrailingWhitespace": _syntax_style,
    "Newline": _syntax_style,
    "Comma": _syntax_style,
    "LeftParen": _syntax_style,
    "RightParen": _syntax_style,
    "LeftSquareBracket": _syntax_style,
    "RightSquareBracket": _syntax_style,
    "LeftCurlyBrace": _syntax_style,
    "RightCurlyBrace": _syntax_style,
    "BaseSmallStatement": _syntax_style,
    "BaseCompoundStatement": _syntax_style,
    "SimpleStatementSuite": _syntax_style,
    "Colon": _syntax_style,
    "Dot": _syntax_style,
    "Semicolon": _syntax_style,
    "ParenthesizedWhitespace": _syntax_style,
    "BaseParenthesizableWhitespace": _syntax_style,
    "Comment": _syntax_style,
    "Name": _value_style,
    "Integer": _value_style,
    "Float": _value_style,
    "Imaginary": _value_style,
    "SimpleString": _value_style,
    "FormattedStringText": _value_style,
}
"""Graphviz style for specific CST nodes"""


def _create_node_graphviz(node: CSTNode) -> str:
    """Creates the graphviz representation of a CST node."""
    node_name = node.__class__.__qualname__

    if node_name in node_style:
        style = node_style[node_name]
    else:
        style = node_style["__default__"]

    # pyre-ignore[16]: the existence of node.value is checked before usage
    if hasattr(node, "value") and isinstance(node.value, str):
        line_break = r"\n"
        quote = '"'
        escaped_quote = r"\""
        value = f"{line_break}<{node.value.replace(quote, escaped_quote)}>"
        style = style + ', shape="box"'
    else:
        value = ""

    return f'{id(node)} [label="{node_name}{value}"{style}]'


def _node_repr_recursive(
    node: object,
    *,
    show_defaults: bool,
    show_syntax: bool,
    show_whitespace: bool,
) -> list[str]:
    """Creates the graphviz representation of a CST node,
    and of its child nodes."""
    if not isinstance(node, CSTNode):
        return []

    fields = filter_node_fields(
        node,
        show_defaults=show_defaults,
        show_syntax=show_syntax,
        show_whitespace=show_whitespace,
    )

    graphviz_lines: list[str] = [_create_node_graphviz(node)]

    for field in fields:
        value = getattr(node, field.name)
        if isinstance(value, CSTNode):
            # Display a single node
            graphviz_lines.append(f'{id(node)} -> {id(value)} [label="{field.name}"]')
            graphviz_lines.extend(
                _node_repr_recursive(
                    value,
                    show_defaults=show_defaults,
                    show_syntax=show_syntax,
                    show_whitespace=show_whitespace,
                )
            )
            continue

        if isinstance(value, Sequence):
            # Display a sequence of nodes
            for index, child in enumerate(value):
                if isinstance(child, CSTNode):
                    graphviz_lines.append(
                        rf'{id(node)} -> {id(child)} [label="{field.name}[{index}]"]'
                    )
                    graphviz_lines.extend(
                        _node_repr_recursive(
                            child,
                            show_defaults=show_defaults,
                            show_syntax=show_syntax,
                            show_whitespace=show_whitespace,
                        )
                    )

    return graphviz_lines


def dump_graphviz(
    node: object,
    *,
    show_defaults: bool = False,
    show_syntax: bool = False,
    show_whitespace: bool = False,
) -> str:
    """
    Returns a string representation (in graphviz .dot style) of a CST node,
    and its child nodes.

    Setting ``show_defaults`` to ``True`` will add fields regardless if their
    value is different from the default value.

    Setting ``show_whitespace`` will add whitespace fields and setting
    ``show_syntax`` will add syntax fields while respecting the value of
    ``show_defaults``.
    """

    graphviz_settings = textwrap.dedent(
        r"""
        layout=dot;
        rankdir=TB;
        splines=line;
        ranksep=0.5;
        nodesep=1.0;
        dpi=300;
        bgcolor=transparent;
        node [
            style=filled,
            color="#fb8d3f",
            fontcolor="#4b4f54",
            fillcolor="#fdd2b3",
            fontname="Source Code Pro Semibold",
            penwidth="2",
            group=main,
        ];
        edge [
            color="#999999",
            fontcolor="#4b4f54",
            fontname="Source Code Pro Semibold",
            fontsize=12,
            penwidth=2,
        ];
        """[
            1:
        ]
    )

    return "\n".join(
        ["digraph {", graphviz_settings]
        + _node_repr_recursive(
            node,
            show_defaults=show_defaults,
            show_syntax=show_syntax,
            show_whitespace=show_whitespace,
        )
        + ["}"]
    )