Skip to content

Instantly share code, notes, and snippets.

@jared-hughes
Last active April 27, 2024 12:44
Show Gist options
  • Save jared-hughes/94ded530662632fa643aa39db962beb6 to your computer and use it in GitHub Desktop.
Save jared-hughes/94ded530662632fa643aa39db962beb6 to your computer and use it in GitHub Desktop.
Print out the lengths of switch statements in code
#!/usr/bin/env python3
import sys, re
# Assume space after 'switch' or 'match'
startre = re.compile(r"(\s*)(switch|match) ")
def switch_lengths(filename):
with open(filename, "r") as f:
try:
lines = [*f.readlines()]
except:
print(f"Failed to read file '{filename}'", file=sys.stderr)
return
for i, line in enumerate(lines):
match = re.match(startre, line)
if not match:
continue
indent = match.group(1)
for j in range(i + 1, len(lines)):
subline = lines[j]
if subline.startswith(indent + "}"):
# the length including the `switch(op){` line and the `}` line
print(j - i + 1, f"{filename}:{i+1}-{j+1}")
break
if __name__ == "__main__":
for filename in sys.stdin:
switch_lengths(filename.strip())

Print out the lengths of switch statements in code. Usage example:

find . -type f -name "*.ts" -not -path "*node_modules*" -not -path "*.git*" | ./switch-lengths.py | sort -n -r | head -n 10

Also handles match statements (Rust). Warning: match can be a false positive in languages where switch is a reserved word, and vice versa.

Example output:

$ find esbuild -name "*.go" | ./switch-lengths.py | sort -n -r | head -n 10
2329 esbuild/internal/js_parser/js_parser.go:12778-15106
1248 esbuild/internal/js_printer/js_printer.go:1989-3236
1220 esbuild/internal/js_parser/js_parser.go:6842-8061
1104 esbuild/internal/js_parser/js_parser.go:9971-11074
864 esbuild/pkg/cli/cli_impl.go:94-957
795 esbuild/internal/js_printer/js_printer.go:3993-4787
686 esbuild/internal/js_parser/js_parser.go:4101-4786
617 esbuild/internal/js_lexer/js_lexer.go:1016-1632
600 esbuild/internal/js_parser/js_parser.go:3326-3925
429 esbuild/internal/js_parser/js_parser.go:15287-15715
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment