File: common.py

package info (click to toggle)
python-refurb 1.27.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,700 kB
  • sloc: python: 9,468; makefile: 40; sh: 6
file content (343 lines) | stat: -rw-r--r-- 9,790 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
from collections.abc import Callable
from itertools import chain, combinations, starmap

from mypy.nodes import (
    ArgKind,
    Block,
    BytesExpr,
    CallExpr,
    ComparisonExpr,
    DictExpr,
    DictionaryComprehension,
    Expression,
    ForStmt,
    GeneratorExpr,
    IndexExpr,
    IntExpr,
    LambdaExpr,
    ListExpr,
    MemberExpr,
    MypyFile,
    NameExpr,
    Node,
    OpExpr,
    ReturnStmt,
    SetExpr,
    SliceExpr,
    StarExpr,
    Statement,
    TupleExpr,
    UnaryExpr,
)

from refurb.error import Error
from refurb.visitor import TraverserVisitor


def extract_binary_oper(oper: str, node: OpExpr) -> tuple[Expression, Expression] | None:
    match node:
        case OpExpr(
            op=op,
            left=lhs,
            right=rhs,
        ) if op == oper:
            match rhs:
                case OpExpr(op=op, left=rhs) if op == oper:
                    return lhs, rhs

                case OpExpr():
                    return None

                case Expression():
                    return lhs, rhs

    return None


def check_block_like(
    func: Callable[[list[Statement], list[Error]], None],
    node: Block | MypyFile,
    errors: list[Error],
) -> None:
    match node:
        case Block():
            func(node.body, errors)

        case MypyFile():
            func(node.defs, errors)


def check_for_loop_like(
    func: Callable[[Node, Node, list[Node], list[Error]], None],
    node: ForStmt | GeneratorExpr | DictionaryComprehension,
    errors: list[Error],
) -> None:
    match node:
        case ForStmt(index=index, expr=expr):
            func(index, expr, [node.body], errors)

        case GeneratorExpr(
            indices=[index],
            sequences=[expr],
            condlists=condlists,
        ):
            func(
                index,
                expr,
                list(chain([node.left_expr], *condlists)),
                errors,
            )

        case DictionaryComprehension(
            indices=[index],
            sequences=[expr],
            condlists=condlists,
        ):
            func(
                index,
                expr,
                list(chain([node.key, node.value], *condlists)),
                errors,
            )


def unmangle_name(name: str | None) -> str:
    return (name or "").replace("'", "")


def is_equivalent(lhs: Node | None, rhs: Node | None) -> bool:
    match (lhs, rhs):
        case None, None:
            return True

        case NameExpr() as lhs, NameExpr() as rhs:
            return unmangle_name(lhs.fullname) == unmangle_name(rhs.fullname)

        case MemberExpr() as lhs, MemberExpr() as rhs:
            return (
                lhs.name == rhs.name
                and unmangle_name(lhs.fullname) == unmangle_name(rhs.fullname)
                and is_equivalent(lhs.expr, rhs.expr)
            )

        case IndexExpr() as lhs, IndexExpr() as rhs:
            return is_equivalent(lhs.base, rhs.base) and is_equivalent(lhs.index, rhs.index)

        case CallExpr() as lhs, CallExpr() as rhs:
            return (
                is_equivalent(lhs.callee, rhs.callee)
                and all(starmap(is_equivalent, zip(lhs.args, rhs.args)))
                and lhs.arg_kinds == rhs.arg_kinds
                and lhs.arg_names == rhs.arg_names
            )

        case (
            (ListExpr() as lhs, ListExpr() as rhs)
            | (TupleExpr() as lhs, TupleExpr() as rhs)
            | (SetExpr() as lhs, SetExpr() as rhs)
        ):
            return len(lhs.items) == len(rhs.items) and all(  # type: ignore
                starmap(is_equivalent, zip(lhs.items, rhs.items))  # type: ignore
            )

        case DictExpr() as lhs, DictExpr() as rhs:
            return len(lhs.items) == len(rhs.items) and all(
                is_equivalent(lhs_item[0], rhs_item[0]) and is_equivalent(lhs_item[1], rhs_item[1])
                for lhs_item, rhs_item in zip(lhs.items, rhs.items)
            )

        case StarExpr() as lhs, StarExpr() as rhs:
            return is_equivalent(lhs.expr, rhs.expr)

        case UnaryExpr() as lhs, UnaryExpr() as rhs:
            return lhs.op == rhs.op and is_equivalent(lhs.expr, rhs.expr)

        case OpExpr() as lhs, OpExpr() as rhs:
            return (
                lhs.op == rhs.op
                and is_equivalent(lhs.left, rhs.left)
                and is_equivalent(lhs.right, rhs.right)
            )

        case ComparisonExpr() as lhs, ComparisonExpr() as rhs:
            return lhs.operators == rhs.operators and all(
                starmap(is_equivalent, zip(lhs.operands, rhs.operands))
            )

        case SliceExpr() as lhs, SliceExpr() as rhs:
            return (
                is_equivalent(lhs.begin_index, rhs.begin_index)
                and is_equivalent(lhs.end_index, rhs.end_index)
                and is_equivalent(lhs.stride, rhs.stride)
            )

    return str(lhs) == str(rhs)


