blob: c57c990c324481d789241e79f7aeb1c1ed23a915 [file] [log] [blame]
Valentin Rothberg7c5227a2016-08-28 08:51:28 +02001#!/usr/bin/env python3
Thomas Gleixner4f190482019-05-27 08:55:14 +02002# SPDX-License-Identifier: GPL-2.0-only
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02003
Valentin Rothbergb1a3f242015-03-16 12:16:14 +01004"""Find Kconfig symbols that are referenced but not defined."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02005
Valentin Rothberg8e8e3332017-01-18 13:08:19 +01006# (c) 2014-2017 Valentin Rothberg <[email protected]>
Valentin Rothbergcc641d552014-11-08 20:56:35 +01007# (c) 2014 Stefan Hengelein <[email protected]>
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02008#
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02009
10
Valentin Rothberg14390e32016-08-28 08:51:29 +020011import argparse
Valentin Rothberg1b2c8412015-11-26 14:17:15 +010012import difflib
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020013import os
14import re
Valentin Rothberge2042a82015-10-15 10:37:47 +020015import signal
Valentin Rothbergf175ba12016-08-27 10:59:07 +020016import subprocess
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010017import sys
Valentin Rothberge2042a82015-10-15 10:37:47 +020018from multiprocessing import Pool, cpu_count
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020019
Valentin Rothbergcc641d552014-11-08 20:56:35 +010020
21# regex expressions
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020022OPERATORS = r"&|\(|\)|\||\!"
Valentin Rothbergef3f5542016-08-28 08:51:31 +020023SYMBOL = r"(?:\w*[A-Z0-9]\w*){2,}"
24DEF = r"^\s*(?:menu){,1}config\s+(" + SYMBOL + r")\s*"
25EXPR = r"(?:" + OPERATORS + r"|\s|" + SYMBOL + r")+"
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +020026DEFAULT = r"default\s+.*?(?:if\s.+){,1}"
Valentin Rothberg3b28f4f2017-02-02 18:00:44 +010027STMT = r"^\s*(?:if|select|imply|depends\s+on|(?:" + DEFAULT + r"))\s+" + EXPR
Valentin Rothbergef3f5542016-08-28 08:51:31 +020028SOURCE_SYMBOL = r"(?:\W|\b)+[D]{,1}CONFIG_(" + SYMBOL + r")"
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020029
Valentin Rothbergcc641d552014-11-08 20:56:35 +010030# regex objects
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020031REGEX_FILE_KCONFIG = re.compile(r".*Kconfig[\.\w+\-]*$")
Valentin Rothbergef3f5542016-08-28 08:51:31 +020032REGEX_SYMBOL = re.compile(r'(?!\B)' + SYMBOL + r'(?!\B)')
33REGEX_SOURCE_SYMBOL = re.compile(SOURCE_SYMBOL)
Valentin Rothbergcc641d552014-11-08 20:56:35 +010034REGEX_KCONFIG_DEF = re.compile(DEF)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020035REGEX_KCONFIG_EXPR = re.compile(EXPR)
36REGEX_KCONFIG_STMT = re.compile(STMT)
Masahiro Yamadaf70f74d2020-06-17 12:02:19 +090037REGEX_KCONFIG_HELP = re.compile(r"^\s+help\s*$")
Valentin Rothbergef3f5542016-08-28 08:51:31 +020038REGEX_FILTER_SYMBOLS = re.compile(r"[A-Za-z0-9]$")
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +020039REGEX_NUMERIC = re.compile(r"0[xX][0-9a-fA-F]+|[0-9]+")
Valentin Rothberge2042a82015-10-15 10:37:47 +020040REGEX_QUOTES = re.compile("(\"(.*?)\")")
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020041
42
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010043def parse_options():
44 """The user interface of this module."""
Valentin Rothberg14390e32016-08-28 08:51:29 +020045 usage = "Run this tool to detect Kconfig symbols that are referenced but " \
46 "not defined in Kconfig. If no option is specified, " \
47 "checkkconfigsymbols defaults to check your current tree. " \
48 "Please note that specifying commits will 'git reset --hard\' " \
49 "your current tree! You may save uncommitted changes to avoid " \
50 "losing data."
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010051
Valentin Rothberg14390e32016-08-28 08:51:29 +020052 parser = argparse.ArgumentParser(description=usage)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010053
Valentin Rothberg14390e32016-08-28 08:51:29 +020054 parser.add_argument('-c', '--commit', dest='commit', action='store',
55 default="",
56 help="check if the specified commit (hash) introduces "
57 "undefined Kconfig symbols")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010058
Valentin Rothberg14390e32016-08-28 08:51:29 +020059 parser.add_argument('-d', '--diff', dest='diff', action='store',
60 default="",
61 help="diff undefined symbols between two commits "
62 "(e.g., -d commmit1..commit2)")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010063
Valentin Rothberg14390e32016-08-28 08:51:29 +020064 parser.add_argument('-f', '--find', dest='find', action='store_true',
65 default=False,
66 help="find and show commits that may cause symbols to be "
67 "missing (required to run with --diff)")
Valentin Rothberga42fa922015-06-01 16:00:19 +020068
Valentin Rothberg14390e32016-08-28 08:51:29 +020069 parser.add_argument('-i', '--ignore', dest='ignore', action='store',
70 default="",
71 help="ignore files matching this Python regex "
72 "(e.g., -i '.*defconfig')")
Valentin Rothbergcf132e42015-04-29 16:58:27 +020073
Valentin Rothberg14390e32016-08-28 08:51:29 +020074 parser.add_argument('-s', '--sim', dest='sim', action='store', default="",
75 help="print a list of max. 10 string-similar symbols")
Valentin Rothberg1b2c8412015-11-26 14:17:15 +010076
Valentin Rothberg14390e32016-08-28 08:51:29 +020077 parser.add_argument('--force', dest='force', action='store_true',
78 default=False,
79 help="reset current Git tree even when it's dirty")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010080
Valentin Rothberg14390e32016-08-28 08:51:29 +020081 parser.add_argument('--no-color', dest='color', action='store_false',
82 default=True,
83 help="don't print colored output (default when not "
84 "outputting to a terminal)")
Andrew Donnellan4c73c082016-07-05 17:47:37 +100085
Valentin Rothberg14390e32016-08-28 08:51:29 +020086 args = parser.parse_args()
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010087
Valentin Rothberg14390e32016-08-28 08:51:29 +020088 if args.commit and args.diff:
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010089 sys.exit("Please specify only one option at once.")
90
Valentin Rothberg0d18c192016-10-27 14:34:57 +020091 if args.diff and not re.match(r"^[\w\-\.\^]+\.\.[\w\-\.\^]+$", args.diff):
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010092 sys.exit("Please specify valid input in the following format: "
Andreas Ziegler38cbfe42016-03-31 09:24:29 +020093 "\'commit1..commit2\'")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010094
Valentin Rothberg14390e32016-08-28 08:51:29 +020095 if args.commit or args.diff:
96 if not args.force and tree_is_dirty():
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010097 sys.exit("The current Git tree is dirty (see 'git status'). "
98 "Running this script may\ndelete important data since it "
99 "calls 'git reset --hard' for some performance\nreasons. "
100 " Please run this script in a clean Git tree or pass "
101 "'--force' if you\nwant to ignore this warning and "
102 "continue.")
103
Valentin Rothberg14390e32016-08-28 08:51:29 +0200104 if args.commit:
Ariel Marcovitchd62d5ae2021-09-01 17:52:12 +0300105 if args.commit.startswith('HEAD'):
106 sys.exit("The --commit option can't use the HEAD ref")
107
Valentin Rothberg14390e32016-08-28 08:51:29 +0200108 args.find = False
Valentin Rothberga42fa922015-06-01 16:00:19 +0200109
Valentin Rothberg14390e32016-08-28 08:51:29 +0200110 if args.ignore:
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200111 try:
Valentin Rothberg14390e32016-08-28 08:51:29 +0200112 re.match(args.ignore, "this/is/just/a/test.c")
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200113 except:
114 sys.exit("Please specify a valid Python regex.")
115
Valentin Rothberg14390e32016-08-28 08:51:29 +0200116 return args
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100117
118
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200119def main():
120 """Main function of this module."""
Valentin Rothberg14390e32016-08-28 08:51:29 +0200121 args = parse_options()
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100122
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200123 global COLOR
124 COLOR = args.color and sys.stdout.isatty()
Andrew Donnellan4c73c082016-07-05 17:47:37 +1000125
Valentin Rothberg14390e32016-08-28 08:51:29 +0200126 if args.sim and not args.commit and not args.diff:
127 sims = find_sims(args.sim, args.ignore)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100128 if sims:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200129 print("%s: %s" % (yel("Similar symbols"), ', '.join(sims)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100130 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200131 print("%s: no similar symbols found" % yel("Similar symbols"))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100132 sys.exit(0)
133
134 # dictionary of (un)defined symbols
135 defined = {}
136 undefined = {}
137
Valentin Rothberg14390e32016-08-28 08:51:29 +0200138 if args.commit or args.diff:
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100139 head = get_head()
140
141 # get commit range
142 commit_a = None
143 commit_b = None
Valentin Rothberg14390e32016-08-28 08:51:29 +0200144 if args.commit:
145 commit_a = args.commit + "~"
146 commit_b = args.commit
147 elif args.diff:
148 split = args.diff.split("..")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100149 commit_a = split[0]
150 commit_b = split[1]
151 undefined_a = {}
152 undefined_b = {}
153
154 # get undefined items before the commit
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200155 reset(commit_a)
Valentin Rothberg14390e32016-08-28 08:51:29 +0200156 undefined_a, _ = check_symbols(args.ignore)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100157
158 # get undefined items for the commit
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200159 reset(commit_b)
Valentin Rothberg14390e32016-08-28 08:51:29 +0200160 undefined_b, defined = check_symbols(args.ignore)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100161
162 # report cases that are present for the commit but not before
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200163 for symbol in sorted(undefined_b):
164 # symbol has not been undefined before
165 if symbol not in undefined_a:
166 files = sorted(undefined_b.get(symbol))
167 undefined[symbol] = files
168 # check if there are new files that reference the undefined symbol
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100169 else:
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200170 files = sorted(undefined_b.get(symbol) -
171 undefined_a.get(symbol))
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100172 if files:
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200173 undefined[symbol] = files
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100174
175 # reset to head
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200176 reset(head)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100177
178 # default to check the entire tree
179 else:
Valentin Rothberg14390e32016-08-28 08:51:29 +0200180 undefined, defined = check_symbols(args.ignore)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100181
182 # now print the output
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200183 for symbol in sorted(undefined):
184 print(red(symbol))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100185
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200186 files = sorted(undefined.get(symbol))
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200187 print("%s: %s" % (yel("Referencing files"), ", ".join(files)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100188
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200189 sims = find_sims(symbol, args.ignore, defined)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100190 sims_out = yel("Similar symbols")
191 if sims:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200192 print("%s: %s" % (sims_out, ', '.join(sims)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100193 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200194 print("%s: %s" % (sims_out, "no similar symbols found"))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100195
Valentin Rothberg14390e32016-08-28 08:51:29 +0200196 if args.find:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200197 print("%s:" % yel("Commits changing symbol"))
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200198 commits = find_commits(symbol, args.diff)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100199 if commits:
200 for commit in commits:
201 commit = commit.split(" ", 1)
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200202 print("\t- %s (\"%s\")" % (yel(commit[0]), commit[1]))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100203 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200204 print("\t- no commit found")
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200205 print() # new line
Valentin Rothbergc7455662015-06-01 16:00:20 +0200206
207
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200208def reset(commit):
209 """Reset current git tree to %commit."""
210 execute(["git", "reset", "--hard", commit])
211
212
Valentin Rothbergc7455662015-06-01 16:00:20 +0200213def yel(string):
214 """
215 Color %string yellow.
216 """
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200217 return "\033[33m%s\033[0m" % string if COLOR else string
Valentin Rothbergc7455662015-06-01 16:00:20 +0200218
219
220def red(string):
221 """
222 Color %string red.
223 """
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200224 return "\033[31m%s\033[0m" % string if COLOR else string
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100225
226
227def execute(cmd):
228 """Execute %cmd and return stdout. Exit in case of error."""
Valentin Rothbergf175ba12016-08-27 10:59:07 +0200229 try:
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200230 stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=False)
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200231 stdout = stdout.decode(errors='replace')
Valentin Rothbergf175ba12016-08-27 10:59:07 +0200232 except subprocess.CalledProcessError as fail:
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200233 exit(fail)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100234 return stdout
235
236
Valentin Rothberga42fa922015-06-01 16:00:19 +0200237def find_commits(symbol, diff):
238 """Find commits changing %symbol in the given range of %diff."""
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200239 commits = execute(["git", "log", "--pretty=oneline",
240 "--abbrev-commit", "-G",
241 symbol, diff])
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100242 return [x for x in commits.split("\n") if x]
Valentin Rothberga42fa922015-06-01 16:00:19 +0200243
244
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100245def tree_is_dirty():
246 """Return true if the current working tree is dirty (i.e., if any file has
247 been added, deleted, modified, renamed or copied but not committed)."""
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200248 stdout = execute(["git", "status", "--porcelain"])
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100249 for line in stdout:
250 if re.findall(r"[URMADC]{1}", line[:2]):
251 return True
252 return False
253
254
255def get_head():
256 """Return commit hash of current HEAD."""
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200257 stdout = execute(["git", "rev-parse", "HEAD"])
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100258 return stdout.strip('\n')
259
260
Valentin Rothberge2042a82015-10-15 10:37:47 +0200261def partition(lst, size):
262 """Partition list @lst into eveni-sized lists of size @size."""
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200263 return [lst[i::size] for i in range(size)]
Valentin Rothberge2042a82015-10-15 10:37:47 +0200264
265
266def init_worker():
267 """Set signal handler to ignore SIGINT."""
268 signal.signal(signal.SIGINT, signal.SIG_IGN)
269
270
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200271def find_sims(symbol, ignore, defined=[]):
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100272 """Return a list of max. ten Kconfig symbols that are string-similar to
273 @symbol."""
274 if defined:
Valentin Rothberg8e8e3332017-01-18 13:08:19 +0100275 return difflib.get_close_matches(symbol, set(defined), 10)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100276
277 pool = Pool(cpu_count(), init_worker)
278 kfiles = []
279 for gitfile in get_files():
280 if REGEX_FILE_KCONFIG.match(gitfile):
281 kfiles.append(gitfile)
282
283 arglist = []
284 for part in partition(kfiles, cpu_count()):
285 arglist.append((part, ignore))
286
287 for res in pool.map(parse_kconfig_files, arglist):
288 defined.extend(res[0])
289
Valentin Rothberg8e8e3332017-01-18 13:08:19 +0100290 return difflib.get_close_matches(symbol, set(defined), 10)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100291
292
293def get_files():
294 """Return a list of all files in the current git directory."""
295 # use 'git ls-files' to get the worklist
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200296 stdout = execute(["git", "ls-files"])
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100297 if len(stdout) > 0 and stdout[-1] == "\n":
298 stdout = stdout[:-1]
299
300 files = []
301 for gitfile in stdout.rsplit("\n"):
302 if ".git" in gitfile or "ChangeLog" in gitfile or \
303 ".log" in gitfile or os.path.isdir(gitfile) or \
304 gitfile.startswith("tools/"):
305 continue
306 files.append(gitfile)
307 return files
308
309
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200310def check_symbols(ignore):
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100311 """Find undefined Kconfig symbols and return a dict with the symbol as key
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200312 and a list of referencing files as value. Files matching %ignore are not
313 checked for undefined symbols."""
Valentin Rothberge2042a82015-10-15 10:37:47 +0200314 pool = Pool(cpu_count(), init_worker)
315 try:
316 return check_symbols_helper(pool, ignore)
317 except KeyboardInterrupt:
318 pool.terminate()
319 pool.join()
320 sys.exit(1)
321
322
323def check_symbols_helper(pool, ignore):
324 """Helper method for check_symbols(). Used to catch keyboard interrupts in
325 check_symbols() in order to properly terminate running worker processes."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200326 source_files = []
327 kconfig_files = []
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200328 defined_symbols = []
329 referenced_symbols = dict() # {file: [symbols]}
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200330
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100331 for gitfile in get_files():
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200332 if REGEX_FILE_KCONFIG.match(gitfile):
333 kconfig_files.append(gitfile)
334 else:
Ariel Marcovitch1439ebd2021-08-22 22:22:01 +0300335 if ignore and re.match(ignore, gitfile):
Valentin Rothberge2042a82015-10-15 10:37:47 +0200336 continue
337 # add source files that do not match the ignore pattern
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200338 source_files.append(gitfile)
339
Valentin Rothberge2042a82015-10-15 10:37:47 +0200340 # parse source files
341 arglist = partition(source_files, cpu_count())
342 for res in pool.map(parse_source_files, arglist):
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200343 referenced_symbols.update(res)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200344
Valentin Rothberge2042a82015-10-15 10:37:47 +0200345 # parse kconfig files
346 arglist = []
347 for part in partition(kconfig_files, cpu_count()):
348 arglist.append((part, ignore))
349 for res in pool.map(parse_kconfig_files, arglist):
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200350 defined_symbols.extend(res[0])
351 referenced_symbols.update(res[1])
352 defined_symbols = set(defined_symbols)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200353
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200354 # inverse mapping of referenced_symbols to dict(symbol: [files])
Valentin Rothberge2042a82015-10-15 10:37:47 +0200355 inv_map = dict()
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200356 for _file, symbols in referenced_symbols.items():
357 for symbol in symbols:
358 inv_map[symbol] = inv_map.get(symbol, set())
359 inv_map[symbol].add(_file)
360 referenced_symbols = inv_map
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200361
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200362 undefined = {} # {symbol: [files]}
363 for symbol in sorted(referenced_symbols):
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100364 # filter some false positives
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200365 if symbol == "FOO" or symbol == "BAR" or \
366 symbol == "FOO_BAR" or symbol == "XXX":
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100367 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200368 if symbol not in defined_symbols:
369 if symbol.endswith("_MODULE"):
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100370 # avoid false positives for kernel modules
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200371 if symbol[:-len("_MODULE")] in defined_symbols:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200372 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200373 undefined[symbol] = referenced_symbols.get(symbol)
374 return undefined, defined_symbols
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200375
376
Valentin Rothberge2042a82015-10-15 10:37:47 +0200377def parse_source_files(source_files):
378 """Parse each source file in @source_files and return dictionary with source
379 files as keys and lists of references Kconfig symbols as values."""
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200380 referenced_symbols = dict()
Valentin Rothberge2042a82015-10-15 10:37:47 +0200381 for sfile in source_files:
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200382 referenced_symbols[sfile] = parse_source_file(sfile)
383 return referenced_symbols
Valentin Rothberge2042a82015-10-15 10:37:47 +0200384
385
386def parse_source_file(sfile):
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200387 """Parse @sfile and return a list of referenced Kconfig symbols."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200388 lines = []
Valentin Rothberge2042a82015-10-15 10:37:47 +0200389 references = []
390
391 if not os.path.exists(sfile):
392 return references
393
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200394 with open(sfile, "r", encoding='utf-8', errors='replace') as stream:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200395 lines = stream.readlines()
396
397 for line in lines:
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200398 if "CONFIG_" not in line:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200399 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200400 symbols = REGEX_SOURCE_SYMBOL.findall(line)
401 for symbol in symbols:
402 if not REGEX_FILTER_SYMBOLS.search(symbol):
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200403 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200404 references.append(symbol)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200405
406 return references
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200407
408
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200409def get_symbols_in_line(line):
410 """Return mentioned Kconfig symbols in @line."""
411 return REGEX_SYMBOL.findall(line)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200412
413
Valentin Rothberge2042a82015-10-15 10:37:47 +0200414def parse_kconfig_files(args):
415 """Parse kconfig files and return tuple of defined and references Kconfig
416 symbols. Note, @args is a tuple of a list of files and the @ignore
417 pattern."""
418 kconfig_files = args[0]
419 ignore = args[1]
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200420 defined_symbols = []
421 referenced_symbols = dict()
Valentin Rothberge2042a82015-10-15 10:37:47 +0200422
423 for kfile in kconfig_files:
424 defined, references = parse_kconfig_file(kfile)
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200425 defined_symbols.extend(defined)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200426 if ignore and re.match(ignore, kfile):
427 # do not collect references for files that match the ignore pattern
428 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200429 referenced_symbols[kfile] = references
430 return (defined_symbols, referenced_symbols)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200431
432
433def parse_kconfig_file(kfile):
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200434 """Parse @kfile and update symbol definitions and references."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200435 lines = []
Valentin Rothberge2042a82015-10-15 10:37:47 +0200436 defined = []
437 references = []
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200438 skip = False
439
Valentin Rothberge2042a82015-10-15 10:37:47 +0200440 if not os.path.exists(kfile):
441 return defined, references
442
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200443 with open(kfile, "r", encoding='utf-8', errors='replace') as stream:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200444 lines = stream.readlines()
445
446 for i in range(len(lines)):
447 line = lines[i]
448 line = line.strip('\n')
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100449 line = line.split("#")[0] # ignore comments
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200450
451 if REGEX_KCONFIG_DEF.match(line):
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200452 symbol_def = REGEX_KCONFIG_DEF.findall(line)
453 defined.append(symbol_def[0])
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200454 skip = False
455 elif REGEX_KCONFIG_HELP.match(line):
456 skip = True
457 elif skip:
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100458 # ignore content of help messages
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200459 pass
460 elif REGEX_KCONFIG_STMT.match(line):
Valentin Rothberge2042a82015-10-15 10:37:47 +0200461 line = REGEX_QUOTES.sub("", line)
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200462 symbols = get_symbols_in_line(line)
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100463 # multi-line statements
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200464 while line.endswith("\\"):
465 i += 1
466 line = lines[i]
467 line = line.strip('\n')
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200468 symbols.extend(get_symbols_in_line(line))
469 for symbol in set(symbols):
470 if REGEX_NUMERIC.match(symbol):
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +0200471 # ignore numeric values
472 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200473 references.append(symbol)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200474
475 return defined, references
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200476
477
478if __name__ == "__main__":
479 main()