summaryrefslogtreecommitdiff
path: root/check_checkers.py
blob: 90ccc434b24c51f2cf423e3726c76a8e90ce89db (plain)
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
#!/usr/bin/env python3
import html
import json
import os
import re
import shutil
from subprocess import PIPE, Popen, check_output
import tempfile
import time
from typing import Dict, List, NamedTuple, TextIO, Tuple, TypedDict

import mypy.api
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import PythonLexer
import tomli


Error = Tuple[str, int, str]
"""The filename, line number and the error message."""


class Checker:
    url: str

    def run(self, path: str, typeshed_path: str) -> List[Error]:
        """
        Type checks the given path with the given options.
        """
        raise NotImplementedError()

    def version(self) -> str:
        """Returns the version of the checker."""
        raise NotImplementedError()


class Mypy(Checker):
    url = 'https://github.com/python/mypy'

    # mypy cannot output JSON (https://github.com/python/mypy/issues/10816)
    # though there is a PR (https://github.com/python/mypy/pull/11396)
    # so we just use the regex from https://github.com/matangover/mypy-vscode/blob/48162f345c7f14b96f29976660100ae1dd49cc0a/src/mypy.ts
    _pattern = re.compile(
        r'^(?P<file>[^\n]+?):((?P<line>\d+):)?((?P<column>\d+):)? (?P<type>\w+): (?P<message>.*)$',
        re.MULTILINE,
    )

    @classmethod
    def run(cls, path: str, typeshed_path: str):
        cachedir = tempfile.mkdtemp(prefix='mypy-cache-')
        stdout, stderr, retcode = mypy.api.run(
            [
                # fmt: off
                '--cache-dir', cachedir,
                '--custom-typeshed-dir', typeshed_path,
                # fmt: on
                '--',
                path,
            ]
        )
        shutil.rmtree(cachedir)
        return [
            (m.group('file'), m.group('line'), m.group('message'))
            for m in cls._pattern.finditer(stdout)
        ]

    @staticmethod
    def version():
        return mypy.api.run(['--version'])[0].split()[1].strip()


class Pytype(Checker):
    url = 'https://github.com/google/pytype'

    # pytype supports CSV output only for pytype-single which however doesn't support multiple modules
    # (https://github.com/google/pytype/issues/92)
    _pattern = re.compile(
        r'^File "(?P<file>[^"]+?)", line (?P<line>\d+), in (?P<module>[^ ]+): (?P<message>.*) \[(?P<id>[^]]+)\]$',
        re.MULTILINE,
    )

    @classmethod
    def run(cls, path: str, typeshed_path: str):
        env = {'TYPESHED_HOME': typeshed_path, 'PATH': os.environ['PATH']}
        proc = Popen(
            ['pytype', '--', path],
            stdout=PIPE,
            stderr=PIPE,
            encoding='utf-8',
            env=env,
        )
        stdout, stderr = proc.communicate()
        return [
            (m.group('file'), m.group('line'), m.group('message'))
            for m in cls._pattern.finditer(stdout)
        ]

    @staticmethod
    def version():
        return check_output(['pytype', '--version'], encoding='utf-8').strip()


class Pyright(Checker):
    url = 'https://github.com/microsoft/pyright'

    @staticmethod
    def run(path: str, typeshed_path: str):
        proc = Popen(
            [
                'pyright',
                # fmt: off
                '--typeshed-path', typeshed_path,
                '--outputjson',
                # fmt: on
                # pyright does not support --
                path,
            ],
            stdout=PIPE,
            stderr=PIPE,
            encoding='utf-8',
        )
        stdout, stderr = proc.communicate()
        return [
            (d['file'], d['range']['start']['line'] + 1, d['message'])
            for d in json.loads(stdout)['generalDiagnostics']
        ]

    @staticmethod
    def version():
        return (
            check_output(['pyright', '--version'], encoding='utf-8').split()[1].strip()
        )