def get_common_expr_positions(*exprs: Expression) -> tuple[int, int] | None:
    for lhs, rhs in combinations(exprs, 2):
        if is_equivalent(lhs, rhs):
            return exprs.index(lhs), exprs.index(rhs)

    return None


def get_common_expr_in_comparison_chain(
    node: OpExpr, oper: str, cmp_oper: str = "=="
) -> tuple[Expression, tuple[int, int]] | None:
    """
    This function finds the first expression shared between 2 comparison
    expressions in the binary operator `oper`.

    For example, an OpExpr that looks like the following:

    1 == 2 or 3 == 1

    Will return a tuple containing the first common expression (`IntExpr(1)` in
    this case), and the indices of the common expressions as they appear in the
    source (`0` and `3` in this case). The indices are to be used for display
    purposes by the caller.

    If the binary operator is not composed of 2 comparison operators, or if
    there are no common expressions, `None` is returned.
    """

    match extract_binary_oper(oper, node):
        case (
            ComparisonExpr(operators=[lhs_oper], operands=[a, b]),
            ComparisonExpr(operators=[rhs_oper], operands=[c, d]),
        ) if (
            lhs_oper == rhs_oper == cmp_oper and (indices := get_common_expr_positions(a, b, c, d))
        ):
            return a, indices

    return None  # pragma: no cover


class ReadCountVisitor(TraverserVisitor):
    name: NameExpr
    read_count: int

    def __init__(self, name: NameExpr) -> None:
        self.name = name
        self.read_count = 0

    def visit_name_expr(self, node: NameExpr) -> None:
        if node.fullname == self.name.fullname:
            self.read_count += 1

    @property
    def was_read(self) -> int:
        return self.read_count > 0


def is_name_unused_in_contexts(name: NameExpr, contexts: list[Node]) -> bool:
    for ctx in contexts:
        visitor = ReadCountVisitor(name)
        visitor.accept(ctx)

        if visitor.was_read:
            return False

    return True


def normalize_os_path(module: str | None) -> str:
    """
    Mypy turns "os.path" module names into their respective platform, such
    as "ntpath" for windows, "posixpath" if they are POSIX only, or
    "genericpath" if they apply to both (I assume). To make life easier
    for us though, we turn those module names into their original form.
    """

    # Used for compatibility with older versions of Mypy.
    if not module:
        return ""

    segments = module.split(".")

    if segments[0].startswith(("genericpath", "ntpath", "posixpath")):
        return ".".join(["os", "path"] + segments[1:])

    return module


def is_type_none_call(node: Expression) -> bool:
    match node:
        case CallExpr(
            callee=NameExpr(fullname="builtins.type"),
            args=[NameExpr(fullname="builtins.None")],
        ):
            return True

    return False


def stringify(node: Node) -> str:
    try:
        return _stringify(node)

    except ValueError:  # pragma: no cover
        return "x"


def _stringify(node: Node) -> str:
    match node:
        case MemberExpr(expr=expr, name=name):
            return f"{_stringify(expr)}.{name}"

        case NameExpr(name=name):
            return unmangle_name(name)

        case BytesExpr(value=value):
            # TODO: use same formatting as source line
            return repr(value.encode())

        case IntExpr(value=value):
            # TODO: use same formatting as source line
            return str(value)

        case CallExpr():
            name = _stringify(node.callee)

            args = ", ".join(_stringify(arg) for arg in node.args)

            return f"{name}({args})"

        case OpExpr(left=left, op=op, right=right):
            return f"{_stringify(left)} {op} {_stringify(right)}"

        case ComparisonExpr():
            parts: list[str] = []

            for op, operand in zip(node.operators, node.operands):
                parts.extend((_stringify(operand), op))

            parts.append(_stringify(node.operands[-1]))

            return " ".join(parts)

        case UnaryExpr(op=op, expr=expr):
            return f"{op} {_stringify(expr)}"

        case LambdaExpr(
            arg_names=arg_names,
            arg_kinds=arg_kinds,
            body=Block(body=[ReturnStmt(expr=Expression() as expr)]),
        ) if (all(kind == ArgKind.ARG_POS for kind in arg_kinds) and all(arg_names)):
            if arg_names:
                args = " "
                args += ", ".join(arg_names)  # type: ignore
            else:
                args = ""

            body = _stringify(expr)

            return f"lambda{args}: {body}"

        case ListExpr(items=items):
            inner = ", ".join(stringify(x) for x in items)

            return f"[{inner}]"

    raise ValueError