Bug 1776056 - Switch to the tab an animation is running and make sure the animation...
[gecko.git] / config / check_spidermonkey_style.py
blob3ad27cbe883258b0808af2281a79e7f1094163f6
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/.
6 # ----------------------------------------------------------------------------
7 # This script checks various aspects of SpiderMonkey code style. The current checks are as
8 # follows.
10 # We check the following things in headers.
12 # - No cyclic dependencies.
14 # - No normal header should #include a inlines.h/-inl.h file.
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.
20 # We check the following things in all files.
22 # - #includes should have full paths, e.g. "jit/Ion.h", not "Ion.h".
24 # - #includes should use the appropriate form for system headers (<...>) and
25 # local headers ("...").
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 # ----------------------------------------------------------------------------
38 import difflib
39 import os
40 import re
41 import sys
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
55 # We ignore #includes of these files, because they don't follow the usual rules.
56 included_inclnames_to_ignore = set(
58 "ffi.h", # generated in ctypes/libffi/
59 "devtools/Instruments.h", # we ignore devtools/ in general
60 "double-conversion/double-conversion.h", # strange MFBT case
61 "javascript-trace.h", # generated in $OBJDIR if HAVE_DTRACE is defined
62 "frontend/ReservedWordsGenerated.h", # generated in $OBJDIR
63 "frontend/smoosh_generated.h", # generated in $OBJDIR
64 "gc/StatsPhasesGenerated.h", # generated in $OBJDIR
65 "gc/StatsPhasesGenerated.inc", # generated in $OBJDIR
66 "jit/AtomicOperationsGenerated.h", # generated in $OBJDIR
67 "jit/CacheIROpsGenerated.h", # generated in $OBJDIR
68 "jit/LIROpsGenerated.h", # generated in $OBJDIR
69 "jit/MIROpsGenerated.h", # generated in $OBJDIR
70 "js/ProfilingCategoryList.h", # comes from mozglue/baseprofiler
71 "jscustomallocator.h", # provided by embedders; allowed to be missing
72 "js-config.h", # generated in $OBJDIR
73 "fdlibm.h", # fdlibm
74 "FuzzerDefs.h", # included without a path
75 "FuzzingInterface.h", # included without a path
76 "mozmemory.h", # included without a path
77 "pratom.h", # NSPR
78 "prcvar.h", # NSPR
79 "prerror.h", # NSPR
80 "prinit.h", # NSPR
81 "prio.h", # NSPR
82 "private/pprio.h", # NSPR
83 "prlink.h", # NSPR
84 "prlock.h", # NSPR
85 "prprf.h", # NSPR
86 "prthread.h", # NSPR
87 "prtypes.h", # NSPR
88 "selfhosted.out.h", # generated in $OBJDIR
89 "shellmoduleloader.out.h", # generated in $OBJDIR
90 "unicode/locid.h", # ICU
91 "unicode/uchar.h", # ICU
92 "unicode/uniset.h", # ICU
93 "unicode/unistr.h", # ICU
94 "unicode/utypes.h", # ICU
95 "vtune/VTuneWrapper.h", # VTune
96 "wasm/WasmIntrinsicGenerated.h", # generated in $OBJDIR"
97 "zydis/ZydisAPI.h", # Zydis
101 deprecated_inclnames = {
102 "mozilla/Unused.h": "Use [[nodiscard]] and (void)expr casts instead.",
105 # JSAPI functions should be included through headers from js/public instead of
106 # using the old, catch-all jsapi.h file.
107 deprecated_inclnames_in_header = {
108 "jsapi.h": "Prefer including headers from js/public.",
111 # Temporary exclusions for files which still need to include jsapi.h.
112 deprecated_inclnames_in_header_excludes = {
113 "js/src/vm/Compartment-inl.h", # for JS::InformalValueTypeName
114 "js/src/jsapi-tests/tests.h", # for JS_ValueToSource
117 # These files have additional constraints on where they are #included, so we
118 # ignore #includes of them when checking #include ordering.
119 oddly_ordered_inclnames = set(
121 "ctypes/typedefs.h", # Included multiple times in the body of ctypes/CTypes.h
122 # Included in the body of frontend/TokenStream.h
123 "frontend/ReservedWordsGenerated.h",
124 "gc/StatsPhasesGenerated.h", # Included in the body of gc/Statistics.h
125 "gc/StatsPhasesGenerated.inc", # Included in the body of gc/Statistics.cpp
126 "psapi.h", # Must be included after "util/WindowsWrapper.h" on Windows
127 "machine/endian.h", # Must be included after <sys/types.h> on BSD
128 "winbase.h", # Must precede other system headers(?)
129 "windef.h", # Must precede other system headers(?)
133 # The files in tests/style/ contain code that fails this checking in various
134 # ways. Here is the output we expect. If the actual output differs from
135 # this, one of the following must have happened.
136 # - New SpiderMonkey code violates one of the checked rules.
137 # - The tests/style/ files have changed without expected_output being changed
138 # accordingly.
139 # - This script has been broken somehow.
141 expected_output = """\
142 js/src/tests/style/BadIncludes.h:3: error:
143 the file includes itself
145 js/src/tests/style/BadIncludes.h:6: error:
146 "BadIncludes2.h" is included using the wrong path;
147 did you forget a prefix, or is the file not yet committed?
149 js/src/tests/style/BadIncludes.h:8: error:
150 <tests/style/BadIncludes2.h> should be included using
151 the #include "..." form
153 js/src/tests/style/BadIncludes.h:10: error:
154 "stdio.h" is included using the wrong path;
155 did you forget a prefix, or is the file not yet committed?
157 js/src/tests/style/BadIncludes.h:12: error:
158 "mozilla/Unused.h" is deprecated: Use [[nodiscard]] and (void)expr casts instead.
160 js/src/tests/style/BadIncludes2.h:1: error:
161 vanilla header includes an inline-header file "tests/style/BadIncludes2-inl.h"
163 js/src/tests/style/BadIncludesOrder-inl.h:5:6: error:
164 "vm/JSScript-inl.h" should be included after "vm/Interpreter-inl.h"
166 js/src/tests/style/BadIncludesOrder-inl.h:6:7: error:
167 "vm/Interpreter-inl.h" should be included after "js/Value.h"
169 js/src/tests/style/BadIncludesOrder-inl.h:7:8: error:
170 "js/Value.h" should be included after "ds/LifoAlloc.h"
172 js/src/tests/style/BadIncludesOrder-inl.h:9: error:
173 "jsapi.h" is deprecated: Prefer including headers from js/public.
175 js/src/tests/style/BadIncludesOrder-inl.h:8:9: error:
176 "ds/LifoAlloc.h" should be included after "jsapi.h"
178 js/src/tests/style/BadIncludesOrder-inl.h:9:10: error:
179 "jsapi.h" should be included after <stdio.h>
181 js/src/tests/style/BadIncludesOrder-inl.h:10:11: error:
182 <stdio.h> should be included after "mozilla/HashFunctions.h"
184 js/src/tests/style/BadIncludesOrder-inl.h:20: error:
185 "jsapi.h" is deprecated: Prefer including headers from js/public.
187 js/src/tests/style/BadIncludesOrder-inl.h:28:29: error:
188 "vm/JSScript.h" should be included after "vm/JSFunction.h"
190 (multiple files): error:
191 header files form one or more cycles
193 tests/style/HeaderCycleA1.h
194 -> tests/style/HeaderCycleA2.h
195 -> tests/style/HeaderCycleA3.h
196 -> tests/style/HeaderCycleA1.h
198 tests/style/HeaderCycleB1-inl.h
199 -> tests/style/HeaderCycleB2-inl.h
200 -> tests/style/HeaderCycleB3-inl.h
201 -> tests/style/HeaderCycleB4-inl.h
202 -> tests/style/HeaderCycleB1-inl.h
203 -> tests/style/jsheadercycleB5inlines.h
204 -> tests/style/HeaderCycleB1-inl.h
205 -> tests/style/HeaderCycleB4-inl.h
207 """.splitlines(
208 True
211 actual_output = []
214 def out(*lines):
215 for line in lines:
216 actual_output.append(line + "\n")
219 def error(filename, linenum, *lines):
220 location = filename
221 if linenum is not None:
222 location += ":" + str(linenum)
223 out(location + ": error:")
224 for line in lines:
225 out(" " + line)
226 out("")
229 class FileKind(object):
230 C = 1
231 CPP = 2
232 INL_H = 3
233 H = 4
234 TBL = 5
235 MSG = 6
237 @staticmethod
238 def get(filename):
239 if filename.endswith(".c"):
240 return FileKind.C
242 if filename.endswith(".cpp"):
243 return FileKind.CPP
245 if filename.endswith(("inlines.h", "-inl.h")):
246 return FileKind.INL_H
248 if filename.endswith(".h"):
249 return FileKind.H
251 if filename.endswith(".tbl"):
252 return FileKind.TBL
254 if filename.endswith(".msg"):
255 return FileKind.MSG
257 error(filename, None, "unknown file kind")
260 def check_style(enable_fixup):
261 # We deal with two kinds of name.
262 # - A "filename" is a full path to a file from the repository root.
263 # - An "inclname" is how a file is referred to in a #include statement.
265 # Examples (filename -> inclname)
266 # - "mfbt/Attributes.h" -> "mozilla/Attributes.h"
267 # - "mozglue/misc/TimeStamp.h -> "mozilla/TimeStamp.h"
268 # - "memory/mozalloc/mozalloc.h -> "mozilla/mozalloc.h"
269 # - "js/public/Vector.h" -> "js/Vector.h"
270 # - "js/src/vm/String.h" -> "vm/String.h"
272 non_js_dirnames = (
273 "mfbt/",
274 "memory/mozalloc/",
275 "mozglue/",
276 "intl/components/",
277 ) # type: tuple(str)
278 non_js_inclnames = set() # type: set(inclname)
279 js_names = dict() # type: dict(filename, inclname)
281 # Process files in js/src.
282 js_src_root = os.path.join("js", "src")
283 for dirpath, dirnames, filenames in os.walk(js_src_root):
284 if dirpath == js_src_root:
285 # Skip any subdirectories that contain a config.status file
286 # (likely objdirs).
287 builddirs = []
288 for dirname in dirnames:
289 path = os.path.join(dirpath, dirname, "config.status")
290 if os.path.isfile(path):
291 builddirs.append(dirname)
292 for dirname in builddirs:
293 dirnames.remove(dirname)
294 for filename in filenames:
295 filepath = os.path.join(dirpath, filename).replace("\\", "/")
296 if not filepath.startswith(
297 tuple(ignored_js_src_dirs)
298 ) and filepath.endswith((".c", ".cpp", ".h", ".tbl", ".msg")):
299 inclname = filepath[len("js/src/") :]
300 js_names[filepath] = inclname
302 # Look for header files in directories in non_js_dirnames.
303 for non_js_dir in non_js_dirnames:
304 for dirpath, dirnames, filenames in os.walk(non_js_dir):
305 for filename in filenames:
306 if filename.endswith(".h"):
307 inclname = "mozilla/" + filename
308 if non_js_dir == "intl/components/":
309 inclname = "mozilla/intl/" + filename
310 non_js_inclnames.add(inclname)
312 # Look for header files in js/public.
313 js_public_root = os.path.join("js", "public")
314 for dirpath, dirnames, filenames in os.walk(js_public_root):
315 for filename in filenames:
316 if filename.endswith((".h", ".msg")):
317 filepath = os.path.join(dirpath, filename).replace("\\", "/")
318 inclname = "js/" + filepath[len("js/public/") :]
319 js_names[filepath] = inclname
321 all_inclnames = non_js_inclnames | set(js_names.values())
323 edges = dict() # type: dict(inclname, set(inclname))
325 # We don't care what's inside the MFBT and MOZALLOC files, but because they
326 # are #included from JS files we have to add them to the inclusion graph.
327 for inclname in non_js_inclnames:
328 edges[inclname] = set()
330 # Process all the JS files.
331 for filename in sorted(js_names.keys()):
332 inclname = js_names[filename]
333 file_kind = FileKind.get(filename)
334 if (
335 file_kind == FileKind.C
336 or file_kind == FileKind.CPP
337 or file_kind == FileKind.H
338 or file_kind == FileKind.INL_H
340 included_h_inclnames = set() # type: set(inclname)
342 with open(filename, encoding="utf-8") as f:
343 code = read_file(f)
345 if enable_fixup:
346 code = code.sorted(inclname)
347 with open(filename, "w") as f:
348 f.write(code.to_source())
350 check_file(
351 filename, inclname, file_kind, code, all_inclnames, included_h_inclnames
354 edges[inclname] = included_h_inclnames
356 find_cycles(all_inclnames, edges)
358 # Compare expected and actual output.
359 difflines = difflib.unified_diff(
360 expected_output,
361 actual_output,
362 fromfile="check_spidermonkey_style.py expected output",
363 tofile="check_spidermonkey_style.py actual output",
365 ok = True
366 for diffline in difflines:
367 ok = False
368 print(diffline, end="")
370 return ok
373 def module_name(name):
374 """Strip the trailing .cpp, .h, inlines.h or -inl.h from a filename."""
376 return (
377 name.replace("inlines.h", "")
378 .replace("-inl.h", "")
379 .replace(".h", "")
380 .replace(".cpp", "")
381 ) # NOQA: E501
384 def is_module_header(enclosing_inclname, header_inclname):
385 """Determine if an included name is the "module header", i.e. should be
386 first in the file."""
388 module = module_name(enclosing_inclname)
390 # Normal case, for example:
391 # module == "vm/Runtime", header_inclname == "vm/Runtime.h".
392 if module == module_name(header_inclname):
393 return True
395 # A public header, for example:
397 # module == "vm/CharacterEncoding",
398 # header_inclname == "js/CharacterEncoding.h"
400 # or (for implementation files for js/public/*/*.h headers)
402 # module == "vm/SourceHook",
403 # header_inclname == "js/experimental/SourceHook.h"
404 m = re.match(r"js\/.*?([^\/]+)\.h", header_inclname)
405 if m is not None and module.endswith("/" + m.group(1)):
406 return True
408 return False
411 class Include(object):
412 """Important information for a single #include statement."""
414 def __init__(self, include_prefix, inclname, line_suffix, linenum, is_system):
415 self.include_prefix = include_prefix
416 self.line_suffix = line_suffix
417 self.inclname = inclname
418 self.linenum = linenum
419 self.is_system = is_system
421 def is_style_relevant(self):
422 # Includes are style-relevant; that is, they're checked by the pairwise
423 # style-checking algorithm in check_file.
424 return True
426 def section(self, enclosing_inclname):
427 """Identify which section inclname belongs to.
429 The section numbers are as follows.
430 0. Module header (e.g. jsfoo.h or jsfooinlines.h within jsfoo.cpp)
431 1. mozilla/Foo.h
432 2. <foo.h> or <foo>
433 3. jsfoo.h, prmjtime.h, etc
434 4. foo/Bar.h
435 5. jsfooinlines.h
436 6. foo/Bar-inl.h
437 7. non-.h, e.g. *.tbl, *.msg (these can be scattered throughout files)
440 if self.is_system:
441 return 2
443 if not self.inclname.endswith(".h"):
444 return 7
446 # A couple of modules have the .h file in js/ and the .cpp file elsewhere and so need
447 # special handling.
448 if is_module_header(enclosing_inclname, self.inclname):
449 return 0
451 if "/" in self.inclname:
452 if self.inclname.startswith("mozilla/"):
453 return 1
455 if self.inclname.endswith("-inl.h"):
456 return 6
458 return 4
460 if self.inclname.endswith("inlines.h"):
461 return 5
463 return 3
465 def quote(self):
466 if self.is_system:
467 return "<" + self.inclname + ">"
468 else:
469 return '"' + self.inclname + '"'
471 def sort_key(self, enclosing_inclname):
472 return (self.section(enclosing_inclname), self.inclname.lower())
474 def to_source(self):
475 return self.include_prefix + self.quote() + self.line_suffix + "\n"
478 class CppBlock(object):
479 """C preprocessor block: a whole file or a single #if/#elif/#else block.
481 A #if/#endif block is the contents of a #if/#endif (or similar) section.
482 The top-level block, which is not within a #if/#endif pair, is also
483 considered a block.
485 Each kid is either an Include (representing a #include), OrdinaryCode, or
486 a nested CppBlock."""
488 def __init__(self, start_line=""):
489 self.start = start_line
490 self.end = ""
491 self.kids = []
493 def is_style_relevant(self):
494 return True
496 def append_ordinary_line(self, line):
497 if len(self.kids) == 0 or not isinstance(self.kids[-1], OrdinaryCode):
498 self.kids.append(OrdinaryCode())
499 self.kids[-1].lines.append(line)
501 def style_relevant_kids(self):
502 """Return a list of kids in this block that are style-relevant."""
503 return [kid for kid in self.kids if kid.is_style_relevant()]
505 def sorted(self, enclosing_inclname):
506 """Return a hopefully-sorted copy of this block. Implements --fixup.
508 When in doubt, this leaves the code unchanged.
511 def pretty_sorted_includes(includes):
512 """Return a new list containing the given includes, in order,
513 with blank lines separating sections."""
514 keys = [inc.sort_key(enclosing_inclname) for inc in includes]
515 if sorted(keys) == keys:
516 return includes # if nothing is out of order, don't touch anything
518 output = []
519 current_section = None
520 for (section, _), inc in sorted(zip(keys, includes)):
521 if current_section is not None and section != current_section:
522 output.append(OrdinaryCode(["\n"])) # blank line
523 output.append(inc)
524 current_section = section
525 return output
527 def should_try_to_sort(includes):
528 if "tests/style/BadIncludes" in enclosing_inclname:
529 return False # don't straighten the counterexample
530 if any(inc.inclname in oddly_ordered_inclnames for inc in includes):
531 return False # don't sort batches containing odd includes
532 if includes == sorted(
533 includes, key=lambda inc: inc.sort_key(enclosing_inclname)
535 return False # it's already sorted, avoid whitespace-only fixups
536 return True
538 # The content of the eventual output of this method.
539 output = []
541 # The current batch of includes to sort. This list only ever contains Include objects
542 # and whitespace OrdinaryCode objects.
543 batch = []
545 def flush_batch():
546 """Sort the contents of `batch` and move it to `output`."""
548 assert all(
549 isinstance(item, Include)
550 or (isinstance(item, OrdinaryCode) and "".join(item.lines).isspace())
551 for item in batch
554 # Here we throw away the blank lines.
555 # `pretty_sorted_includes` puts them back.
556 includes = []
557 last_include_index = -1
558 for i, item in enumerate(batch):
559 if isinstance(item, Include):
560 includes.append(item)
561 last_include_index = i
562 cutoff = last_include_index + 1
564 if should_try_to_sort(includes):
565 output.extend(pretty_sorted_includes(includes) + batch[cutoff:])
566 else:
567 output.extend(batch)
568 del batch[:]
570 for kid in self.kids:
571 if isinstance(kid, CppBlock):
572 flush_batch()
573 output.append(kid.sorted(enclosing_inclname))
574 elif isinstance(kid, Include):
575 batch.append(kid)
576 else:
577 assert isinstance(kid, OrdinaryCode)
578 if kid.to_source().isspace():
579 batch.append(kid)
580 else:
581 flush_batch()
582 output.append(kid)
583 flush_batch()
585 result = CppBlock()
586 result.start = self.start
587 result.end = self.end
588 result.kids = output
589 return result
591 def to_source(self):
592 return self.start + "".join(kid.to_source() for kid in self.kids) + self.end
595 class OrdinaryCode(object):
596 """A list of lines of code that aren't #include/#if/#else/#endif lines."""
598 def __init__(self, lines=None):
599 self.lines = lines if lines is not None else []
601 def is_style_relevant(self):
602 return False
604 def to_source(self):
605 return "".join(self.lines)
608 # A "snippet" is one of:
610 # * Include - representing an #include line
611 # * CppBlock - a whole file or #if/#elif/#else block; contains a list of snippets
612 # * OrdinaryCode - representing lines of non-#include-relevant code
615 def read_file(f):
616 block_stack = [CppBlock()]
618 # Extract the #include statements as a tree of snippets.
619 for linenum, line in enumerate(f, start=1):
620 if line.lstrip().startswith("#"):
621 # Look for a |#include "..."| line.
622 m = re.match(r'(\s*#\s*include\s+)"([^"]*)"(.*)', line)
623 if m is not None:
624 prefix, inclname, suffix = m.groups()
625 block_stack[-1].kids.append(
626 Include(prefix, inclname, suffix, linenum, is_system=False)
628 continue
630 # Look for a |#include <...>| line.
631 m = re.match(r"(\s*#\s*include\s+)<([^>]*)>(.*)", line)
632 if m is not None:
633 prefix, inclname, suffix = m.groups()
634 block_stack[-1].kids.append(
635 Include(prefix, inclname, suffix, linenum, is_system=True)
637 continue
639 # Look for a |#{if,ifdef,ifndef}| line.
640 m = re.match(r"\s*#\s*(if|ifdef|ifndef)\b", line)
641 if m is not None:
642 # Open a new block.
643 new_block = CppBlock(line)
644 block_stack[-1].kids.append(new_block)
645 block_stack.append(new_block)
646 continue
648 # Look for a |#{elif,else}| line.
649 m = re.match(r"\s*#\s*(elif|else)\b", line)
650 if m is not None:
651 # Close the current block, and open an adjacent one.
652 block_stack.pop()
653 new_block = CppBlock(line)
654 block_stack[-1].kids.append(new_block)
655 block_stack.append(new_block)
656 continue
658 # Look for a |#endif| line.
659 m = re.match(r"\s*#\s*endif\b", line)
660 if m is not None:
661 # Close the current block.
662 block_stack.pop().end = line
663 if len(block_stack) == 0:
664 raise ValueError("#endif without #if at line " + str(linenum))
665 continue
667 # Otherwise, we have an ordinary line.
668 block_stack[-1].append_ordinary_line(line)
670 if len(block_stack) > 1:
671 raise ValueError("unmatched #if")
672 return block_stack[-1]
675 def check_file(
676 filename, inclname, file_kind, code, all_inclnames, included_h_inclnames
678 def check_include_statement(include):
679 """Check the style of a single #include statement."""
681 if include.is_system:
682 # Check it is not a known local file (in which case it's probably a system header).
683 if (
684 include.inclname in included_inclnames_to_ignore
685 or include.inclname in all_inclnames
687 error(
688 filename,
689 include.linenum,
690 include.quote() + " should be included using",
691 'the #include "..." form',
694 else:
695 msg = deprecated_inclnames.get(include.inclname)
696 if msg:
697 error(
698 filename,
699 include.linenum,
700 include.quote() + " is deprecated: " + msg,
703 if file_kind == FileKind.H or file_kind == FileKind.INL_H:
704 msg = deprecated_inclnames_in_header.get(include.inclname)
705 if msg and filename not in deprecated_inclnames_in_header_excludes:
706 error(
707 filename,
708 include.linenum,
709 include.quote() + " is deprecated: " + msg,
712 if include.inclname not in included_inclnames_to_ignore:
713 included_kind = FileKind.get(include.inclname)
715 # Check the #include path has the correct form.
716 if include.inclname not in all_inclnames:
717 error(
718 filename,
719 include.linenum,
720 include.quote() + " is included using the wrong path;",
721 "did you forget a prefix, or is the file not yet committed?",
724 # Record inclusions of .h files for cycle detection later.
725 # (Exclude .tbl and .msg files.)
726 elif included_kind == FileKind.H or included_kind == FileKind.INL_H:
727 included_h_inclnames.add(include.inclname)
729 # Check a H file doesn't #include an INL_H file.
730 if file_kind == FileKind.H and included_kind == FileKind.INL_H:
731 error(
732 filename,
733 include.linenum,
734 "vanilla header includes an inline-header file "
735 + include.quote(),
738 # Check a file doesn't #include itself. (We do this here because the cycle
739 # detection below doesn't detect this case.)
740 if inclname == include.inclname:
741 error(filename, include.linenum, "the file includes itself")
743 def check_includes_order(include1, include2):
744 """Check the ordering of two #include statements."""
746 if (
747 include1.inclname in oddly_ordered_inclnames
748 or include2.inclname in oddly_ordered_inclnames
750 return
752 section1 = include1.section(inclname)
753 section2 = include2.section(inclname)
754 if (section1 > section2) or (
755 (section1 == section2)
756 and (include1.inclname.lower() > include2.inclname.lower())
758 error(
759 filename,
760 str(include1.linenum) + ":" + str(include2.linenum),
761 include1.quote() + " should be included after " + include2.quote(),
764 # Check the extracted #include statements, both individually, and the ordering of
765 # adjacent pairs that live in the same block.
766 def pair_traverse(prev, this):
767 if isinstance(this, Include):
768 check_include_statement(this)
769 if isinstance(prev, Include):
770 check_includes_order(prev, this)
771 else:
772 kids = this.style_relevant_kids()
773 for prev2, this2 in zip([None] + kids[0:-1], kids):
774 pair_traverse(prev2, this2)
776 pair_traverse(None, code)
779 def find_cycles(all_inclnames, edges):
780 """Find and draw any cycles."""
782 SCCs = tarjan(all_inclnames, edges)
784 # The various sorted() calls below ensure the output is deterministic.
786 def draw_SCC(c):
787 cset = set(c)
788 drawn = set()
790 def draw(v, indent):
791 out(" " * indent + ("-> " if indent else " ") + v)
792 if v in drawn:
793 return
794 drawn.add(v)
795 for succ in sorted(edges[v]):
796 if succ in cset:
797 draw(succ, indent + 1)
799 draw(sorted(c)[0], 0)
800 out("")
802 have_drawn_an_SCC = False
803 for scc in sorted(SCCs):
804 if len(scc) != 1:
805 if not have_drawn_an_SCC:
806 error("(multiple files)", None, "header files form one or more cycles")
807 have_drawn_an_SCC = True
809 draw_SCC(scc)
812 # Tarjan's algorithm for finding the strongly connected components (SCCs) of a graph.
813 # https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
814 def tarjan(V, E):
815 vertex_index = {}
816 vertex_lowlink = {}
817 index = 0
818 S = []
819 all_SCCs = []
821 def strongconnect(v, index):
822 # Set the depth index for v to the smallest unused index
823 vertex_index[v] = index
824 vertex_lowlink[v] = index
825 index += 1
826 S.append(v)
828 # Consider successors of v
829 for w in E[v]:
830 if w not in vertex_index:
831 # Successor w has not yet been visited; recurse on it
832 index = strongconnect(w, index)
833 vertex_lowlink[v] = min(vertex_lowlink[v], vertex_lowlink[w])
834 elif w in S:
835 # Successor w is in stack S and hence in the current SCC
836 vertex_lowlink[v] = min(vertex_lowlink[v], vertex_index[w])
838 # If v is a root node, pop the stack and generate an SCC
839 if vertex_lowlink[v] == vertex_index[v]:
840 i = S.index(v)
841 scc = S[i:]
842 del S[i:]
843 all_SCCs.append(scc)
845 return index
847 for v in V:
848 if v not in vertex_index:
849 index = strongconnect(v, index)
851 return all_SCCs
854 def main():
855 if sys.argv[1:] == ["--fixup"]:
856 # Sort #include directives in-place. Fixup mode doesn't solve
857 # all possible silliness that the script checks for; it's just a
858 # hack for the common case where renaming a header causes style
859 # errors.
860 fixup = True
861 elif sys.argv[1:] == []:
862 fixup = False
863 else:
864 print(
865 "TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | unexpected command "
866 "line options: " + repr(sys.argv[1:])
868 sys.exit(1)
870 ok = check_style(fixup)
872 if ok:
873 print("TEST-PASS | check_spidermonkey_style.py | ok")
874 else:
875 print(
876 "TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | "
877 + "actual output does not match expected output; diff is above."
879 print(
880 "TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | "
881 + "Hint: If the problem is that you renamed a header, and many #includes "
882 + "are no longer in alphabetical order, commit your work and then try "
883 + "`check_spidermonkey_style.py --fixup`. "
884 + "You need to commit first because --fixup modifies your files in place."
887 sys.exit(0 if ok else 1)
890 if __name__ == "__main__":
891 main()