# We don't check pyre because it has a very slow startup time (5s) since it parses the whole typeshed.
# (see https://github.com/facebook/pyre-check/issues/592)


class Puzzle(TypedDict):
    checker_results: Dict[str, List[Error]]
    last_modified: int


def run_checkers(checkers: List[Checker], puzzle: str, typeshed_path: str):
    results = {}
    for checker in checkers:
        start = time.time()
        results[checker.__class__.__name__] = checker.run(puzzle, typeshed_path)
        duration = time.time() - start
        print(checker, time.time() - start)
    return results


def run(
    checkers: List[Checker],
    puzzles: List[str],
    default_typeshed: str,
    out: TextIO,
    cache: Dict[str, Puzzle],
    issues: Dict[str, Dict[str, str]],
):
    python_lexer = PythonLexer()
    html_formatter = HtmlFormatter(noclasses=True, linenos='table')
    out.write(
        "<meta charset=utf-8><title>Comparison of static type checkers for Python</title>"
    )
    out.write(
        '''<p>This page compares three static type checkers for Python.
    The <span class=unexpected>red</span> background indicates that the checker
    fails to detect a type error or reports a false positive.
    <a href=/>Back to start page</a>.</p>'''
    )

    out.write('<style>.unexpected {background: #ffd2d0}</style>')

    out.write('<table border=1>')
    out.write('<tr><th>Input')
    for checker in checkers:
        out.write('<th>')
        out.write('<a href="{}">'.format(html.escape(checker.url)))
        out.write(checker.__class__.__name__)
        out.write('</a>')
        out.write('<br>({})'.format(html.escape(checker.version())))
    out.write('</tr>')

    for puzzle in puzzles:
        print(puzzle)
        last_modified = int(os.stat(puzzle).st_mtime)
        if puzzle in cache and last_modified == cache[puzzle]['last_modified']:
            checker_results = cache[puzzle]['checker_results']
        else:
            checker_results = run_checkers(checkers, puzzle, default_typeshed)
            cache[puzzle] = {
                'last_modified': last_modified,
                'checker_results': checker_results,
            }

        out.write('<tr>')
        out.write('<td>')
        with open(puzzle) as f:
            code = f.read()
        out.write(highlight(code, python_lexer, html_formatter))
        error_ok = '# error' in code or '# maybe error' in code
        no_error_ok = '# error' not in code

        for checker in checkers:
            errors = checker_results[checker.__class__.__name__]
            expected = (errors and error_ok) or (not errors and no_error_ok)
            out.write('<td class="{}">'.format('ok' if expected else 'unexpected'))
            if errors:
                out.write('<ul>')
                for filename, line, message in errors:
                    out.write('<li>')
                    out.write(f'{line}: ' + html.escape(message).replace('\n', '<br>'))
                    out.write('</li>')
                out.write('</ul>')
            else:
                out.write('<center>no errors found')
            if not expected:
                checker_issues = issues.get(checker.__class__.__name__.lower(), {})
                issue = checker_issues.get(
                    os.path.splitext(os.path.basename(puzzle))[0].split(
                        '_', maxsplit=1
                    )[1]
                )
                if issue:
                    out.write('<br>(')
                    out.write(issue)
                    out.write(')')
    out.write('</table>')


if __name__ == '__main__':
    # TODO: git clone typeshed if missing
    typeshed = os.path.abspath('typeshed')  # pytype requries an absolute path

    try:
        with open('cache.json') as f:
            cache = json.load(f)
    except FileNotFoundError:
        cache = {}

    with open('issues.toml', 'rb') as f:
        issues = tomli.load(f)

    with open('dist/checkers.html', 'w') as f:
        run(
            [Mypy(), Pytype(), Pyright()],
            ['puzzles/' + f for f in sorted(os.listdir('puzzles'))],
            typeshed,
            f,
            cache,
            issues,
        )

    with open('cache.json', 'w') as f:
        json.dump(cache, f)