| 1 |
#!/usr/bin/env python |
| 2 |
""" |
| 3 |
Count number of references to tokens in lexer source |
| 4 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 5 |
|
| 6 |
:program:`count_token_references` counts how many references to all existing |
| 7 |
tokens it can find by "grepping" the the source code of the lexers. This can |
| 8 |
be used to find typos in token names, as those tokens are only used by one lexer. |
| 9 |
|
| 10 |
:program:`count_token_references` supports the following options: |
| 11 |
|
| 12 |
.. program:: count_token_references |
| 13 |
|
| 14 |
.. option:: -v, --verbose |
| 15 |
This gives output while the script is collecting information. |
| 16 |
|
| 17 |
.. option:: --minfiles <COUNT> |
| 18 |
Only report about tokens that are referenced in at least this many lexer |
| 19 |
source files (default 1). |
| 20 |
|
| 21 |
.. option:: --maxfiles <COUNT> |
| 22 |
Only report about tokens that are referenced in at most this many lexer |
| 23 |
source files (default 1). |
| 24 |
|
| 25 |
.. option:: --minlines <COUNT> |
| 26 |
Only report about tokens that are referenced in at least this many lexer |
| 27 |
source lines (default 1). |
| 28 |
|
| 29 |
.. option:: --maxlines <COUNT> |
| 30 |
Only report about tokens that are referenced in at most this many lexer |
| 31 |
source lines (default 10). |
| 32 |
|
| 33 |
.. option:: -s, --subtokens |
| 34 |
When ``--subtoken`` is given each token is also counted for each of its |
| 35 |
parent tokens. I.e. if we have 10 occurrences of the token |
| 36 |
``Token.Literal.Number.Integer`` and 10 occurrences of the token |
| 37 |
``Token.Literal.Number.Hex`` but none for ``Token.Literal.Number``, with |
| 38 |
``--subtoken`` ``Token.Literal.Number`` would be counted as having |
| 39 |
20 references. |
| 40 |
""" |
| 41 |
|
| 42 |
import argparse |
| 43 |
import pathlib |
| 44 |
import re |
| 45 |
import sys |
| 46 |
|
| 47 |
from pygments import token, lexers |
| 48 |
|
| 49 |
|
| 50 |
def lookup_all_lexers(): |
| 51 |
""" |
| 52 |
Iterate through all lexers and fetch them. |
| 53 |
This should create all tokens that any of the lexers produce. |
| 54 |
""" |
| 55 |
count = 0 |
| 56 |
for (_, aliases, patterns, mimetypes) in lexers.get_all_lexers(): |
| 57 |
for alias in aliases: |
| 58 |
_ = lexers.get_lexer_by_name(alias) |
| 59 |
break |
| 60 |
else: |
| 61 |
for pattern in patterns: |
| 62 |
_ = lexers.get_lexer_for_filename(pattern) |
| 63 |
break |
| 64 |
else: |
| 65 |
for mimetype in mimetypes: |
| 66 |
_ = lexers.get_lexer_for_mimetype(mimetype) |
| 67 |
break |
| 68 |
count += 1 |
| 69 |
return count |
| 70 |
|
| 71 |
|
| 72 |
def fetch_lexer_sources(): |
| 73 |
""" |
| 74 |
Return the source code of all lexers as a dictionary, mapping filenames |
| 75 |
to a list of lines. |
| 76 |
""" |
| 77 |
lexer_dir = pathlib.Path(__file__).parent / "../pygments/lexers" |
| 78 |
lexer_dir = lexer_dir.resolve() |
| 79 |
lexer_sources = { |
| 80 |
fn: fn.read_text(encoding='utf-8').splitlines(keepends=False) |
| 81 |
for fn in lexer_dir.glob("*.py") |
| 82 |
} |
| 83 |
return lexer_sources |
| 84 |
|
| 85 |
|
| 86 |
def sub_tokens(token): |
| 87 |
""" |
| 88 |
Generator that yields a token and all of its sub-tokens recursively. |
| 89 |
""" |
| 90 |
yield token |
| 91 |
for subtoken in token.subtypes: |
| 92 |
yield from sub_tokens(subtoken) |
| 93 |
|
| 94 |
|
| 95 |
class FileCount: |
| 96 |
""" |
| 97 |
Stores information about line numbers in a file. |
| 98 |
|
| 99 |
This is used to store from which lines in a files a certain token is |
| 100 |
referenced. |
| 101 |
""" |
| 102 |
def __init__(self, filename): |
| 103 |
self.filename = filename |
| 104 |
self.lines = [] |
| 105 |
|
| 106 |
def __str__(self): |
| 107 |
if len(self.lines) > 3: |
| 108 |
lines = ", ".join(f"{line}" for line in self.lines[:5]) |
| 109 |
lines = f"{lines}, ... ({len(lines):,} lines)" |
| 110 |
else: |
| 111 |
lines = ", ".join(f"{line}" for line in self.lines) |
| 112 |
return f"{self.filename.name}[{lines}]" |
| 113 |
|
| 114 |
def add(self, linenumber): |
| 115 |
self.lines.append(linenumber) |
| 116 |
|
| 117 |
def count_lines(self): |
| 118 |
return len(self.lines) |
| 119 |
|
| 120 |
|
| 121 |
class TokenCount: |
| 122 |
""" |
| 123 |
Stores information about a token and in which files it is referenced. |
| 124 |
""" |
| 125 |
def __init__(self, token): |
| 126 |
self.token = token |
| 127 |
self.files = {} |
| 128 |
|
| 129 |
def add(self, filename, linenumber): |
| 130 |
if filename not in self.files: |
| 131 |
self.files[filename] = FileCount(filename) |
| 132 |
self.files[filename].add(linenumber) |
| 133 |
|
| 134 |
def __str__(self): |
| 135 |
if len(self.files) > 3: |
| 136 |
files = [] |
| 137 |
for (i, filecount) in enumerate(self.files.values()): |
| 138 |
files.append(str(filecount)) |
| 139 |
if i >= 5: |
| 140 |
break |
| 141 |
files = ", ".join(files) + f", ... ({len(self.files):,} files)" |
| 142 |
else: |
| 143 |
files = ", ".join(str(filecount) for filecount in self.files.values()) |
| 144 |
return f"{self.count_files():,} files, {self.count_lines():,} locations: {files}" |
| 145 |
|
| 146 |
def count_files(self): |
| 147 |
return len(self.files) |
| 148 |
|
| 149 |
def count_lines(self): |
| 150 |
return sum(fc.count_lines() for fc in self.files.values()) |
| 151 |
|
| 152 |
|
| 153 |
def find_token_references(lexer_sources, args): |
| 154 |
""" |
| 155 |
Find all references to all tokens in the source code of all lexers. |
| 156 |
|
| 157 |
Note that this can't be 100% reliable, as it searches the source code for |
| 158 |
certain patterns: It searches for the last two components of a token name, |
| 159 |
i.e. to find references to the token ``Token.Literal.Number.Integer.Long`` |
| 160 |
it searches for the regular expression ``\\bInteger.Long\\b``. This |
| 161 |
won't work reliably for top level token like ``Token.String`` since this |
| 162 |
is often referred to as ``String``, but searching for ``\\bString\\b`` |
| 163 |
yields too many false positives. |
| 164 |
""" |
| 165 |
|
| 166 |
# Maps token to :class:`TokenCount` objects. |
| 167 |
token_references = {} |
| 168 |
|
| 169 |
# Search for each token in each lexer source file and record in which file |
| 170 |
# and in which line they are referenced |
| 171 |
for t in sub_tokens(token.Token): |
| 172 |
parts = list(t)[-2:] |
| 173 |
if len(parts) == 0: |
| 174 |
name = "Token" |
| 175 |
elif len(parts) == 1: |
| 176 |
name = f"Token.{parts[0]}" |
| 177 |
else: |
| 178 |
name = ".".join(parts) |
| 179 |
|
| 180 |
token_references[t] = tokencount = TokenCount(t) |
| 181 |
|
| 182 |
if name != "Token": |
| 183 |
pattern = re.compile(f"\\b{name}\\b") |
| 184 |
|
| 185 |
for (filename, sourcelines) in lexer_sources.items(): |
| 186 |
for (i, line) in enumerate(sourcelines, 1): |
| 187 |
if pattern.search(line) is not None: |
| 188 |
tokencount.add(filename, i) |
| 189 |
if args.subtoken: |
| 190 |
t2 = t |
| 191 |
while t2 is not token.Token: |
| 192 |
t2 = t2.parent |
| 193 |
tokencount2 = token_references[t2] |
| 194 |
tokencount2.add(filename, i) |
| 195 |
|
| 196 |
return token_references |
| 197 |
|
| 198 |
|
| 199 |
def print_result(token_references, args): |
| 200 |
def key(item): |
| 201 |
return (item[1].count_files(), item[1].count_lines()) |
| 202 |
|
| 203 |
for (tok, locations) in sorted(token_references.items(), key=key): |
| 204 |
if args.minfiles <= locations.count_files() <= args.maxfiles and \ |
| 205 |
args.minlines <= locations.count_lines() <= args.maxlines: |
| 206 |
print(f"{tok}: {locations}") |
| 207 |
|
| 208 |
|
| 209 |
def main(args=None): |
| 210 |
p = argparse.ArgumentParser(description="Count how often each token is used by the lexers") |
| 211 |
p.add_argument( |
| 212 |
"-v", "--verbose", |
| 213 |
dest="verbose", help="Give more output.", |
| 214 |
default=False, action="store_true" |
| 215 |
) |
| 216 |
p.add_argument( |
| 217 |
"--minfiles", |
| 218 |
dest="minfiles", metavar="COUNT", type=int, |
| 219 |
help="Report all tokens referenced by at least COUNT lexer source files (default %(default)s)", |
| 220 |
default=1 |
| 221 |
) |
| 222 |
p.add_argument( |
| 223 |
"--maxfiles", |
| 224 |
dest="maxfiles", metavar="COUNT", type=int, |
| 225 |
help="Report all tokens referenced by at most COUNT lexer source files (default %(default)s)", |
| 226 |
default=1 |
| 227 |
) |
| 228 |
p.add_argument( |
| 229 |
"--minlines", |
| 230 |
dest="minlines", metavar="COUNT", type=int, |
| 231 |
help="Report all tokens referenced by at least COUNT lexer source lines (default %(default)s)", |
| 232 |
default=1 |
| 233 |
) |
| 234 |
p.add_argument( |
| 235 |
"--maxlines", |
| 236 |
dest="maxlines", metavar="COUNT", type=int, |
| 237 |
help="Report all tokens referenced by at most COUNT lexer source lines (default %(default)s)", |
| 238 |
default=10 |
| 239 |
) |
| 240 |
p.add_argument( |
| 241 |
"-s", "--subtoken", |
| 242 |
dest="subtoken", |
| 243 |
help="Include count of references to subtokens in the count for each token (default %(default)s)", |
| 244 |
default=False, action="store_true" |
| 245 |
) |
| 246 |
|
| 247 |
args = p.parse_args(args) |
| 248 |
|
| 249 |
if args.verbose: |
| 250 |
print("Looking up all lexers ... ", end="", flush=True) |
| 251 |
count = lookup_all_lexers() |
| 252 |
if args.verbose: |
| 253 |
print(f"found {count:,} lexers") |
| 254 |
|
| 255 |
if args.verbose: |
| 256 |
print("Fetching lexer source code ... ", end="", flush=True) |
| 257 |
lexer_sources = fetch_lexer_sources() |
| 258 |
if args.verbose: |
| 259 |
print(f"found {len(lexer_sources):,} lexer source files") |
| 260 |
|
| 261 |
if args.verbose: |
| 262 |
print("Finding token references ... ", end="", flush=True) |
| 263 |
token_references = find_token_references(lexer_sources, args) |
| 264 |
if args.verbose: |
| 265 |
print(f"found references to {len(token_references):,} tokens") |
| 266 |
|
| 267 |
if args.verbose: |
| 268 |
print() |
| 269 |
print("Result:") |
| 270 |
print_result(token_references, args) |
| 271 |
|
| 272 |
|
| 273 |
if __name__ == "__main__": |
| 274 |
sys.exit(main()) |