File: __init__.py

package info (click to toggle)
firefox 149.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,767,760 kB
  • sloc: cpp: 7,416,064; javascript: 6,752,859; ansic: 3,774,850; python: 1,250,473; xml: 641,578; asm: 439,191; java: 186,617; sh: 56,634; makefile: 18,856; objc: 13,092; perl: 12,763; pascal: 5,960; yacc: 4,583; cs: 3,846; lex: 1,720; ruby: 1,002; php: 436; lisp: 258; awk: 105; sql: 66; sed: 53; csh: 10; exp: 6
file content (188 lines) | stat: -rw-r--r-- 5,820 bytes parent folder | download | duplicates (2)
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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import difflib
import os
import re

import yaml
from mozlint import result
from mozlint.pathutils import expand_exclusions

from .std import api as std_api
from .std import capi as std_capi

here = os.path.dirname(__file__)
with open(os.path.join(here, "..", "..", "..", "mfbt", "api.yml")) as fd:
    description = yaml.safe_load(fd)


def generate_diff(path, raw_content, line_to_delete):
    prev_content = raw_content.split("\n")
    new_content = [
        raw_line
        for lineno, raw_line in enumerate(prev_content, start=1)
        if lineno != line_to_delete
    ]
    diff = "\n".join(
        difflib.unified_diff(prev_content, new_content, fromfile=path, tofile=path)
    )
    return diff


def fix_includes(path, raw_content, line_to_delete):
    prev_content = raw_content.split("\n")
    new_content = [
        raw_line
        for lineno, raw_line in enumerate(prev_content, start=1)
        if lineno != line_to_delete
    ]
    with open(path, "w") as outfd:
        outfd.write("\n".join(new_content))


symbol_pattern = r"\b{}\b"
literal_pattern = r'[0-9."\']{}\b'

categories_pattern = {
    "variables": symbol_pattern,
    "functions": symbol_pattern,
    "macros": symbol_pattern,
    "types": symbol_pattern,
    "literals": literal_pattern,
}


def lint_mfbt_headers(results, path, raw_content, config, fix):
    supported_keys = "variables", "functions", "macros", "types", "literals"

    for header, categories in description.items():
        assert set(categories.keys()).issubset(supported_keys)

        if path.endswith(f"mfbt/{header}") or path.endswith(f"mfbt/{header[:-1]}.cpp"):
            continue

        headerline = rf'#\s*include "mozilla/{header}"'
        if not (match := re.search(headerline, raw_content)):
            continue

        content = raw_content.replace(f'"mozilla/{header}"', "")

        for category, pattern in categories_pattern.items():
            identifiers = categories.get(category, [])
            if any(
                re.search(pattern.format(identifier), content)
                for identifier in identifiers
            ):
                break
        else:
            msg = f"{path} includes {header} but does not reference any of its API"
            lineno = 1 + raw_content.count("\n", 0, match.start())

            if fix:
                fix_includes(path, raw_content, lineno)
                results["fixed"] += 1
            else:
                diff = generate_diff(path, raw_content, lineno)

                results["results"].append(
                    result.from_config(
                        config,
                        path=path,
                        message=msg,
                        level="error",
                        lineno=lineno,
                        diff=diff,
                    )
                )


def lint_std_headers(results, path, raw_content, config, fix):
    if re.search(r"using\s+namespace\s+std", raw_content):
        return

    symbol_pattern = r"\bstd::{}\b"

    for header, symbols in std_api.items():
        headerline = rf"#\s*include <{header}>"
        if not (match := re.search(headerline, raw_content)):
            continue
        if re.search(
            "|".join(symbol_pattern.format(symbol) for symbol in symbols), raw_content
        ):
            continue

        msg = f"{path} includes <{header}> but does not reference any of its API"
        lineno = 1 + raw_content.count("\n", 0, match.start())

        if fix:
            fix_includes(path, raw_content, lineno)
            results["fixed"] += 1
        else:
            diff = generate_diff(path, raw_content, lineno)

            results["results"].append(
                result.from_config(
                    config,
                    path=path,
                    message=msg,
                    level="error",
                    lineno=lineno,
                    diff=diff,
                )
            )


def lint_cstd_headers(results, path, raw_content, config, fix):
    symbol_pattern = r"\b((std)?::)?{}\b"

    for header, symbols in std_capi.items():
        headerline = rf"#\s*include <({header}|c{header[:-2]})>"
        if not (match := re.search(headerline, raw_content)):
            continue
        if re.search(
            "|".join(symbol_pattern.format(symbol) for symbol in symbols), raw_content
        ):
            continue

        msg = (
            f"{path} includes <{match.group(1)}> but does not reference any of its API"
        )
        lineno = 1 + raw_content.count("\n", 0, match.start())

        if fix:
            fix_includes(path, raw_content, lineno)
            results["fixed"] += 1
        else:
            diff = generate_diff(path, raw_content, lineno)

            results["results"].append(
                result.from_config(
                    config,
                    path=path,
                    message=msg,
                    level="error",
                    lineno=lineno,
                    diff=diff,
                )
            )


def lint(paths, config, **lintargs):
    results = {"results": [], "fixed": 0}
    paths = list(expand_exclusions(paths, config, lintargs["root"]))
    fix = lintargs.get("fix")

    for path in paths:
        try:
            with open(path) as fd:
                raw_content = fd.read()
        except UnicodeDecodeError:
            continue

        lint_mfbt_headers(results, path, raw_content, config, fix)
        lint_std_headers(results, path, raw_content, config, fix)
        lint_cstd_headers(results, path, raw_content, config, fix)

    return results