Bug 1537549 [wpt PR 15932] - Fix splitting of git ls-tree output, a=testonly
[gecko.git] / config / check_spidermonkey_style.py
blob260b00d923abbb804e1e77d887e69c24ccff3767
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 from __future__ import print_function
40 import difflib
41 import os
42 import re
43 import sys
45 # We don't bother checking files in these directories, because they're (a) auxiliary or (b)
46 # imported code that doesn't follow our coding style.
47 ignored_js_src_dirs = [
48 'js/src/config/', # auxiliary stuff
49 'js/src/ctypes/libffi/', # imported code
50 'js/src/devtools/', # auxiliary stuff
51 'js/src/editline/', # imported code
52 'js/src/gdb/', # auxiliary stuff
53 'js/src/vtune/' # imported code
56 # We ignore #includes of these files, because they don't follow the usual rules.
57 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 'gc/StatsPhasesGenerated.h', # generated in $OBJDIR
64 'gc/StatsPhasesGenerated.cpp', # generated in $OBJDIR
65 'jit/LOpcodes.h', # generated in $OBJDIR
66 'jit/MOpcodes.h', # generated in $OBJDIR
67 'jscustomallocator.h', # provided by embedders; allowed to be missing
68 'js-config.h', # generated in $OBJDIR
69 'fdlibm.h', # fdlibm
70 'FuzzerDefs.h', # included without a path
71 'FuzzingInterface.h', # included without a path
72 'mozmemory.h', # included without a path
73 'pratom.h', # NSPR
74 'prcvar.h', # NSPR
75 'prerror.h', # NSPR
76 'prinit.h', # NSPR
77 'prio.h', # NSPR
78 'private/pprio.h', # NSPR
79 'prlink.h', # NSPR
80 'prlock.h', # NSPR
81 'prprf.h', # NSPR
82 'prthread.h', # NSPR
83 'prtypes.h', # NSPR
84 'selfhosted.out.h', # generated in $OBJDIR
85 'shellmoduleloader.out.h', # generated in $OBJDIR
86 'unicode/basictz.h', # ICU
87 'unicode/locid.h', # ICU
88 'unicode/plurrule.h', # ICU
89 'unicode/putil.h', # ICU
90 'unicode/timezone.h', # ICU
91 'unicode/ucal.h', # ICU
92 'unicode/uchar.h', # ICU
93 'unicode/uclean.h', # ICU
94 'unicode/ucol.h', # ICU
95 'unicode/udat.h', # ICU
96 'unicode/udatpg.h', # ICU
97 'unicode/udisplaycontext.h', # ICU
98 'unicode/uenum.h', # ICU
99 'unicode/uloc.h', # ICU
100 'unicode/unistr.h', # ICU
101 'unicode/unorm2.h', # ICU
102 'unicode/unum.h', # ICU
103 'unicode/unumsys.h', # ICU
104 'unicode/upluralrules.h', # ICU
105 'unicode/ureldatefmt.h', # ICU
106 'unicode/ustring.h', # ICU
107 'unicode/utypes.h', # ICU
108 'unicode/uversion.h', # ICU
109 'vtune/VTuneWrapper.h' # VTune
112 # These files have additional constraints on where they are #included, so we
113 # ignore #includes of them when checking #include ordering.
114 oddly_ordered_inclnames = set([
115 'ctypes/typedefs.h', # Included multiple times in the body of ctypes/CTypes.h
116 # Included in the body of frontend/TokenStream.h
117 'frontend/ReservedWordsGenerated.h',
118 'gc/StatsPhasesGenerated.h', # Included in the body of gc/Statistics.h
119 'gc/StatsPhasesGenerated.cpp', # Included in the body of gc/Statistics.cpp
120 'psapi.h', # Must be included after "util/Windows.h" on Windows
121 'machine/endian.h', # Must be included after <sys/types.h> on BSD
122 'winbase.h', # Must precede other system headers(?)
123 'windef.h' # Must precede other system headers(?)
126 # The files in tests/style/ contain code that fails this checking in various
127 # ways. Here is the output we expect. If the actual output differs from
128 # this, one of the following must have happened.
129 # - New SpiderMonkey code violates one of the checked rules.
130 # - The tests/style/ files have changed without expected_output being changed
131 # accordingly.
132 # - This script has been broken somehow.
134 expected_output = '''\
135 js/src/tests/style/BadIncludes.h:3: error:
136 the file includes itself
138 js/src/tests/style/BadIncludes.h:6: error:
139 "BadIncludes2.h" is included using the wrong path;
140 did you forget a prefix, or is the file not yet committed?
142 js/src/tests/style/BadIncludes.h:8: error:
143 <tests/style/BadIncludes2.h> should be included using
144 the #include "..." form
146 js/src/tests/style/BadIncludes.h:10: error:
147 "stdio.h" is included using the wrong path;
148 did you forget a prefix, or is the file not yet committed?
150 js/src/tests/style/BadIncludes2.h:1: error:
151 vanilla header includes an inline-header file "tests/style/BadIncludes2-inl.h"
153 js/src/tests/style/BadIncludesOrder-inl.h:5:6: error:
154 "vm/JSScript-inl.h" should be included after "vm/Interpreter-inl.h"
156 js/src/tests/style/BadIncludesOrder-inl.h:6:7: error:
157 "vm/Interpreter-inl.h" should be included after "js/Value.h"
159 js/src/tests/style/BadIncludesOrder-inl.h:7:8: error:
160 "js/Value.h" should be included after "ds/LifoAlloc.h"
162 js/src/tests/style/BadIncludesOrder-inl.h:8:9: error:
163 "ds/LifoAlloc.h" should be included after "jsapi.h"
165 js/src/tests/style/BadIncludesOrder-inl.h:9:10: error:
166 "jsapi.h" should be included after <stdio.h>
168 js/src/tests/style/BadIncludesOrder-inl.h:10:11: error:
169 <stdio.h> should be included after "mozilla/HashFunctions.h"
171 js/src/tests/style/BadIncludesOrder-inl.h:28:29: error:
172 "vm/JSScript.h" should be included after "vm/JSFunction.h"
174 (multiple files): error:
175 header files form one or more cycles
177 tests/style/HeaderCycleA1.h
178 -> tests/style/HeaderCycleA2.h
179 -> tests/style/HeaderCycleA3.h
180 -> tests/style/HeaderCycleA1.h
182 tests/style/HeaderCycleB1-inl.h
183 -> tests/style/HeaderCycleB2-inl.h
184 -> tests/style/HeaderCycleB3-inl.h
185 -> tests/style/HeaderCycleB4-inl.h
186 -> tests/style/HeaderCycleB1-inl.h
187 -> tests/style/jsheadercycleB5inlines.h
188 -> tests/style/HeaderCycleB1-inl.h
189 -> tests/style/HeaderCycleB4-inl.h
191 '''.splitlines(True)
193 actual_output = []
196 def out(*lines):
197 for line in lines:
198 actual_output.append(line + '\n')
201 def error(filename, linenum, *lines):
202 location = filename
203 if linenum is not None:
204 location += ':' + str(linenum)
205 out(location + ': error:')
206 for line in (lines):
207 out(' ' + line)
208 out('')
211 class FileKind(object):
212 C = 1
213 CPP = 2
214 INL_H = 3
215 H = 4
216 TBL = 5
217 MSG = 6
219 @staticmethod
220 def get(filename):
221 if filename.endswith('.c'):
222 return FileKind.C
224 if filename.endswith('.cpp'):
225 return FileKind.CPP
227 if filename.endswith(('inlines.h', '-inl.h')):
228 return FileKind.INL_H
230 if filename.endswith('.h'):
231 return FileKind.H
233 if filename.endswith('.tbl'):
234 return FileKind.TBL
236 if filename.endswith('.msg'):
237 return FileKind.MSG
239 error(filename, None, 'unknown file kind')
242 def check_style(enable_fixup):
243 # We deal with two kinds of name.
244 # - A "filename" is a full path to a file from the repository root.
245 # - An "inclname" is how a file is referred to in a #include statement.
247 # Examples (filename -> inclname)
248 # - "mfbt/Attributes.h" -> "mozilla/Attributes.h"
249 # - "mfbt/decimal/Decimal.h -> "mozilla/Decimal.h"
250 # - "mozglue/misc/TimeStamp.h -> "mozilla/TimeStamp.h"
251 # - "memory/mozalloc/mozalloc.h -> "mozilla/mozalloc.h"
252 # - "js/public/Vector.h" -> "js/Vector.h"
253 # - "js/src/vm/String.h" -> "vm/String.h"
255 non_js_dirnames = ('mfbt/',
256 'memory/mozalloc/',
257 'mozglue/') # type: tuple(str)
258 non_js_inclnames = set() # type: set(inclname)
259 js_names = dict() # type: dict(filename, inclname)
261 # Process files in js/src.
262 js_src_root = os.path.join('js', 'src')
263 for dirpath, dirnames, filenames in os.walk(js_src_root):
264 if dirpath == js_src_root:
265 # Skip any subdirectories that contain a config.status file
266 # (likely objdirs).
267 builddirs = []
268 for dirname in dirnames:
269 path = os.path.join(dirpath, dirname, 'config.status')
270 if os.path.isfile(path):
271 builddirs.append(dirname)
272 for dirname in builddirs:
273 dirnames.remove(dirname)
274 for filename in filenames:
275 filepath = os.path.join(dirpath, filename).replace('\\', '/')
276 if not filepath.startswith(tuple(ignored_js_src_dirs)) and \
277 filepath.endswith(('.c', '.cpp', '.h', '.tbl', '.msg')):
278 inclname = filepath[len('js/src/'):]
279 js_names[filepath] = inclname
281 # Look for header files in directories in non_js_dirnames.
282 for non_js_dir in non_js_dirnames:
283 for dirpath, dirnames, filenames in os.walk(non_js_dir):
284 for filename in filenames:
285 if filename.endswith('.h'):
286 inclname = 'mozilla/' + filename
287 non_js_inclnames.add(inclname)
289 # Look for header files in js/public.
290 js_public_root = os.path.join('js', 'public')
291 for dirpath, dirnames, filenames in os.walk(js_public_root):
292 for filename in filenames:
293 if filename.endswith('.h'):
294 filepath = os.path.join(dirpath, filename).replace('\\', '/')
295 inclname = 'js/' + filepath[len('js/public/'):]
296 js_names[filepath] = inclname
298 all_inclnames = non_js_inclnames | set(js_names.values())
300 edges = dict() # type: dict(inclname, set(inclname))
302 # We don't care what's inside the MFBT and MOZALLOC files, but because they
303 # are #included from JS files we have to add them to the inclusion graph.
304 for inclname in non_js_inclnames:
305 edges[inclname] = set()
307 # Process all the JS files.
308 for filename in sorted(js_names.keys()):
309 inclname = js_names[filename]
310 file_kind = FileKind.get(filename)
311 if file_kind == FileKind.C or file_kind == FileKind.CPP or \
312 file_kind == FileKind.H or file_kind == FileKind.INL_H:
313 included_h_inclnames = set() # type: set(inclname)
315 with open(filename) as f:
316 code = read_file(f)
318 if enable_fixup:
319 code = code.sorted(inclname)
320 with open(filename, 'w') as f:
321 f.write(code.to_source())
323 check_file(filename, inclname, file_kind, code,
324 all_inclnames, included_h_inclnames)
326 edges[inclname] = included_h_inclnames
328 find_cycles(all_inclnames, edges)
330 # Compare expected and actual output.
331 difflines = difflib.unified_diff(expected_output, actual_output,
332 fromfile='check_spidermonkey_style.py expected output',
333 tofile='check_spidermonkey_style.py actual output')
334 ok = True
335 for diffline in difflines:
336 ok = False
337 print(diffline, end='')
339 return ok
342 def module_name(name):
343 '''Strip the trailing .cpp, .h, inlines.h or -inl.h from a filename.'''
345 return name.replace('inlines.h', '').replace('-inl.h', '').replace('.h', '').replace('.cpp', '') # NOQA: E501
348 def is_module_header(enclosing_inclname, header_inclname):
349 '''Determine if an included name is the "module header", i.e. should be
350 first in the file.'''
352 module = module_name(enclosing_inclname)
354 # Normal case, e.g. module == "foo/Bar", header_inclname == "foo/Bar.h".
355 if module == module_name(header_inclname):
356 return True
358 # A public header, e.g. module == "foo/Bar", header_inclname == "js/Bar.h".
359 m = re.match(r'js\/(.*)\.h', header_inclname)
360 if m is not None and module.endswith('/' + m.group(1)):
361 return True
363 return False
366 class Include(object):
367 '''Important information for a single #include statement.'''
369 def __init__(self, include_prefix, inclname, line_suffix, linenum, is_system):
370 self.include_prefix = include_prefix
371 self.line_suffix = line_suffix
372 self.inclname = inclname
373 self.linenum = linenum
374 self.is_system = is_system
376 def is_style_relevant(self):
377 # Includes are style-relevant; that is, they're checked by the pairwise
378 # style-checking algorithm in check_file.
379 return True
381 def section(self, enclosing_inclname):
382 '''Identify which section inclname belongs to.
384 The section numbers are as follows.
385 0. Module header (e.g. jsfoo.h or jsfooinlines.h within jsfoo.cpp)
386 1. mozilla/Foo.h
387 2. <foo.h> or <foo>
388 3. jsfoo.h, prmjtime.h, etc
389 4. foo/Bar.h
390 5. jsfooinlines.h
391 6. foo/Bar-inl.h
392 7. non-.h, e.g. *.tbl, *.msg
395 if self.is_system:
396 return 2
398 if not self.inclname.endswith('.h'):
399 return 7
401 # A couple of modules have the .h file in js/ and the .cpp file elsewhere and so need
402 # special handling.
403 if is_module_header(enclosing_inclname, self.inclname):
404 return 0
406 if '/' in self.inclname:
407 if self.inclname.startswith('mozilla/'):
408 return 1
410 if self.inclname.endswith('-inl.h'):
411 return 6
413 return 4
415 if self.inclname.endswith('inlines.h'):
416 return 5
418 return 3
420 def quote(self):
421 if self.is_system:
422 return '<' + self.inclname + '>'
423 else:
424 return '"' + self.inclname + '"'
426 def sort_key(self, enclosing_inclname):
427 return (self.section(enclosing_inclname), self.inclname.lower())
429 def to_source(self):
430 return self.include_prefix + self.quote() + self.line_suffix + '\n'
433 class CppBlock(object):
434 '''C preprocessor block: a whole file or a single #if/#elif/#else block.
436 A #if/#endif block is the contents of a #if/#endif (or similar) section.
437 The top-level block, which is not within a #if/#endif pair, is also
438 considered a block.
440 Each kid is either an Include (representing a #include), OrdinaryCode, or
441 a nested CppBlock.'''
443 def __init__(self, start_line=""):
444 self.start = start_line
445 self.end = ''
446 self.kids = []
448 def is_style_relevant(self):
449 return True
451 def append_ordinary_line(self, line):
452 if len(self.kids) == 0 or not isinstance(self.kids[-1], OrdinaryCode):
453 self.kids.append(OrdinaryCode())
454 self.kids[-1].lines.append(line)
456 def style_relevant_kids(self):
457 """ Return a list of kids in this block that are style-relevant. """
458 return [kid for kid in self.kids if kid.is_style_relevant()]
460 def sorted(self, enclosing_inclname):
461 """Return a hopefully-sorted copy of this block. Implements --fixup.
463 When in doubt, this leaves the code unchanged.
466 def pretty_sorted_includes(includes):
467 """ Return a new list containing the given includes, in order,
468 with blank lines separating sections. """
469 keys = [inc.sort_key(enclosing_inclname) for inc in includes]
470 if sorted(keys) == keys:
471 return includes # if nothing is out of order, don't touch anything
473 output = []
474 current_section = None
475 for (section, _), inc in sorted(zip(keys, includes)):
476 if current_section is not None and section != current_section:
477 output.append(OrdinaryCode(["\n"])) # blank line
478 output.append(inc)
479 current_section = section
480 return output
482 def should_try_to_sort(includes):
483 if 'tests/style/BadIncludes' in enclosing_inclname:
484 return False # don't straighten the counterexample
485 if any(inc.inclname in oddly_ordered_inclnames for inc in includes):
486 return False # don't sort batches containing odd includes
487 if includes == sorted(includes, key=lambda inc: inc.sort_key(enclosing_inclname)):
488 return False # it's already sorted, avoid whitespace-only fixups
489 return True
491 # The content of the eventual output of this method.
492 output = []
494 # The current batch of includes to sort. This list only ever contains Include objects
495 # and whitespace OrdinaryCode objects.
496 batch = []
498 def flush_batch():
499 """Sort the contents of `batch` and move it to `output`."""
501 assert all(isinstance(item, Include)
502 or (isinstance(item, OrdinaryCode) and "".join(item.lines).isspace())
503 for item in batch)
505 # Here we throw away the blank lines.
506 # `pretty_sorted_includes` puts them back.
507 includes = []
508 last_include_index = -1
509 for i, item in enumerate(batch):
510 if isinstance(item, Include):
511 includes.append(item)
512 last_include_index = i
513 cutoff = last_include_index + 1
515 if should_try_to_sort(includes):
516 output.extend(pretty_sorted_includes(
517 includes) + batch[cutoff:])
518 else:
519 output.extend(batch)
520 del batch[:]
522 for kid in self.kids:
523 if isinstance(kid, CppBlock):
524 flush_batch()
525 output.append(kid.sorted(enclosing_inclname))
526 elif isinstance(kid, Include):
527 batch.append(kid)
528 else:
529 assert isinstance(kid, OrdinaryCode)
530 if kid.to_source().isspace():
531 batch.append(kid)
532 else:
533 flush_batch()
534 output.append(kid)
535 flush_batch()
537 result = CppBlock()
538 result.start = self.start
539 result.end = self.end
540 result.kids = output
541 return result
543 def to_source(self):
544 return self.start + ''.join(kid.to_source() for kid in self.kids) + self.end
547 class OrdinaryCode(object):
548 ''' A list of lines of code that aren't #include/#if/#else/#endif lines. '''
550 def __init__(self, lines=None):
551 self.lines = lines if lines is not None else []
553 def is_style_relevant(self):
554 return False
556 def to_source(self):
557 return ''.join(self.lines)
560 # A "snippet" is one of:
562 # * Include - representing an #include line
563 # * CppBlock - a whole file or #if/#elif/#else block; contains a list of snippets
564 # * OrdinaryCode - representing lines of non-#include-relevant code
566 def read_file(f):
567 block_stack = [CppBlock()]
569 # Extract the #include statements as a tree of snippets.
570 for linenum, line in enumerate(f, start=1):
571 if line.lstrip().startswith('#'):
572 # Look for a |#include "..."| line.
573 m = re.match(r'(\s*#\s*include\s+)"([^"]*)"(.*)', line)
574 if m is not None:
575 prefix, inclname, suffix = m.groups()
576 block_stack[-1].kids.append(Include(prefix,
577 inclname, suffix, linenum, is_system=False))
578 continue
580 # Look for a |#include <...>| line.
581 m = re.match(r'(\s*#\s*include\s+)<([^>]*)>(.*)', line)
582 if m is not None:
583 prefix, inclname, suffix = m.groups()
584 block_stack[-1].kids.append(Include(prefix,
585 inclname, suffix, linenum, is_system=True))
586 continue
588 # Look for a |#{if,ifdef,ifndef}| line.
589 m = re.match(r'\s*#\s*(if|ifdef|ifndef)\b', line)
590 if m is not None:
591 # Open a new block.
592 new_block = CppBlock(line)
593 block_stack[-1].kids.append(new_block)
594 block_stack.append(new_block)
595 continue
597 # Look for a |#{elif,else}| line.
598 m = re.match(r'\s*#\s*(elif|else)\b', line)
599 if m is not None:
600 # Close the current block, and open an adjacent one.
601 block_stack.pop()
602 new_block = CppBlock(line)
603 block_stack[-1].kids.append(new_block)
604 block_stack.append(new_block)
605 continue
607 # Look for a |#endif| line.
608 m = re.match(r'\s*#\s*endif\b', line)
609 if m is not None:
610 # Close the current block.
611 block_stack.pop().end = line
612 if len(block_stack) == 0:
613 raise ValueError(
614 "#endif without #if at line " + str(linenum))
615 continue
617 # Otherwise, we have an ordinary line.
618 block_stack[-1].append_ordinary_line(line)
620 if len(block_stack) > 1:
621 raise ValueError("unmatched #if")
622 return block_stack[-1]
625 def check_file(filename, inclname, file_kind, code, all_inclnames, included_h_inclnames):
627 def check_include_statement(include):
628 '''Check the style of a single #include statement.'''
630 if include.is_system:
631 # Check it is not a known local file (in which case it's probably a system header).
632 if include.inclname in included_inclnames_to_ignore or \
633 include.inclname in all_inclnames:
634 error(filename, include.linenum,
635 include.quote() + ' should be included using',
636 'the #include "..." form')
638 else:
639 if include.inclname not in included_inclnames_to_ignore:
640 included_kind = FileKind.get(include.inclname)
642 # Check the #include path has the correct form.
643 if include.inclname not in all_inclnames:
644 error(filename, include.linenum,
645 include.quote() + ' is included using the wrong path;',
646 'did you forget a prefix, or is the file not yet committed?')
648 # Record inclusions of .h files for cycle detection later.
649 # (Exclude .tbl and .msg files.)
650 elif included_kind == FileKind.H or included_kind == FileKind.INL_H:
651 included_h_inclnames.add(include.inclname)
653 # Check a H file doesn't #include an INL_H file.
654 if file_kind == FileKind.H and included_kind == FileKind.INL_H:
655 error(filename, include.linenum,
656 'vanilla header includes an inline-header file ' + include.quote())
658 # Check a file doesn't #include itself. (We do this here because the cycle
659 # detection below doesn't detect this case.)
660 if inclname == include.inclname:
661 error(filename, include.linenum,
662 'the file includes itself')
664 def check_includes_order(include1, include2):
665 '''Check the ordering of two #include statements.'''
667 if include1.inclname in oddly_ordered_inclnames or \
668 include2.inclname in oddly_ordered_inclnames:
669 return
671 section1 = include1.section(inclname)
672 section2 = include2.section(inclname)
673 if (section1 > section2) or \
674 ((section1 == section2) and (include1.inclname.lower() > include2.inclname.lower())):
675 error(filename, str(include1.linenum) + ':' + str(include2.linenum),
676 include1.quote() + ' should be included after ' + include2.quote())
678 # Check the extracted #include statements, both individually, and the ordering of
679 # adjacent pairs that live in the same block.
680 def pair_traverse(prev, this):
681 if isinstance(this, Include):
682 check_include_statement(this)
683 if isinstance(prev, Include):
684 check_includes_order(prev, this)
685 else:
686 kids = this.style_relevant_kids()
687 for prev2, this2 in zip([None] + kids[0:-1], kids):
688 pair_traverse(prev2, this2)
690 pair_traverse(None, code)
693 def find_cycles(all_inclnames, edges):
694 '''Find and draw any cycles.'''
696 SCCs = tarjan(all_inclnames, edges)
698 # The various sorted() calls below ensure the output is deterministic.
700 def draw_SCC(c):
701 cset = set(c)
702 drawn = set()
704 def draw(v, indent):
705 out(' ' * indent + ('-> ' if indent else ' ') + v)
706 if v in drawn:
707 return
708 drawn.add(v)
709 for succ in sorted(edges[v]):
710 if succ in cset:
711 draw(succ, indent + 1)
712 draw(sorted(c)[0], 0)
713 out('')
715 have_drawn_an_SCC = False
716 for scc in sorted(SCCs):
717 if len(scc) != 1:
718 if not have_drawn_an_SCC:
719 error('(multiple files)', None,
720 'header files form one or more cycles')
721 have_drawn_an_SCC = True
723 draw_SCC(scc)
726 # Tarjan's algorithm for finding the strongly connected components (SCCs) of a graph.
727 # https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
728 def tarjan(V, E):
729 vertex_index = {}
730 vertex_lowlink = {}
731 index = 0
732 S = []
733 all_SCCs = []
735 def strongconnect(v, index):
736 # Set the depth index for v to the smallest unused index
737 vertex_index[v] = index
738 vertex_lowlink[v] = index
739 index += 1
740 S.append(v)
742 # Consider successors of v
743 for w in E[v]:
744 if w not in vertex_index:
745 # Successor w has not yet been visited; recurse on it
746 index = strongconnect(w, index)
747 vertex_lowlink[v] = min(vertex_lowlink[v], vertex_lowlink[w])
748 elif w in S:
749 # Successor w is in stack S and hence in the current SCC
750 vertex_lowlink[v] = min(vertex_lowlink[v], vertex_index[w])
752 # If v is a root node, pop the stack and generate an SCC
753 if vertex_lowlink[v] == vertex_index[v]:
754 i = S.index(v)
755 scc = S[i:]
756 del S[i:]
757 all_SCCs.append(scc)
759 return index
761 for v in V:
762 if v not in vertex_index:
763 index = strongconnect(v, index)
765 return all_SCCs
768 def main():
769 if sys.argv[1:] == ["--fixup"]:
770 # Sort #include directives in-place. Fixup mode doesn't solve
771 # all possible silliness that the script checks for; it's just a
772 # hack for the common case where renaming a header causes style
773 # errors.
774 fixup = True
775 elif sys.argv[1:] == []:
776 fixup = False
777 else:
778 print("TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | unexpected command "
779 "line options: " + repr(sys.argv[1:]))
780 sys.exit(1)
782 ok = check_style(fixup)
784 if ok:
785 print('TEST-PASS | check_spidermonkey_style.py | ok')
786 else:
787 print('TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | ' +
788 'actual output does not match expected output; diff is above.')
789 print('TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | ' +
790 'Hint: If the problem is that you renamed a header, and many #includes ' +
791 'are no longer in alphabetical order, commit your work and then try ' +
792 '`check_spidermonkey_style.py --fixup`. ' +
793 'You need to commit first because --fixup modifies your files in place.')
795 sys.exit(0 if ok else 1)
798 if __name__ == '__main__':
799 main()