Bug 1568151 - Replace `target.getInspector()` by `target.getFront("inspector")`....
[gecko.git] / config / check_spidermonkey_style.py
blobeb9004da678247cf2f8edf5dc9b5a6d1eb053d3b
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 absolute_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
54 'js/src/zydis/', # imported code
57 # We ignore #includes of these files, because they don't follow the usual rules.
58 included_inclnames_to_ignore = set([
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/LOpcodes.h', # generated in $OBJDIR
67 'jit/MOpcodes.h', # generated in $OBJDIR
68 'jscustomallocator.h', # provided by embedders; allowed to be missing
69 'js-config.h', # generated in $OBJDIR
70 'fdlibm.h', # fdlibm
71 'FuzzerDefs.h', # included without a path
72 'FuzzingInterface.h', # included without a path
73 'mozmemory.h', # included without a path
74 'pratom.h', # NSPR
75 'prcvar.h', # NSPR
76 'prerror.h', # NSPR
77 'prinit.h', # NSPR
78 'prio.h', # NSPR
79 'private/pprio.h', # NSPR
80 'prlink.h', # NSPR
81 'prlock.h', # NSPR
82 'prprf.h', # NSPR
83 'prthread.h', # NSPR
84 'prtypes.h', # NSPR
85 'selfhosted.out.h', # generated in $OBJDIR
86 'shellmoduleloader.out.h', # generated in $OBJDIR
87 'unicode/basictz.h', # ICU
88 'unicode/locid.h', # ICU
89 'unicode/plurrule.h', # ICU
90 'unicode/putil.h', # ICU
91 'unicode/timezone.h', # ICU
92 'unicode/ucal.h', # ICU
93 'unicode/uchar.h', # ICU
94 'unicode/uclean.h', # ICU
95 'unicode/ucol.h', # ICU
96 'unicode/udat.h', # ICU
97 'unicode/udata.h', # ICU
98 'unicode/udatpg.h', # ICU
99 'unicode/udisplaycontext.h', # ICU
100 'unicode/uenum.h', # ICU
101 'unicode/uformattedvalue.h', # ICU
102 'unicode/uloc.h', # ICU
103 'unicode/unistr.h', # ICU
104 'unicode/unorm2.h', # ICU
105 'unicode/unum.h', # ICU
106 'unicode/unumberformatter.h', # ICU
107 'unicode/unumsys.h', # ICU
108 'unicode/upluralrules.h', # ICU
109 'unicode/ureldatefmt.h', # ICU
110 'unicode/ures.h', # ICU
111 'unicode/ustring.h', # ICU
112 'unicode/utypes.h', # ICU
113 'unicode/uversion.h', # ICU
114 'vtune/VTuneWrapper.h', # VTune
115 'zydis/ZydisAPI.h', # Zydis
118 # These files have additional constraints on where they are #included, so we
119 # ignore #includes of them when checking #include ordering.
120 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/Windows.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(?)
132 # The files in tests/style/ contain code that fails this checking in various
133 # ways. Here is the output we expect. If the actual output differs from
134 # this, one of the following must have happened.
135 # - New SpiderMonkey code violates one of the checked rules.
136 # - The tests/style/ files have changed without expected_output being changed
137 # accordingly.
138 # - This script has been broken somehow.
140 expected_output = '''\
141 js/src/tests/style/BadIncludes.h:3: error:
142 the file includes itself
144 js/src/tests/style/BadIncludes.h:6: error:
145 "BadIncludes2.h" is included using the wrong path;
146 did you forget a prefix, or is the file not yet committed?
148 js/src/tests/style/BadIncludes.h:8: error:
149 <tests/style/BadIncludes2.h> should be included using
150 the #include "..." form
152 js/src/tests/style/BadIncludes.h:10: error:
153 "stdio.h" is included using the wrong path;
154 did you forget a prefix, or is the file not yet committed?
156 js/src/tests/style/BadIncludes2.h:1: error:
157 vanilla header includes an inline-header file "tests/style/BadIncludes2-inl.h"
159 js/src/tests/style/BadIncludesOrder-inl.h:5:6: error:
160 "vm/JSScript-inl.h" should be included after "vm/Interpreter-inl.h"
162 js/src/tests/style/BadIncludesOrder-inl.h:6:7: error:
163 "vm/Interpreter-inl.h" should be included after "js/Value.h"
165 js/src/tests/style/BadIncludesOrder-inl.h:7:8: error:
166 "js/Value.h" should be included after "ds/LifoAlloc.h"
168 js/src/tests/style/BadIncludesOrder-inl.h:8:9: error:
169 "ds/LifoAlloc.h" should be included after "jsapi.h"
171 js/src/tests/style/BadIncludesOrder-inl.h:9:10: error:
172 "jsapi.h" should be included after <stdio.h>
174 js/src/tests/style/BadIncludesOrder-inl.h:10:11: error:
175 <stdio.h> should be included after "mozilla/HashFunctions.h"
177 js/src/tests/style/BadIncludesOrder-inl.h:28:29: error:
178 "vm/JSScript.h" should be included after "vm/JSFunction.h"
180 (multiple files): error:
181 header files form one or more cycles
183 tests/style/HeaderCycleA1.h
184 -> tests/style/HeaderCycleA2.h
185 -> tests/style/HeaderCycleA3.h
186 -> tests/style/HeaderCycleA1.h
188 tests/style/HeaderCycleB1-inl.h
189 -> tests/style/HeaderCycleB2-inl.h
190 -> tests/style/HeaderCycleB3-inl.h
191 -> tests/style/HeaderCycleB4-inl.h
192 -> tests/style/HeaderCycleB1-inl.h
193 -> tests/style/jsheadercycleB5inlines.h
194 -> tests/style/HeaderCycleB1-inl.h
195 -> tests/style/HeaderCycleB4-inl.h
197 '''.splitlines(True)
199 actual_output = []
202 def out(*lines):
203 for line in lines:
204 actual_output.append(line + '\n')
207 def error(filename, linenum, *lines):
208 location = filename
209 if linenum is not None:
210 location += ':' + str(linenum)
211 out(location + ': error:')
212 for line in (lines):
213 out(' ' + line)
214 out('')
217 class FileKind(object):
218 C = 1
219 CPP = 2
220 INL_H = 3
221 H = 4
222 TBL = 5
223 MSG = 6
225 @staticmethod
226 def get(filename):
227 if filename.endswith('.c'):
228 return FileKind.C
230 if filename.endswith('.cpp'):
231 return FileKind.CPP
233 if filename.endswith(('inlines.h', '-inl.h')):
234 return FileKind.INL_H
236 if filename.endswith('.h'):
237 return FileKind.H
239 if filename.endswith('.tbl'):
240 return FileKind.TBL
242 if filename.endswith('.msg'):
243 return FileKind.MSG
245 error(filename, None, 'unknown file kind')
248 def check_style(enable_fixup):
249 # We deal with two kinds of name.
250 # - A "filename" is a full path to a file from the repository root.
251 # - An "inclname" is how a file is referred to in a #include statement.
253 # Examples (filename -> inclname)
254 # - "mfbt/Attributes.h" -> "mozilla/Attributes.h"
255 # - "mozglue/misc/TimeStamp.h -> "mozilla/TimeStamp.h"
256 # - "memory/mozalloc/mozalloc.h -> "mozilla/mozalloc.h"
257 # - "js/public/Vector.h" -> "js/Vector.h"
258 # - "js/src/vm/String.h" -> "vm/String.h"
260 non_js_dirnames = ('mfbt/',
261 'memory/mozalloc/',
262 'mozglue/') # type: tuple(str)
263 non_js_inclnames = set() # type: set(inclname)
264 js_names = dict() # type: dict(filename, inclname)
266 # Process files in js/src.
267 js_src_root = os.path.join('js', 'src')
268 for dirpath, dirnames, filenames in os.walk(js_src_root):
269 if dirpath == js_src_root:
270 # Skip any subdirectories that contain a config.status file
271 # (likely objdirs).
272 builddirs = []
273 for dirname in dirnames:
274 path = os.path.join(dirpath, dirname, 'config.status')
275 if os.path.isfile(path):
276 builddirs.append(dirname)
277 for dirname in builddirs:
278 dirnames.remove(dirname)
279 for filename in filenames:
280 filepath = os.path.join(dirpath, filename).replace('\\', '/')
281 if not filepath.startswith(tuple(ignored_js_src_dirs)) and \
282 filepath.endswith(('.c', '.cpp', '.h', '.tbl', '.msg')):
283 inclname = filepath[len('js/src/'):]
284 js_names[filepath] = inclname
286 # Look for header files in directories in non_js_dirnames.
287 for non_js_dir in non_js_dirnames:
288 for dirpath, dirnames, filenames in os.walk(non_js_dir):
289 for filename in filenames:
290 if filename.endswith('.h'):
291 inclname = 'mozilla/' + filename
292 non_js_inclnames.add(inclname)
294 # Look for header files in js/public.
295 js_public_root = os.path.join('js', 'public')
296 for dirpath, dirnames, filenames in os.walk(js_public_root):
297 for filename in filenames:
298 if filename.endswith('.h'):
299 filepath = os.path.join(dirpath, filename).replace('\\', '/')
300 inclname = 'js/' + filepath[len('js/public/'):]
301 js_names[filepath] = inclname
303 all_inclnames = non_js_inclnames | set(js_names.values())
305 edges = dict() # type: dict(inclname, set(inclname))
307 # We don't care what's inside the MFBT and MOZALLOC files, but because they
308 # are #included from JS files we have to add them to the inclusion graph.
309 for inclname in non_js_inclnames:
310 edges[inclname] = set()
312 # Process all the JS files.
313 for filename in sorted(js_names.keys()):
314 inclname = js_names[filename]
315 file_kind = FileKind.get(filename)
316 if file_kind == FileKind.C or file_kind == FileKind.CPP or \
317 file_kind == FileKind.H or file_kind == FileKind.INL_H:
318 included_h_inclnames = set() # type: set(inclname)
320 with open(filename) as f:
321 code = read_file(f)
323 if enable_fixup:
324 code = code.sorted(inclname)
325 with open(filename, 'w') as f:
326 f.write(code.to_source())
328 check_file(filename, inclname, file_kind, code,
329 all_inclnames, included_h_inclnames)
331 edges[inclname] = included_h_inclnames
333 find_cycles(all_inclnames, edges)
335 # Compare expected and actual output.
336 difflines = difflib.unified_diff(expected_output, actual_output,
337 fromfile='check_spidermonkey_style.py expected output',
338 tofile='check_spidermonkey_style.py actual output')
339 ok = True
340 for diffline in difflines:
341 ok = False
342 print(diffline, end='')
344 return ok
347 def module_name(name):
348 '''Strip the trailing .cpp, .h, inlines.h or -inl.h from a filename.'''
350 return name.replace('inlines.h', '').replace('-inl.h', '').replace('.h', '').replace('.cpp', '') # NOQA: E501
353 def is_module_header(enclosing_inclname, header_inclname):
354 '''Determine if an included name is the "module header", i.e. should be
355 first in the file.'''
357 module = module_name(enclosing_inclname)
359 # Normal case, e.g. module == "foo/Bar", header_inclname == "foo/Bar.h".
360 if module == module_name(header_inclname):
361 return True
363 # A public header, e.g. module == "foo/Bar", header_inclname == "js/Bar.h".
364 m = re.match(r'js\/(.*)\.h', header_inclname)
365 if m is not None and module.endswith('/' + m.group(1)):
366 return True
368 return False
371 class Include(object):
372 '''Important information for a single #include statement.'''
374 def __init__(self, include_prefix, inclname, line_suffix, linenum, is_system):
375 self.include_prefix = include_prefix
376 self.line_suffix = line_suffix
377 self.inclname = inclname
378 self.linenum = linenum
379 self.is_system = is_system
381 def is_style_relevant(self):
382 # Includes are style-relevant; that is, they're checked by the pairwise
383 # style-checking algorithm in check_file.
384 return True
386 def section(self, enclosing_inclname):
387 '''Identify which section inclname belongs to.
389 The section numbers are as follows.
390 0. Module header (e.g. jsfoo.h or jsfooinlines.h within jsfoo.cpp)
391 1. mozilla/Foo.h
392 2. <foo.h> or <foo>
393 3. jsfoo.h, prmjtime.h, etc
394 4. foo/Bar.h
395 5. jsfooinlines.h
396 6. foo/Bar-inl.h
397 7. non-.h, e.g. *.tbl, *.msg
400 if self.is_system:
401 return 2
403 if not self.inclname.endswith('.h'):
404 return 7
406 # A couple of modules have the .h file in js/ and the .cpp file elsewhere and so need
407 # special handling.
408 if is_module_header(enclosing_inclname, self.inclname):
409 return 0
411 if '/' in self.inclname:
412 if self.inclname.startswith('mozilla/'):
413 return 1
415 if self.inclname.endswith('-inl.h'):
416 return 6
418 return 4
420 if self.inclname.endswith('inlines.h'):
421 return 5
423 return 3
425 def quote(self):
426 if self.is_system:
427 return '<' + self.inclname + '>'
428 else:
429 return '"' + self.inclname + '"'
431 def sort_key(self, enclosing_inclname):
432 return (self.section(enclosing_inclname), self.inclname.lower())
434 def to_source(self):
435 return self.include_prefix + self.quote() + self.line_suffix + '\n'
438 class CppBlock(object):
439 '''C preprocessor block: a whole file or a single #if/#elif/#else block.
441 A #if/#endif block is the contents of a #if/#endif (or similar) section.
442 The top-level block, which is not within a #if/#endif pair, is also
443 considered a block.
445 Each kid is either an Include (representing a #include), OrdinaryCode, or
446 a nested CppBlock.'''
448 def __init__(self, start_line=""):
449 self.start = start_line
450 self.end = ''
451 self.kids = []
453 def is_style_relevant(self):
454 return True
456 def append_ordinary_line(self, line):
457 if len(self.kids) == 0 or not isinstance(self.kids[-1], OrdinaryCode):
458 self.kids.append(OrdinaryCode())
459 self.kids[-1].lines.append(line)
461 def style_relevant_kids(self):
462 """ Return a list of kids in this block that are style-relevant. """
463 return [kid for kid in self.kids if kid.is_style_relevant()]
465 def sorted(self, enclosing_inclname):
466 """Return a hopefully-sorted copy of this block. Implements --fixup.
468 When in doubt, this leaves the code unchanged.
471 def pretty_sorted_includes(includes):
472 """ Return a new list containing the given includes, in order,
473 with blank lines separating sections. """
474 keys = [inc.sort_key(enclosing_inclname) for inc in includes]
475 if sorted(keys) == keys:
476 return includes # if nothing is out of order, don't touch anything
478 output = []
479 current_section = None
480 for (section, _), inc in sorted(zip(keys, includes)):
481 if current_section is not None and section != current_section:
482 output.append(OrdinaryCode(["\n"])) # blank line
483 output.append(inc)
484 current_section = section
485 return output
487 def should_try_to_sort(includes):
488 if 'tests/style/BadIncludes' in enclosing_inclname:
489 return False # don't straighten the counterexample
490 if any(inc.inclname in oddly_ordered_inclnames for inc in includes):
491 return False # don't sort batches containing odd includes
492 if includes == sorted(includes, key=lambda inc: inc.sort_key(enclosing_inclname)):
493 return False # it's already sorted, avoid whitespace-only fixups
494 return True
496 # The content of the eventual output of this method.
497 output = []
499 # The current batch of includes to sort. This list only ever contains Include objects
500 # and whitespace OrdinaryCode objects.
501 batch = []
503 def flush_batch():
504 """Sort the contents of `batch` and move it to `output`."""
506 assert all(isinstance(item, Include)
507 or (isinstance(item, OrdinaryCode) and "".join(item.lines).isspace())
508 for item in batch)
510 # Here we throw away the blank lines.
511 # `pretty_sorted_includes` puts them back.
512 includes = []
513 last_include_index = -1
514 for i, item in enumerate(batch):
515 if isinstance(item, Include):
516 includes.append(item)
517 last_include_index = i
518 cutoff = last_include_index + 1
520 if should_try_to_sort(includes):
521 output.extend(pretty_sorted_includes(
522 includes) + batch[cutoff:])
523 else:
524 output.extend(batch)
525 del batch[:]
527 for kid in self.kids:
528 if isinstance(kid, CppBlock):
529 flush_batch()
530 output.append(kid.sorted(enclosing_inclname))
531 elif isinstance(kid, Include):
532 batch.append(kid)
533 else:
534 assert isinstance(kid, OrdinaryCode)
535 if kid.to_source().isspace():
536 batch.append(kid)
537 else:
538 flush_batch()
539 output.append(kid)
540 flush_batch()
542 result = CppBlock()
543 result.start = self.start
544 result.end = self.end
545 result.kids = output
546 return result
548 def to_source(self):
549 return self.start + ''.join(kid.to_source() for kid in self.kids) + self.end
552 class OrdinaryCode(object):
553 ''' A list of lines of code that aren't #include/#if/#else/#endif lines. '''
555 def __init__(self, lines=None):
556 self.lines = lines if lines is not None else []
558 def is_style_relevant(self):
559 return False
561 def to_source(self):
562 return ''.join(self.lines)
565 # A "snippet" is one of:
567 # * Include - representing an #include line
568 # * CppBlock - a whole file or #if/#elif/#else block; contains a list of snippets
569 # * OrdinaryCode - representing lines of non-#include-relevant code
571 def read_file(f):
572 block_stack = [CppBlock()]
574 # Extract the #include statements as a tree of snippets.
575 for linenum, line in enumerate(f, start=1):
576 if line.lstrip().startswith('#'):
577 # Look for a |#include "..."| line.
578 m = re.match(r'(\s*#\s*include\s+)"([^"]*)"(.*)', line)
579 if m is not None:
580 prefix, inclname, suffix = m.groups()
581 block_stack[-1].kids.append(Include(prefix,
582 inclname, suffix, linenum, is_system=False))
583 continue
585 # Look for a |#include <...>| line.
586 m = re.match(r'(\s*#\s*include\s+)<([^>]*)>(.*)', line)
587 if m is not None:
588 prefix, inclname, suffix = m.groups()
589 block_stack[-1].kids.append(Include(prefix,
590 inclname, suffix, linenum, is_system=True))
591 continue
593 # Look for a |#{if,ifdef,ifndef}| line.
594 m = re.match(r'\s*#\s*(if|ifdef|ifndef)\b', line)
595 if m is not None:
596 # Open a new block.
597 new_block = CppBlock(line)
598 block_stack[-1].kids.append(new_block)
599 block_stack.append(new_block)
600 continue
602 # Look for a |#{elif,else}| line.
603 m = re.match(r'\s*#\s*(elif|else)\b', line)
604 if m is not None:
605 # Close the current block, and open an adjacent one.
606 block_stack.pop()
607 new_block = CppBlock(line)
608 block_stack[-1].kids.append(new_block)
609 block_stack.append(new_block)
610 continue
612 # Look for a |#endif| line.
613 m = re.match(r'\s*#\s*endif\b', line)
614 if m is not None:
615 # Close the current block.
616 block_stack.pop().end = line
617 if len(block_stack) == 0:
618 raise ValueError(
619 "#endif without #if at line " + str(linenum))
620 continue
622 # Otherwise, we have an ordinary line.
623 block_stack[-1].append_ordinary_line(line)
625 if len(block_stack) > 1:
626 raise ValueError("unmatched #if")
627 return block_stack[-1]
630 def check_file(filename, inclname, file_kind, code, all_inclnames, included_h_inclnames):
632 def check_include_statement(include):
633 '''Check the style of a single #include statement.'''
635 if include.is_system:
636 # Check it is not a known local file (in which case it's probably a system header).
637 if include.inclname in included_inclnames_to_ignore or \
638 include.inclname in all_inclnames:
639 error(filename, include.linenum,
640 include.quote() + ' should be included using',
641 'the #include "..." form')
643 else:
644 if include.inclname not in included_inclnames_to_ignore:
645 included_kind = FileKind.get(include.inclname)
647 # Check the #include path has the correct form.
648 if include.inclname not in all_inclnames:
649 error(filename, include.linenum,
650 include.quote() + ' is included using the wrong path;',
651 'did you forget a prefix, or is the file not yet committed?')
653 # Record inclusions of .h files for cycle detection later.
654 # (Exclude .tbl and .msg files.)
655 elif included_kind == FileKind.H or included_kind == FileKind.INL_H:
656 included_h_inclnames.add(include.inclname)
658 # Check a H file doesn't #include an INL_H file.
659 if file_kind == FileKind.H and included_kind == FileKind.INL_H:
660 error(filename, include.linenum,
661 'vanilla header includes an inline-header file ' + include.quote())
663 # Check a file doesn't #include itself. (We do this here because the cycle
664 # detection below doesn't detect this case.)
665 if inclname == include.inclname:
666 error(filename, include.linenum,
667 'the file includes itself')
669 def check_includes_order(include1, include2):
670 '''Check the ordering of two #include statements.'''
672 if include1.inclname in oddly_ordered_inclnames or \
673 include2.inclname in oddly_ordered_inclnames:
674 return
676 section1 = include1.section(inclname)
677 section2 = include2.section(inclname)
678 if (section1 > section2) or \
679 ((section1 == section2) and (include1.inclname.lower() > include2.inclname.lower())):
680 error(filename, str(include1.linenum) + ':' + str(include2.linenum),
681 include1.quote() + ' should be included after ' + include2.quote())
683 # Check the extracted #include statements, both individually, and the ordering of
684 # adjacent pairs that live in the same block.
685 def pair_traverse(prev, this):
686 if isinstance(this, Include):
687 check_include_statement(this)
688 if isinstance(prev, Include):
689 check_includes_order(prev, this)
690 else:
691 kids = this.style_relevant_kids()
692 for prev2, this2 in zip([None] + kids[0:-1], kids):
693 pair_traverse(prev2, this2)
695 pair_traverse(None, code)
698 def find_cycles(all_inclnames, edges):
699 '''Find and draw any cycles.'''
701 SCCs = tarjan(all_inclnames, edges)
703 # The various sorted() calls below ensure the output is deterministic.
705 def draw_SCC(c):
706 cset = set(c)
707 drawn = set()
709 def draw(v, indent):
710 out(' ' * indent + ('-> ' if indent else ' ') + v)
711 if v in drawn:
712 return
713 drawn.add(v)
714 for succ in sorted(edges[v]):
715 if succ in cset:
716 draw(succ, indent + 1)
717 draw(sorted(c)[0], 0)
718 out('')
720 have_drawn_an_SCC = False
721 for scc in sorted(SCCs):
722 if len(scc) != 1:
723 if not have_drawn_an_SCC:
724 error('(multiple files)', None,
725 'header files form one or more cycles')
726 have_drawn_an_SCC = True
728 draw_SCC(scc)
731 # Tarjan's algorithm for finding the strongly connected components (SCCs) of a graph.
732 # https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
733 def tarjan(V, E):
734 vertex_index = {}
735 vertex_lowlink = {}
736 index = 0
737 S = []
738 all_SCCs = []
740 def strongconnect(v, index):
741 # Set the depth index for v to the smallest unused index
742 vertex_index[v] = index
743 vertex_lowlink[v] = index
744 index += 1
745 S.append(v)
747 # Consider successors of v
748 for w in E[v]:
749 if w not in vertex_index:
750 # Successor w has not yet been visited; recurse on it
751 index = strongconnect(w, index)
752 vertex_lowlink[v] = min(vertex_lowlink[v], vertex_lowlink[w])
753 elif w in S:
754 # Successor w is in stack S and hence in the current SCC
755 vertex_lowlink[v] = min(vertex_lowlink[v], vertex_index[w])
757 # If v is a root node, pop the stack and generate an SCC
758 if vertex_lowlink[v] == vertex_index[v]:
759 i = S.index(v)
760 scc = S[i:]
761 del S[i:]
762 all_SCCs.append(scc)
764 return index
766 for v in V:
767 if v not in vertex_index:
768 index = strongconnect(v, index)
770 return all_SCCs
773 def main():
774 if sys.argv[1:] == ["--fixup"]:
775 # Sort #include directives in-place. Fixup mode doesn't solve
776 # all possible silliness that the script checks for; it's just a
777 # hack for the common case where renaming a header causes style
778 # errors.
779 fixup = True
780 elif sys.argv[1:] == []:
781 fixup = False
782 else:
783 print("TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | unexpected command "
784 "line options: " + repr(sys.argv[1:]))
785 sys.exit(1)
787 ok = check_style(fixup)
789 if ok:
790 print('TEST-PASS | check_spidermonkey_style.py | ok')
791 else:
792 print('TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | ' +
793 'actual output does not match expected output; diff is above.')
794 print('TEST-UNEXPECTED-FAIL | check_spidermonkey_style.py | ' +
795 'Hint: If the problem is that you renamed a header, and many #includes ' +
796 'are no longer in alphabetical order, commit your work and then try ' +
797 '`check_spidermonkey_style.py --fixup`. ' +
798 'You need to commit first because --fixup modifies your files in place.')
800 sys.exit(0 if ok else 1)
803 if __name__ == '__main__':
804 main()