| 1 |
# vim: set ts=8 sts=4 et sw=4 tw=99: |
| 2 |
# This Source Code Form is subject to the terms of the Mozilla Public |
| 3 |
# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 4 |
# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 |
|
| 6 |
# ---------------------------------------------------------------------------- |
| 7 |
# This script checks various aspects of SpiderMonkey code style. The current checks are as |
| 8 |
# follows. |
| 9 |
# |
| 10 |
# We check the following things in headers. |
| 11 |
# |
| 12 |
# - No cyclic dependencies. |
| 13 |
# |
| 14 |
# - No normal header should #include a inlines.h/-inl.h file. |
| 15 |
# |
| 16 |
# - #ifndef wrappers should have the right form. (XXX: not yet implemented) |
| 17 |
# - Every header file should have one. |
| 18 |
# - The guard name used should be appropriate for the filename. |
| 19 |
# |
| 20 |
# We check the following things in all files. |
| 21 |
# |
| 22 |
# - #includes should have full paths, e.g. "jit/Ion.h", not "Ion.h". |
| 23 |
# |
| 24 |
# - #includes should use the appropriate form for system headers (<...>) and |
| 25 |
# local headers ("..."). |
| 26 |
# |
| 27 |
# - #includes should be ordered correctly. |
| 28 |
# - Each one should be in the correct section. |
| 29 |
# - Alphabetical order should be used within sections. |
| 30 |
# - Sections should be in the right order. |
| 31 |
# Note that the presence of #if/#endif blocks complicates things, to the |
| 32 |
# point that it's not always clear where a conditionally-compiled #include |
| 33 |
# statement should go, even to a human. Therefore, we check the #include |
| 34 |
# statements within each #if/#endif block (including nested ones) in |
| 35 |
# isolation, but don't try to do any order checking between such blocks. |
| 36 |
# ---------------------------------------------------------------------------- |
| 37 |
|
| 38 |
import difflib |
| 39 |
import os |
| 40 |
import re |
| 41 |
import sys |
| 42 |
|
| 43 |
# We don't bother checking files in these directories, because they're (a) auxiliary or (b) |
| 44 |
# imported code that doesn't follow our coding style. |
| 45 |
ignored_js_src_dirs = [ |
| 46 |
"js/src/config/", # auxiliary stuff |
| 47 |
"js/src/ctypes/libffi/", # imported code |
| 48 |
"js/src/devtools/", # auxiliary stuff |
| 49 |
"js/src/editline/", # imported code |
| 50 |
"js/src/gdb/", # auxiliary stuff |
| 51 |
"js/src/vtune/", # imported code |
| 52 |
"js/src/zydis/", # imported code |
| 53 |
"js/src/xsum/", # imported code |
| 54 |
] |
| 55 |
|
| 56 |
# We ignore #includes of these files, because they don't follow the usual rules. |
| 57 |
included_inclnames_to_ignore = set( |
| 58 |
[ |
| 59 |
"ffi.h", # generated in ctypes/libffi/ |
| 60 |
"devtools/Instruments.h", # we ignore devtools/ in general |
| 61 |
"double-conversion/double-conversion.h", # strange MFBT case |
| 62 |
"javascript-trace.h", # generated in $OBJDIR if HAVE_DTRACE is defined |
| 63 |
"frontend/ReservedWordsGenerated.h", # generated in $OBJDIR |
| 64 |
"gc/StatsPhasesGenerated.h", # generated in $OBJDIR |
| 65 |
"gc/StatsPhasesGenerated.inc", # generated in $OBJDIR |
| 66 |
"jit/ABIFunctionTypeGenerated.h", # generated in $OBJDIR" |
| 67 |
"jit/AtomicOperationsGenerated.h", # generated in $OBJDIR |
| 68 |
"jit/CacheIROpsGenerated.h", # generated in $OBJDIR |
| 69 |
"jit/CacheIRAOTGenerated.h", # generated in $OBJDIR |
| 70 |
"jit/LIROpsGenerated.h", # generated in $OBJDIR |
| 71 |
"jit/MIROpsGenerated.h", # generated in $OBJDIR |
| 72 |
"js/PrefsGenerated.h", # generated in $OBJDIR |
| 73 |
"js/ProfilingCategoryList.h", # comes from mozglue/baseprofiler |
| 74 |
"mozilla/glue/Debug.h", # comes from mozglue/misc, shadowed by <mozilla/Debug.h> |
| 75 |
"jscustomallocator.h", # provided by embedders; allowed to be missing |
| 76 |
"js-config.h", # generated in $OBJDIR |
| 77 |
"fdlibm.h", # fdlibm |
| 78 |
"FuzzerDefs.h", # included without a path |
| 79 |
"FuzzingInterface.h", # included without a path |
| 80 |
"diplomat_runtime.h", # ICU4X |
| 81 |
"ICU4XAnyCalendarKind.h", # ICU4X |
| 82 |
"ICU4XCalendar.h", # ICU4X |
| 83 |
"ICU4XDate.h", # ICU4X |
| 84 |
"ICU4XError.h", # ICU4X |
| 85 |
"ICU4XGraphemeClusterSegmenter.h", # ICU4X |
| 86 |
"ICU4XIsoDate.h", # ICU4X |
| 87 |
"ICU4XIsoWeekday.h", # ICU4X |
| 88 |
"ICU4XSentenceSegmenter.h", # ICU4X |
| 89 |
"ICU4XWeekCalculator.h", # ICU4X |
| 90 |
"ICU4XWeekOf.h", # ICU4X |
| 91 |
"ICU4XWeekRelativeUnit.h", # ICU4X |
| 92 |
"ICU4XWordSegmenter.h", # ICU4X |
| 93 |
"mozmemory.h", # included without a path |
| 94 |
"mozmemory_utils.h", # included without a path |
| 95 |
"pratom.h", # NSPR |
| 96 |
"prcvar.h", # NSPR |
| 97 |
"prerror.h", # NSPR |
| 98 |
"prinit.h", # NSPR |
| 99 |
"prio.h", # NSPR |
| 100 |
"private/pprio.h", # NSPR |
| 101 |
"prlink.h", # NSPR |
| 102 |
"prlock.h", # NSPR |
| 103 |
"prprf.h", # NSPR |
| 104 |
"prthread.h", # NSPR |
| 105 |
"prtypes.h", # NSPR |
| 106 |
"selfhosted.out.h", # generated in $OBJDIR |
| 107 |
"shellmoduleloader.out.h", # generated in $OBJDIR |
| 108 |
"unicode/locid.h", # ICU |
| 109 |
"unicode/uchar.h", # ICU |
| 110 |
"unicode/uniset.h", # ICU |
| 111 |
"unicode/unistr.h", # ICU |
| 112 |
"unicode/utypes.h", # ICU |
| 113 |
"vtune/VTuneWrapper.h", # VTune |
| 114 |
"wasm/WasmBuiltinModuleGenerated.h", # generated in $OBJDIR" |
| 115 |
"zydis/ZydisAPI.h", # Zydis |
| 116 |
"xsum/xsum.h", # xsum |
| 117 |
"fmt/format.h", # {fmt} main header |
| 118 |
] |
| 119 |
) |
| 120 |
|
| 121 |
deprecated_inclnames = { |
| 122 |
"mozilla/Unused.h": "Use [[nodiscard]] and (void)expr casts instead.", |
| 123 |
} |
| 124 |
|
| 125 |
# JSAPI functions should be included through headers from js/public instead of |
| 126 |
# using the old, catch-all jsapi.h file. |
| 127 |
deprecated_inclnames_in_header = { |
| 128 |
"jsapi.h": "Prefer including headers from js/public.", |
| 129 |
} |
| 130 |
|
| 131 |
# Temporary exclusions for files which still need to include jsapi.h. |
| 132 |
deprecated_inclnames_in_header_excludes = { |
| 133 |
"js/src/vm/Compartment-inl.h", # for JS::InformalValueTypeName |
| 134 |
"js/src/jsapi-tests/tests.h", # for JS_ValueToSource |
| 135 |
} |
| 136 |
|
| 137 |
# These files have additional constraints on where they are #included, so we |
| 138 |
# ignore #includes of them when checking #include ordering. |
| 139 |
oddly_ordered_inclnames = set( |
| 140 |
[ |
| 141 |
"ctypes/typedefs.h", # Included multiple times in the body of ctypes/CTypes.h |
| 142 |
# Included in the body of frontend/TokenStream.h |
| 143 |
"frontend/ReservedWordsGenerated.h", |
| 144 |
"gc/StatsPhasesGenerated.h", # Included in the body of gc/Statistics.h |
| 145 |
"gc/StatsPhasesGenerated.inc", # Included in the body of gc/Statistics.cpp |
| 146 |
"psapi.h", # Must be included after "util/WindowsWrapper.h" on Windows |
| 147 |
"machine/endian.h", # Must be included after <sys/types.h> on BSD |
| 148 |
"process.h", # Windows-specific |
| 149 |
"util/WindowsWrapper.h", # Must precede other system headers(?) |
| 150 |
] |
| 151 |
) |
| 152 |
|
| 153 |
# System headers which shouldn't be included directly, but instead use the |
| 154 |
# designated wrapper. |
| 155 |
wrapper_system_inclnames = { |
| 156 |
"windows.h": "util/WindowsWrapper.h", |
| 157 |
"windef.h": "util/WindowsWrapper.h", |
| 158 |
"winbase.h": "util/WindowsWrapper.h", |
| 159 |
} |
| 160 |
|
| 161 |
# The files in tests/style/ contain code that fails this checking in various |
| 162 |
# ways. Here is the output we expect. If the actual output differs from |
| 163 |
# this, one of the following must have happened. |
| 164 |
# - New SpiderMonkey code violates one of the checked rules. |
| 165 |
# - The tests/style/ files have changed without expected_output being changed |
| 166 |
# accordingly. |
| 167 |
# - This script has been broken somehow. |
| 168 |
# |
| 169 |
expected_output = """\ |
| 170 |
js/src/tests/style/BadIncludes.h:3: error: |
| 171 |
the file includes itself |
| 172 |
|
| 173 |
js/src/tests/style/BadIncludes.h:6: error: |
| 174 |
"BadIncludes2.h" is included using the wrong path; |
| 175 |
did you forget a prefix, or is the file not yet committed? |
| 176 |
|
| 177 |
js/src/tests/style/BadIncludes.h:8: error: |
| 178 |
<tests/style/BadIncludes2.h> should be included using |
| 179 |
the #include "..." form |
| 180 |
|
| 181 |
js/src/tests/style/BadIncludes.h:10: error: |
| 182 |
"stdio.h" is included using the wrong path; |
| 183 |
did you forget a prefix, or is the file not yet committed? |
| 184 |
|
| 185 |
js/src/tests/style/BadIncludes.h:12: error: |
| 186 |
"mozilla/Unused.h" is deprecated: Use [[nodiscard]] and (void)expr casts instead. |
| 187 |
|
| 188 |
js/src/tests/style/BadIncludes2.h:1: error: |
| 189 |
vanilla header includes an inline-header file "tests/style/BadIncludes2-inl.h" |
| 190 |
|
| 191 |
js/src/tests/style/BadIncludesOrder-inl.h:5:6: error: |
| 192 |
"vm/JSScript-inl.h" should be included after "vm/Interpreter-inl.h" |
| 193 |
|
| 194 |
js/src/tests/style/BadIncludesOrder-inl.h:6:7: error: |
| 195 |
"vm/Interpreter-inl.h" should be included after "js/Value.h" |
| 196 |
|
| 197 |
js/src/tests/style/BadIncludesOrder-inl.h:7:8: error: |
| 198 |
"js/Value.h" should be included after "ds/LifoAlloc.h" |
| 199 |
|
| 200 |
js/src/tests/style/BadIncludesOrder-inl.h:9: error: |
| 201 |
"jsapi.h" is deprecated: Prefer including headers from js/public. |
| 202 |
|
| 203 |
js/src/tests/style/BadIncludesOrder-inl.h:8:9: error: |
| 204 |
"ds/LifoAlloc.h" should be included after "jsapi.h" |
| 205 |
|
| 206 |
js/src/tests/style/BadIncludesOrder-inl.h:9:10: error: |
| 207 |
"jsapi.h" should be included after <stdio.h> |
| 208 |
|
| 209 |
js/src/tests/style/BadIncludesOrder-inl.h:10:11: error: |
| 210 |
<stdio.h> should be included after "mozilla/HashFunctions.h" |
| 211 |
|
| 212 |
js/src/tests/style/BadIncludesOrder-inl.h:20: error: |
| 213 |
"jsapi.h" is deprecated: Prefer including headers from js/public. |
| 214 |
|
| 215 |
js/src/tests/style/BadIncludesOrder-inl.h:28:29: error: |
| 216 |
"vm/JSScript.h" should be included after "vm/JSFunction.h" |
| 217 |
|
| 218 |
(multiple files): error: |
| 219 |
header files form one or more cycles |
| 220 |
|
| 221 |
tests/style/HeaderCycleA1.h |
| 222 |
-> tests/style/HeaderCycleA2.h |
| 223 |
-> tests/style/HeaderCycleA3.h |
| 224 |
-> tests/style/HeaderCycleA1.h |
| 225 |
|
| 226 |
tests/style/HeaderCycleB1-inl.h |
| 227 |
-> tests/style/HeaderCycleB2-inl.h |
| 228 |
-> tests/style/HeaderCycleB3-inl.h |
| 229 |
-> tests/style/HeaderCycleB4-inl.h |
| 230 |
-> tests/style/HeaderCycleB1-inl.h |
| 231 |
-> tests/style/jsheadercycleB5inlines.h |
| 232 |
-> tests/style/HeaderCycleB1-inl.h |
| 233 |
-> tests/style/HeaderCycleB4-inl.h |
| 234 |
|
| 235 |
""".splitlines( |
| 236 |
True |
| 237 |
) |
| 238 |
|
| 239 |
actual_output = [] |
| 240 |
|
| 241 |
|
| 242 |
def out(*lines): |
| 243 |
for line in lines: |
| 244 |
actual_output.append(line + "\n") |
| 245 |
|
| 246 |
|
| 247 |
def error(filename, linenum, *lines): |
| 248 |
location = filename |
| 249 |
if linenum is not None: |
| 250 |
location += ":" + str(linenum) |
| 251 |
out(location + ": error:") |
| 252 |
for line in lines: |
| 253 |
out(" " + line) |
| 254 |
out("") |
| 255 |
|
| 256 |
|
| 257 |
class FileKind: |
| 258 |
C = 1 |
| 259 |
CPP = 2 |
| 260 |
INL_H = 3 |
| 261 |
H = 4 |
| 262 |
TBL = 5 |
| 263 |
MSG = 6 |
| 264 |
|
| 265 |
@staticmethod |
| 266 |
def get(filename): |
| 267 |
if filename.endswith(".c"): |
| 268 |
return FileKind.C |
| 269 |
|
| 270 |
if filename.endswith(".cpp"): |
| 271 |
return FileKind.CPP |
| 272 |
|
| 273 |
if filename.endswith(("inlines.h", "-inl.h")): |
| 274 |
return FileKind.INL_H |
| 275 |
|
| 276 |
if filename.endswith(".h"): |
| 277 |
return FileKind.H |
| 278 |
|
| 279 |
if filename.endswith(".tbl"): |
| 280 |
return FileKind.TBL |
| 281 |
|
| 282 |
if filename.endswith(".msg"): |
| 283 |
return FileKind.MSG |
| 284 |
|
| 285 |
error(filename, None, "unknown file kind") |
| 286 |
|
| 287 |
|
| 288 |
def check_style(enable_fixup): |
| 289 |
# We deal with two kinds of name. |
| 290 |
# - A "filename" is a full path to a file from the repository root. |
| 291 |
# - An "inclname" is how a file is referred to in a #include statement. |
| 292 |
# |
| 293 |
# Examples (filename -> inclname) |
| 294 |
# - "mfbt/Attributes.h" -> "mozilla/Attributes.h" |
| 295 |
# - "mozglue/misc/TimeStamp.h -> "mozilla/TimeStamp.h" |
| 296 |
# - "memory/mozalloc/mozalloc.h -> "mozilla/mozalloc.h" |
| 297 |
# - "js/public/Vector.h" -> "js/Vector.h" |
| 298 |
# - "js/src/vm/String.h" -> "vm/String.h" |
| 299 |
|
| 300 |
non_js_dirnames = ( |
| 301 |
"mfbt/", |
| 302 |
"memory/mozalloc/", |
| 303 |
"mozglue/", |
| 304 |
"intl/components/", |
| 305 |
) # type: tuple(str) |
| 306 |
non_js_inclnames = set() # type: set(inclname) |
| 307 |
js_names = dict() # type: dict(filename, inclname) |
| 308 |
|
| 309 |
# Process files in js/src. |
| 310 |
js_src_root = os.path.join("js", "src") |
| 311 |
for dirpath, dirnames, filenames in os.walk(js_src_root): |
| 312 |
if dirpath == js_src_root: |
| 313 |
# Skip any subdirectories that contain a config.status file |
| 314 |
# (likely objdirs). |
| 315 |
builddirs = [] |
| 316 |
for dirname in dirnames: |
| 317 |
path = os.path.join(dirpath, dirname, "config.status") |
| 318 |
if os.path.isfile(path): |
| 319 |
builddirs.append(dirname) |
| 320 |
for dirname in builddirs: |
| 321 |
dirnames.remove(dirname) |
| 322 |
for filename in filenames: |
| 323 |
filepath = os.path.join(dirpath, filename).replace("\\", "/") |
| 324 |
if not filepath.startswith( |
| 325 |
tuple(ignored_js_src_dirs) |
| 326 |
) and filepath.endswith((".c", ".cpp", ".h", ".tbl", ".msg")): |
| 327 |
inclname = filepath[len("js/src/") :] |
| 328 |
js_names[filepath] = inclname |
| 329 |
|
| 330 |
# Look for header files in directories in non_js_dirnames. |
| 331 |
for non_js_dir in non_js_dirnames: |
| 332 |
for dirpath, dirnames, filenames in os.walk(non_js_dir): |
| 333 |
for filename in filenames: |
| 334 |
if filename.endswith(".h"): |
| 335 |
inclname = "mozilla/" + filename |
| 336 |
if non_js_dir == "intl/components/": |
| 337 |
inclname = "mozilla/intl/" + filename |
| 338 |
non_js_inclnames.add(inclname) |
| 339 |
|
| 340 |
# Look for header files in js/public. |
| 341 |
js_public_root = os.path.join("js", "public") |
| 342 |
for dirpath, dirnames, filenames in os.walk(js_public_root): |
| 343 |
for filename in filenames: |
| 344 |
if filename.endswith((".h", ".msg")): |
| 345 |
filepath = os.path.join(dirpath, filename).replace("\\", "/") |
| 346 |
inclname = "js/" + filepath[len("js/public/") :] |
| 347 |
js_names[filepath] = inclname |
| 348 |
|
| 349 |
all_inclnames = non_js_inclnames | set(js_names.values()) |
| 350 |
|
| 351 |
edges = dict() # type: dict(inclname, set(inclname)) |
| 352 |
|
| 353 |
# We don't care what's inside the MFBT and MOZALLOC files, but because they |
| 354 |
# are #included from JS files we have to add them to the inclusion graph. |
| 355 |
for inclname in non_js_inclnames: |
| 356 |
edges[inclname] = set() |
| 357 |
|
| 358 |
# Process all the JS files. |
| 359 |
for filename in sorted(js_names.keys()): |
| 360 |
inclname = js_names[filename] |
| 361 |
file_kind = FileKind.get(filename) |
| 362 |
if ( |
| 363 |
file_kind == FileKind.C |
| 364 |
or file_kind == FileKind.CPP |
| 365 |
or file_kind == FileKind.H |
| 366 |
or file_kind == FileKind.INL_H |
| 367 |
): |
| 368 |
included_h_inclnames = set() # type: set(inclname) |
| 369 |
|
| 370 |
with open(filename, encoding="utf-8") as f: |
| 371 |
code = read_file(f) |
| 372 |
|
| 373 |
if enable_fixup: |
| 374 |
code = code.sorted(inclname) |
| 375 |
with open(filename, "w") as f: |
| 376 |
f.write(code.to_source()) |
| 377 |
|
| 378 |
check_file( |
| 379 |
filename, inclname, file_kind, code, all_inclnames, included_h_inclnames |
| 380 |
) |
| 381 |
|
| 382 |
edges[inclname] = included_h_inclnames |
| 383 |
|
| 384 |
find_cycles(all_inclnames, edges) |
| 385 |
|
| 386 |
# Compare expected and actual output. |
| 387 |
difflines = difflib.unified_diff( |
| 388 |
expected_output, |
| 389 |
actual_output, |
| 390 |
fromfile="check_spidermonkey_style.py expected output", |
| 391 |
tofile="check_spidermonkey_style.py actual output", |
| 392 |
) |
| 393 |
ok = True |
| 394 |
for diffline in difflines: |
| 395 |
ok = False |
| 396 |
print(diffline, end="") |
| 397 |
|
| 398 |
return ok |
| 399 |
|
| 400 |
|
| 401 |
def module_name(name): |
| 402 |
"""Strip the trailing .cpp, .h, inlines.h or -inl.h from a filename.""" |
| 403 |
|
| 404 |
return ( |
| 405 |
name.replace("inlines.h", "") |
| 406 |
.replace("-inl.h", "") |
| 407 |
.replace(".h", "") |
| 408 |
.replace(".cpp", "") |
| 409 |
) # NOQA: E501 |
| 410 |
|
| 411 |
|
| 412 |
def is_module_header(enclosing_inclname, header_inclname): |
| 413 |
"""Determine if an included name is the "module header", i.e. should be |
| 414 |
first in the file.""" |
| 415 |
|
| 416 |
module = module_name(enclosing_inclname) |
| 417 |
|
| 418 |
# Normal case, for example: |
| 419 |
# module == "vm/Runtime", header_inclname == "vm/Runtime.h". |
| 420 |
if module == module_name(header_inclname): |
| 421 |
return True |
| 422 |
|
| 423 |
# A public header, for example: |
| 424 |
# |
| 425 |
# module == "vm/CharacterEncoding", |
| 426 |
# header_inclname == "js/CharacterEncoding.h" |
| 427 |
# |
| 428 |
# or (for implementation files for js/public/*/*.h headers) |
| 429 |
# |
| 430 |
# module == "vm/SourceHook", |
| 431 |
# header_inclname == "js/experimental/SourceHook.h" |
| 432 |
m = re.match(r"js\/.*?([^\/]+)\.h", header_inclname) |
| 433 |
if m is not None and module.endswith("/" + m.group(1)): |
| 434 |
return True |
| 435 |
|
| 436 |
return False |
| 437 |
|
| 438 |
|
| 439 |
class Include: |
| 440 |
"""Important information for a single #include statement.""" |
| 441 |
|
| 442 |
def __init__(self, include_prefix, inclname, line_suffix, linenum, is_system): |
| 443 |
self.include_prefix = include_prefix |
| 444 |
self.line_suffix = line_suffix |
| 445 |
self.inclname = inclname |
| 446 |
self.linenum = linenum |
| 447 |
self.is_system = is_system |
| 448 |
|
| 449 |
def is_style_relevant(self): |
| 450 |
# Includes are style-relevant; that is, they're checked by the pairwise |
| 451 |
# style-checking algorithm in check_file. |
| 452 |
return True |
| 453 |
|
| 454 |
def section(self, enclosing_inclname): |
| 455 |
"""Identify which section inclname belongs to. |
| 456 |
|
| 457 |
The section numbers are as follows. |
| 458 |
0. Module header (e.g. jsfoo.h or jsfooinlines.h within jsfoo.cpp) |
| 459 |
1. mozilla/Foo.h |
| 460 |
2. <foo.h> or <foo> |
| 461 |
3. jsfoo.h, prmjtime.h, etc |
| 462 |
4. foo/Bar.h |
| 463 |
5. jsfooinlines.h |
| 464 |
6. foo/Bar-inl.h |
| 465 |
7. non-.h, e.g. *.tbl, *.msg (these can be scattered throughout files) |
| 466 |
""" |
| 467 |
|
| 468 |
if self.is_system: |
| 469 |
return 2 |
| 470 |
|
| 471 |
if not self.inclname.endswith(".h"): |
| 472 |
return 7 |
| 473 |
|
| 474 |
# A couple of modules have the .h file in js/ and the .cpp file elsewhere and so need |
| 475 |
# special handling. |
| 476 |
if is_module_header(enclosing_inclname, self.inclname): |
| 477 |
return 0 |
| 478 |
|
| 479 |
if "/" in self.inclname: |
| 480 |
if self.inclname.startswith("mozilla/"): |
| 481 |
return 1 |
| 482 |
|
| 483 |
if self.inclname.endswith("-inl.h"): |
| 484 |
return 6 |
| 485 |
|
| 486 |
return 4 |
| 487 |
|
| 488 |
if self.inclname.endswith("inlines.h"): |
| 489 |
return 5 |
| 490 |
|
| 491 |
return 3 |
| 492 |
|
| 493 |
def quote(self): |
| 494 |
if self.is_system: |
| 495 |
return "<" + self.inclname + ">" |
| 496 |
else: |
| 497 |
return '"' + self.inclname + '"' |
| 498 |
|
| 499 |
def sort_key(self, enclosing_inclname): |
| 500 |
return (self.section(enclosing_inclname), self.inclname.lower()) |
| 501 |
|
| 502 |
def to_source(self): |
| 503 |
return self.include_prefix + self.quote() + self.line_suffix + "\n" |
| 504 |
|
| 505 |
|
| 506 |
class CppBlock: |
| 507 |
"""C preprocessor block: a whole file or a single #if/#elif/#else block. |
| 508 |
|
| 509 |
A #if/#endif block is the contents of a #if/#endif (or similar) section. |
| 510 |
The top-level block, which is not within a #if/#endif pair, is also |
| 511 |
considered a block. |
| 512 |
|
| 513 |
Each kid is either an Include (representing a #include), OrdinaryCode, or |
| 514 |
a nested CppBlock.""" |
| 515 |
|
| 516 |
def __init__(self, start_line=""): |
| 517 |
self.start = start_line |
| 518 |
self.end = "" |
| 519 |
self.kids = [] |
| 520 |
|
| 521 |
def is_style_relevant(self): |
| 522 |
return True |
| 523 |
|
| 524 |
def append_ordinary_line(self, line): |
| 525 |
if len(self.kids) == 0 or not isinstance(self.kids[-1], OrdinaryCode): |
| 526 |
self.kids.append(OrdinaryCode()) |
| 527 |
self.kids[-1].lines.append(line) |
| 528 |
|
| 529 |
def style_relevant_kids(self): |
| 530 |
"""Return a list of kids in this block that are style-relevant.""" |
| 531 |
return [kid for kid in self.kids if kid.is_style_relevant()] |
| 532 |
|
| 533 |
def sorted(self, enclosing_inclname): |
| 534 |
"""Return a hopefully-sorted copy of this block. Implements --fixup. |
| 535 |
|
| 536 |
When in doubt, this leaves the code unchanged. |
| 537 |
""" |
| 538 |
|
| 539 |
def pretty_sorted_includes(includes): |
| 540 |
"""Return a new list containing the given includes, in order, |
| 541 |
with blank lines separating sections.""" |
| 542 |
keys = [inc.sort_key(enclosing_inclname) for inc in includes] |
| 543 |
if sorted(keys) == keys: |
| 544 |
return includes # if nothing is out of order, don't touch anything |
| 545 |
|
| 546 |
output = [] |
| 547 |
current_section = None |
| 548 |
for (section, _), inc in sorted(zip(keys, includes)): |
| 549 |
if current_section is not None and section != current_section: |
| 550 |
output.append(OrdinaryCode(["\n"])) # blank line |
| 551 |
output.append(inc) |
| 552 |
current_section = section |
| 553 |
return output |
| 554 |
|
| 555 |
def should_try_to_sort(includes): |
| 556 |
if "tests/style/BadIncludes" in enclosing_inclname: |
| 557 |
return False # don't straighten the counterexample |
| 558 |
if any(inc.inclname in oddly_ordered_inclnames for inc in includes): |
| 559 |
return False # don't sort batches containing odd includes |
| 560 |
if includes == sorted( |
| 561 |
includes, key=lambda inc: inc.sort_key(enclosing_inclname) |
| 562 |
): |
| 563 |
return False # it's already sorted, avoid whitespace-only fixups |
| 564 |
return True |
| 565 |
|
| 566 |
# The content of the eventual output of this method. |
| 567 |
output = [] |
| 568 |
|
| 569 |
# The current batch of includes to sort. This list only ever contains Include objects |
| 570 |
# and whitespace OrdinaryCode objects. |
| 571 |
batch = [] |
| 572 |
|
| 573 |
def flush_batch(): |
| 574 |
"""Sort the contents of `batch` and move it to `output`.""" |
| 575 |
|
| 576 |
assert all( |
| 577 |
isinstance(item, Include) |
| 578 |
or (isinstance(item, OrdinaryCode) and "".join(item.lines).isspace()) |
| 579 |
for item in batch |
| 580 |
) |
| 581 |
|
| 582 |
# Here we throw away the blank lines. |
| 583 |
# `pretty_sorted_includes` puts them back. |
| 584 |
includes = [] |
| 585 |
last_include_index = -1 |
| 586 |
for i, item in enumerate(batch): |
| 587 |
if isinstance(item, Include): |
| 588 |
includes.append(item) |
| 589 |
last_include_index = i |
| 590 |
cutoff = last_include_index + 1 |
| 591 |
|
| 592 |
if should_try_to_sort(includes): |
| 593 |
output.extend(pretty_sorted_includes(includes) + batch[cutoff:]) |
| 594 |
else: |
| 595 |
output.extend(batch) |
| 596 |
del batch[:] |
| 597 |
|
| 598 |
for kid in self.kids: |
| 599 |
if isinstance(kid, CppBlock): |
| 600 |
flush_batch() |
| 601 |
output.append(kid.sorted(enclosing_inclname)) |
| 602 |
elif isinstance(kid, Include): |
| 603 |
batch.append(kid) |
| 604 |
else: |
| 605 |
assert isinstance(kid, OrdinaryCode) |
| 606 |
if kid.to_source().isspace(): |
| 607 |
batch.append(kid) |
| 608 |
else: |
| 609 |
flush_batch() |
| 610 |
output.append(kid) |
| 611 |
flush_batch() |
| 612 |
|
| 613 |
result = CppBlock() |
| 614 |
result.start = self.start |
| 615 |
result.end = self.end |
| 616 |
result.kids = output |
| 617 |
return result |
| 618 |
|
| 619 |
def to_source(self): |
| 620 |
return self.start + "".join(kid.to_source() for kid in self.kids) + self.end |
| 621 |
|
| 622 |
|
| 623 |
class OrdinaryCode: |
| 624 |
"""A list of lines of code that aren't #include/#if/#else/#endif lines.""" |
| 625 |
|
| 626 |
def __init__(self, lines=None): |
| 627 |
self.lines = lines if lines is not None else [] |
| 628 |
|
| 629 |
def is_style_relevant(self): |
| 630 |
return False |
| 631 |
|
| 632 |
def to_source(self): |
| 633 |
return "".join(self.lines) |
| 634 |
|
| 635 |
|
| 636 |
# A "snippet" is one of: |
| 637 |
# |
| 638 |
# * Include - representing an #include line |
| 639 |
# * CppBlock - a whole file or #if/#elif/#else block; contains a list of snippets |
| 640 |
# * OrdinaryCode - representing lines of non-#include-relevant code |
| 641 |
|
| 642 |
|
| 643 |
def read_file(f): |
| 644 |
block_stack = [CppBlock()] |
| 645 |
|
| 646 |
# Extract the #include statements as a tree of snippets. |
| 647 |
for linenum, line in enumerate(f, start=1): |
| 648 |
if line.lstrip().startswith("#"): |
| 649 |
# Look for a |#include "..."| line. |
| 650 |
m = re.match(r'(\s*#\s*include\s+)"([^"]*)"(.*)', line) |
| 651 |
if m is not None: |
| 652 |
prefix, inclname, suffix = m.groups() |
| 653 |
block_stack[-1].kids.append( |
| 654 |
Include(prefix, inclname, suffix, linenum, is_system=False) |
| 655 |
) |
| 656 |
continue |
| 657 |
|
| 658 |
# Look for a |#include <...>| line. |
| 659 |
m = re.match(r"(\s*#\s*include\s+)<([^>]*)>(.*)", line) |
| 660 |
if m is not None: |
| 661 |
prefix, inclname, suffix = m.groups() |
| 662 |
block_stack[-1].kids.append( |
| 663 |
Include(prefix, inclname, suffix, linenum, is_system=True) |
| 664 |
) |
| 665 |
continue |
| 666 |
|
| 667 |
# Look for a |#{if,ifdef,ifndef}| line. |
| 668 |
m = re.match(r"\s*#\s*(if|ifdef|ifndef)\b", line) |
| 669 |
if m is not None: |
| 670 |
# Open a new block. |
| 671 |
new_block = CppBlock(line) |
| 672 |
block_stack[-1].kids.append(new_block) |
| 673 |
block_stack.append(new_block) |
| 674 |
continue |
| 675 |
|
| 676 |
# Look for a |#{elif,else}| line. |
| 677 |
m = re.match(r"\s*#\s*(elif|else)\b", line) |
| 678 |
if m is not None: |
| 679 |
# Close the current block, and open an adjacent one. |
| 680 |
block_stack.pop() |
| 681 |
new_block = CppBlock(line) |
| 682 |
block_stack[-1].kids.append(new_block) |
| 683 |
block_stack.append(new_block) |
| 684 |
continue |
| 685 |
|
| 686 |
# Look for a |#endif| line. |
| 687 |
m = re.match(r"\s*#\s*endif\b", line) |
| 688 |
if m is not None: |
| 689 |
# Close the current block. |
| 690 |
block_stack.pop().end = line |
| 691 |
if len(block_stack) == 0: |
| 692 |
raise ValueError("#endif without #if at line " + str(linenum)) |
| 693 |
continue |
| 694 |
|
| 695 |
# Otherwise, we have an ordinary line. |
| 696 |
block_stack[-1].append_ordinary_line(line) |
| 697 |
|
| 698 |
if len(block_stack) > 1: |
| 699 |
raise ValueError("unmatched #if") |
| 700 |
return block_stack[-1] |
| 701 |
|
| 702 |
|
| 703 |
def check_file( |
| 704 |
filename, inclname, file_kind, code, all_inclnames, included_h_inclnames |
| 705 |
): |
| 706 |
def check_include_statement(include): |
| 707 |
"""Check the style of a single #include statement.""" |
| 708 |
|
| 709 |
if include.is_system: |
| 710 |
# Check it is not a known local file (in which case it's probably a system header). |
| 711 |
if ( |
| 712 |
include.inclname in included_inclnames_to_ignore |
| 713 |
or include.inclname in all_inclnames |
| 714 |
): |
| 715 |
error( |
| 716 |
filename, |
| 717 |
include.linenum, |
| 718 |
include.quote() + " should be included using", |
| 719 |
'the #include "..." form', |
| 720 |
) |
| 721 |
|
| 722 |
# Check for system header which shouldn't be included directly. |
| 723 |
if ( |
| 724 |
include.inclname in wrapper_system_inclnames |
| 725 |
and wrapper_system_inclnames[include.inclname] != inclname |
| 726 |
): |
| 727 |
wrapper_inclname = wrapper_system_inclnames[include.inclname] |
| 728 |
error( |
| 729 |
filename, |
| 730 |
include.linenum, |
| 731 |
f"{include.quote()} should not be included directly, " |
| 732 |
f'instead use "{wrapper_inclname}"', |
| 733 |
) |
| 734 |
else: |
| 735 |
msg = deprecated_inclnames.get(include.inclname) |
| 736 |
if msg: |
| 737 |
error( |
| 738 |
filename, |
| 739 |
include.linenum, |
| 740 |
include.quote() + " is deprecated: " + msg, |
| 741 |
) |
| 742 |
|
| 743 |
if file_kind == FileKind.H or file_kind == FileKind.INL_H: |
| 744 |
msg = deprecated_inclnames_in_header.get(include.inclname) |
| 745 |
if msg and filename not in deprecated_inclnames_in_header_excludes: |
| 746 |
error( |
| 747 |
filename, |
| 748 |
include.linenum, |
| 749 |
include.quote() + " is deprecated: " + msg, |
| 750 |
) |
| 751 |
|
| 752 |
if include.inclname not in included_inclnames_to_ignore: |
| 753 |
included_kind = FileKind.get(include.inclname) |
| 754 |
|
| 755 |
# Check the #include path has the correct form. |
| 756 |
if include.inclname not in all_inclnames: |
| 757 |
error( |
| 758 |
filename, |
| 759 |
include.linenum, |
| 760 |
include.quote() + " is included using the wrong path;", |
| 761 |
"did you forget a prefix, or is the file not yet committed?", |
| 762 |
) |
| 763 |
|
| 764 |
# Record inclusions of .h files for cycle detection later. |
| 765 |
# (Exclude .tbl and .msg files.) |
| 766 |
elif included_kind == FileKind.H or included_kind == FileKind.INL_H: |
| 767 |
included_h_inclnames.add(include.inclname) |
| 768 |
|
| 769 |
# Check a H file doesn't #include an INL_H file. |
| 770 |
if file_kind == FileKind.H and included_kind == FileKind.INL_H: |
| 771 |
error( |
| 772 |
filename, |
| 773 |
include.linenum, |
| 774 |
"vanilla header includes an inline-header file " |
| 775 |
+ include.quote(), |
| 776 |
) |
| 777 |
|
| 778 |
# Check a file doesn't #include itself. (We do this here because the cycle |
| 779 |
# detection below doesn't detect this case.) |
| 780 |
if inclname == include.inclname: |
| 781 |
error(filename, include.linenum, "the file includes itself") |
| 782 |
|
| 783 |
def check_includes_order(include1, include2): |
| 784 |
"""Check the ordering of two #include statements.""" |
| 785 |
|
| 786 |
if ( |
| 787 |
include1.inclname in oddly_ordered_inclnames |
| 788 |
or include2.inclname in oddly_ordered_inclnames |
| 789 |
): |
| 790 |
return |
| 791 |
|
| 792 |
section1 = include1.section(inclname) |
| 793 |
section2 = include2.section(inclname) |
| 794 |
if (section1 > section2) or ( |
| 795 |
(section1 == section2) |
| 796 |
and (include1.inclname.lower() > include2.inclname.lower()) |
| 797 |
): |
| 798 |
error( |
| 799 |
filename, |
| 800 |
str(include1.linenum) + ":" + str(include2.linenum), |
| 801 |
include1.quote() + " should be included after " + include2.quote(), |
| 802 |
) |
| 803 |
|
| 804 |
# Check the extracted #include statements, both individually, and the ordering of |
| 805 |
# adjacent pairs that live in the same block. |
| 806 |
def pair_traverse(prev, this): |
| 807 |
if isinstance(this, Include): |
| 808 |
check_include_statement(this) |
| 809 |
if isinstance(prev, Include): |
| 810 |
check_includes_order(prev, this) |
| 811 |
else: |
| 812 |
kids = this.style_relevant_kids() |
| 813 |
for prev2, this2 in zip([None] + kids[0:-1], kids): |
| 814 |
pair_traverse(prev2, this2) |
| 815 |
|
| 816 |
pair_traverse(None, code) |
| 817 |
|
| 818 |
|
| 819 |
def find_cycles(all_inclnames, edges): |
| 820 |
"""Find and draw any cycles.""" |
| 821 |
|
| 822 |
SCCs = tarjan(all_inclnames, edges) |
| 823 |
|
| 824 |
# The various sorted() calls below ensure the output is deterministic. |
| 825 |
|
| 826 |
def draw_SCC(c): |
| 827 |
cset = set(c) |
| 828 |
drawn = set() |
| 829 |
|
| 830 |
def draw(v, indent): |
| 831 |
out(" " * indent + ("-> " if indent else " ") + v) |
| 832 |
if v in drawn: |
| 833 |
return |
| 834 |
drawn.add(v) |
| 835 |
for succ in sorted(edges[v]): |
| 836 |
if succ in cset: |
| 837 |
draw(succ, indent + 1) |
| 838 |
|
| 839 |
draw(sorted(c)[0], 0) |
| 840 |
out("") |
| 841 |
|
| 842 |
have_drawn_an_SCC = False |
| 843 |
for scc in sorted(SCCs): |
| 844 |
if len(scc) != 1: |
| 845 |
if not have_drawn_an_SCC: |
| 846 |
error("(multiple files)", None, "header files form one or more cycles") |
| 847 |
have_drawn_an_SCC = True |
| 848 |
|
| 849 |
draw_SCC(scc) |
| 850 |
|
| 851 |
|
| 852 |
# Tarjan's algorithm for finding the strongly connected components (SCCs) of a graph. |
| 853 |
# https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm |
| 854 |
def tarjan(V, E): |
| 855 |
vertex_index = {} |
| 856 |
vertex_lowlink = {} |
| 857 |
index = 0 |
| 858 |
S = [] |
| 859 |
all_SCCs = [] |
| 860 |
|
| 861 |
def strongconnect(v, index): |
| 862 |
# Set the depth index for v to the smallest unused index |
| 863 |
vertex_index[v] = index |
| 864 |
vertex_lowlink[v] = index |
| 865 |
index += 1 |
| 866 |
S.append(v) |
| 867 |
|
| 868 |
# Consider successors of v |
| 869 |
for w in E[v]: |
| 870 |
if w not in vertex_index: |
| 871 |
# Successor w has not yet been visited; recurse on it |
| 872 |
index = strongconnect(w, index) |
| 873 |
vertex_lowlink[v] = min(vertex_lowlink[v], vertex_lowlink[w]) |
| 874 |
elif w in S: |
| 875 |
# Successor w is in stack S and hence in the current SCC |
| 876 |
vertex_lowlink[v] = min(vertex_lowlink[v], vertex_index[w]) |
| 877 |
|
| 878 |
# If v is a root node, pop the stack and generate an SCC |
| 879 |
if vertex_lowlink[v] == vertex_index[v]: |
| 880 |
i = S.index(v) |
| 881 |
scc = S[i:] |
| 882 |
del S[i:] |
| 883 |
all_SCCs.append(scc) |
| 884 |
|
| 885 |
return index |
| 886 |
|
| 887 |
for v in V: |
| 888 |
if v not in vertex_index: |
| 889 |
index = strongconnect(v, index) |
| 890 |
|
| 891 |
return all_SCCs |
| 892 |
|
| 893 |
|
| 894 |
def main(): |
| 895 |
if sys.argv[1:] == ["--fixup"]: |
| 896 |
# Sort #include directives in-place. Fixup mode doesn't solve |
| 897 |
# all possible silliness that the script checks for; it's just a |
| 898 |
# hack for the common case where renaming a header causes style |
| 899 |
# errors. |
| 900 |
fixup = True |
| 901 |
elif sys.argv[1:] == []: |
| 902 |
fixup = False |
| 903 |
else: |
| 904 |
print( |
| 905 |
"TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | unexpected command " |
| 906 |
"line options: " + repr(sys.argv[1:]) |
| 907 |
) |
| 908 |
sys.exit(1) |
| 909 |
|
| 910 |
ok = check_style(fixup) |
| 911 |
|
| 912 |
if ok: |
| 913 |
print("TEST-PASS | check_spidermonkey_style.py | ok") |
| 914 |
else: |
| 915 |
print( |
| 916 |
"TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | " |
| 917 |
+ "actual output does not match expected output; diff is above." |
| 918 |
) |
| 919 |
print( |
| 920 |
"TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | " |
| 921 |
+ "Hint: If the problem is that you renamed a header, and many #includes " |
| 922 |
+ "are no longer in alphabetical order, commit your work and then try " |
| 923 |
+ "`check_spidermonkey_style.py --fixup`. " |
| 924 |
+ "You need to commit first because --fixup modifies your files in place." |
| 925 |
) |
| 926 |
|
| 927 |
sys.exit(0 if ok else 1) |
| 928 |
|
| 929 |
|
| 930 |
if __name__ == "__main__": |
| 931 |
main() |