blob: 217d21abc86e8d4e04e17ef8fdc7108b6656066f [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 <valentinrothberg@gmail.com>
Valentin Rothbergcc641d552014-11-08 20:56:35 +01007# (c) 2014 Stefan Hengelein <stefan.hengelein@fau.de>
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)
Valentin Rothbergef3f5542016-08-28 08:51:31 +020037REGEX_FILTER_SYMBOLS = re.compile(r"[A-Za-z0-9]$")
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +020038REGEX_NUMERIC = re.compile(r"0[xX][0-9a-fA-F]+|[0-9]+")
Valentin Rothberge2042a82015-10-15 10:37:47 +020039REGEX_QUOTES = re.compile("(\"(.*?)\")")
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020040
41
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010042def parse_options():
43 """The user interface of this module."""
Valentin Rothberg14390e32016-08-28 08:51:29 +020044 usage = "Run this tool to detect Kconfig symbols that are referenced but " \
45 "not defined in Kconfig. If no option is specified, " \
46 "checkkconfigsymbols defaults to check your current tree. " \
47 "Please note that specifying commits will 'git reset --hard\' " \
48 "your current tree! You may save uncommitted changes to avoid " \
49 "losing data."
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010050
Valentin Rothberg14390e32016-08-28 08:51:29 +020051 parser = argparse.ArgumentParser(description=usage)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010052
Valentin Rothberg14390e32016-08-28 08:51:29 +020053 parser.add_argument('-c', '--commit', dest='commit', action='store',
54 default="",
55 help="check if the specified commit (hash) introduces "
56 "undefined Kconfig symbols")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010057
Valentin Rothberg14390e32016-08-28 08:51:29 +020058 parser.add_argument('-d', '--diff', dest='diff', action='store',
59 default="",
60 help="diff undefined symbols between two commits "
61 "(e.g., -d commmit1..commit2)")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010062
Valentin Rothberg14390e32016-08-28 08:51:29 +020063 parser.add_argument('-f', '--find', dest='find', action='store_true',
64 default=False,
65 help="find and show commits that may cause symbols to be "
66 "missing (required to run with --diff)")
Valentin Rothberga42fa922015-06-01 16:00:19 +020067
Valentin Rothberg14390e32016-08-28 08:51:29 +020068 parser.add_argument('-i', '--ignore', dest='ignore', action='store',
69 default="",
70 help="ignore files matching this Python regex "
71 "(e.g., -i '.*defconfig')")
Valentin Rothbergcf132e42015-04-29 16:58:27 +020072
Valentin Rothberg14390e32016-08-28 08:51:29 +020073 parser.add_argument('-s', '--sim', dest='sim', action='store', default="",
74 help="print a list of max. 10 string-similar symbols")
Valentin Rothberg1b2c8412015-11-26 14:17:15 +010075
Valentin Rothberg14390e32016-08-28 08:51:29 +020076 parser.add_argument('--force', dest='force', action='store_true',
77 default=False,
78 help="reset current Git tree even when it's dirty")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010079
Valentin Rothberg14390e32016-08-28 08:51:29 +020080 parser.add_argument('--no-color', dest='color', action='store_false',
81 default=True,
82 help="don't print colored output (default when not "
83 "outputting to a terminal)")
Andrew Donnellan4c73c082016-07-05 17:47:37 +100084
Valentin Rothberg14390e32016-08-28 08:51:29 +020085 args = parser.parse_args()
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010086
Valentin Rothberg14390e32016-08-28 08:51:29 +020087 if args.commit and args.diff:
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010088 sys.exit("Please specify only one option at once.")
89
Valentin Rothberg0d18c192016-10-27 14:34:57 +020090 if args.diff and not re.match(r"^[\w\-\.\^]+\.\.[\w\-\.\^]+$", args.diff):
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010091 sys.exit("Please specify valid input in the following format: "
Andreas Ziegler38cbfe42016-03-31 09:24:29 +020092 "\'commit1..commit2\'")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010093
Valentin Rothberg14390e32016-08-28 08:51:29 +020094 if args.commit or args.diff:
95 if not args.force and tree_is_dirty():
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010096 sys.exit("The current Git tree is dirty (see 'git status'). "
97 "Running this script may\ndelete important data since it "
98 "calls 'git reset --hard' for some performance\nreasons. "
99 " Please run this script in a clean Git tree or pass "
100 "'--force' if you\nwant to ignore this warning and "
101 "continue.")
102
Valentin Rothberg14390e32016-08-28 08:51:29 +0200103 if args.commit:
Ariel Marcovitchd62d5ae2021-09-01 17:52:12 +0300104 if args.commit.startswith('HEAD'):
105 sys.exit("The --commit option can't use the HEAD ref")
106
Valentin Rothberg14390e32016-08-28 08:51:29 +0200107 args.find = False
Valentin Rothberga42fa922015-06-01 16:00:19 +0200108
Valentin Rothberg14390e32016-08-28 08:51:29 +0200109 if args.ignore:
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200110 try:
Valentin Rothberg14390e32016-08-28 08:51:29 +0200111 re.match(args.ignore, "this/is/just/a/test.c")
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200112 except:
113 sys.exit("Please specify a valid Python regex.")
114
Valentin Rothberg14390e32016-08-28 08:51:29 +0200115 return args
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100116
117
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200118def main():
119 """Main function of this module."""
Valentin Rothberg14390e32016-08-28 08:51:29 +0200120 args = parse_options()
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100121
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200122 global COLOR
123 COLOR = args.color and sys.stdout.isatty()
Andrew Donnellan4c73c082016-07-05 17:47:37 +1000124
Valentin Rothberg14390e32016-08-28 08:51:29 +0200125 if args.sim and not args.commit and not args.diff:
126 sims = find_sims(args.sim, args.ignore)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100127 if sims:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200128 print("%s: %s" % (yel("Similar symbols"), ', '.join(sims)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100129 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200130 print("%s: no similar symbols found" % yel("Similar symbols"))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100131 sys.exit(0)
132
133 # dictionary of (un)defined symbols
134 defined = {}
135 undefined = {}
136
Valentin Rothberg14390e32016-08-28 08:51:29 +0200137 if args.commit or args.diff:
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100138 head = get_head()
139
140 # get commit range
141 commit_a = None
142 commit_b = None
Valentin Rothberg14390e32016-08-28 08:51:29 +0200143 if args.commit:
144 commit_a = args.commit + "~"
145 commit_b = args.commit
146 elif args.diff:
147 split = args.diff.split("..")
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100148 commit_a = split[0]
149 commit_b = split[1]
150 undefined_a = {}
151 undefined_b = {}
152
153 # get undefined items before the commit
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200154 reset(commit_a)
Valentin Rothberg14390e32016-08-28 08:51:29 +0200155 undefined_a, _ = check_symbols(args.ignore)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100156
157 # get undefined items for the commit
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200158 reset(commit_b)
Valentin Rothberg14390e32016-08-28 08:51:29 +0200159 undefined_b, defined = check_symbols(args.ignore)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100160
161 # report cases that are present for the commit but not before
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200162 for symbol in sorted(undefined_b):
163 # symbol has not been undefined before
164 if symbol not in undefined_a:
165 files = sorted(undefined_b.get(symbol))
166 undefined[symbol] = files
167 # check if there are new files that reference the undefined symbol
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100168 else:
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200169 files = sorted(undefined_b.get(symbol) -
170 undefined_a.get(symbol))
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100171 if files:
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200172 undefined[symbol] = files
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100173
174 # reset to head
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200175 reset(head)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100176
177 # default to check the entire tree
178 else:
Valentin Rothberg14390e32016-08-28 08:51:29 +0200179 undefined, defined = check_symbols(args.ignore)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100180
181 # now print the output
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200182 for symbol in sorted(undefined):
183 print(red(symbol))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100184
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200185 files = sorted(undefined.get(symbol))
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200186 print("%s: %s" % (yel("Referencing files"), ", ".join(files)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100187
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200188 sims = find_sims(symbol, args.ignore, defined)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100189 sims_out = yel("Similar symbols")
190 if sims:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200191 print("%s: %s" % (sims_out, ', '.join(sims)))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100192 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200193 print("%s: %s" % (sims_out, "no similar symbols found"))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100194
Valentin Rothberg14390e32016-08-28 08:51:29 +0200195 if args.find:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200196 print("%s:" % yel("Commits changing symbol"))
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200197 commits = find_commits(symbol, args.diff)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100198 if commits:
199 for commit in commits:
200 commit = commit.split(" ", 1)
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200201 print("\t- %s (\"%s\")" % (yel(commit[0]), commit[1]))
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100202 else:
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200203 print("\t- no commit found")
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200204 print() # new line
Valentin Rothbergc7455662015-06-01 16:00:20 +0200205
206
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200207def reset(commit):
208 """Reset current git tree to %commit."""
209 execute(["git", "reset", "--hard", commit])
210
211
Valentin Rothbergc7455662015-06-01 16:00:20 +0200212def yel(string):
213 """
214 Color %string yellow.
215 """
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200216 return "\033[33m%s\033[0m" % string if COLOR else string
Valentin Rothbergc7455662015-06-01 16:00:20 +0200217
218
219def red(string):
220 """
221 Color %string red.
222 """
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200223 return "\033[31m%s\033[0m" % string if COLOR else string
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100224
225
226def execute(cmd):
227 """Execute %cmd and return stdout. Exit in case of error."""
Valentin Rothbergf175ba12016-08-27 10:59:07 +0200228 try:
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200229 stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=False)
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200230 stdout = stdout.decode(errors='replace')
Valentin Rothbergf175ba12016-08-27 10:59:07 +0200231 except subprocess.CalledProcessError as fail:
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200232 exit(fail)
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100233 return stdout
234
235
Valentin Rothberga42fa922015-06-01 16:00:19 +0200236def find_commits(symbol, diff):
237 """Find commits changing %symbol in the given range of %diff."""
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200238 commits = execute(["git", "log", "--pretty=oneline",
239 "--abbrev-commit", "-G",
240 symbol, diff])
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100241 return [x for x in commits.split("\n") if x]
Valentin Rothberga42fa922015-06-01 16:00:19 +0200242
243
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100244def tree_is_dirty():
245 """Return true if the current working tree is dirty (i.e., if any file has
246 been added, deleted, modified, renamed or copied but not committed)."""
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200247 stdout = execute(["git", "status", "--porcelain"])
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100248 for line in stdout:
249 if re.findall(r"[URMADC]{1}", line[:2]):
250 return True
251 return False
252
253
254def get_head():
255 """Return commit hash of current HEAD."""
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200256 stdout = execute(["git", "rev-parse", "HEAD"])
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100257 return stdout.strip('\n')
258
259
Valentin Rothberge2042a82015-10-15 10:37:47 +0200260def partition(lst, size):
261 """Partition list @lst into eveni-sized lists of size @size."""
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200262 return [lst[i::size] for i in range(size)]
Valentin Rothberge2042a82015-10-15 10:37:47 +0200263
264
265def init_worker():
266 """Set signal handler to ignore SIGINT."""
267 signal.signal(signal.SIGINT, signal.SIG_IGN)
268
269
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200270def find_sims(symbol, ignore, defined=[]):
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100271 """Return a list of max. ten Kconfig symbols that are string-similar to
272 @symbol."""
273 if defined:
Valentin Rothberg8e8e3332017-01-18 13:08:19 +0100274 return difflib.get_close_matches(symbol, set(defined), 10)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100275
276 pool = Pool(cpu_count(), init_worker)
277 kfiles = []
278 for gitfile in get_files():
279 if REGEX_FILE_KCONFIG.match(gitfile):
280 kfiles.append(gitfile)
281
282 arglist = []
283 for part in partition(kfiles, cpu_count()):
284 arglist.append((part, ignore))
285
286 for res in pool.map(parse_kconfig_files, arglist):
287 defined.extend(res[0])
288
Valentin Rothberg8e8e3332017-01-18 13:08:19 +0100289 return difflib.get_close_matches(symbol, set(defined), 10)
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100290
291
292def get_files():
293 """Return a list of all files in the current git directory."""
294 # use 'git ls-files' to get the worklist
Valentin Rothberg2f9cc122016-08-28 08:51:32 +0200295 stdout = execute(["git", "ls-files"])
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100296 if len(stdout) > 0 and stdout[-1] == "\n":
297 stdout = stdout[:-1]
298
299 files = []
300 for gitfile in stdout.rsplit("\n"):
301 if ".git" in gitfile or "ChangeLog" in gitfile or \
302 ".log" in gitfile or os.path.isdir(gitfile) or \
303 gitfile.startswith("tools/"):
304 continue
305 files.append(gitfile)
306 return files
307
308
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200309def check_symbols(ignore):
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100310 """Find undefined Kconfig symbols and return a dict with the symbol as key
Valentin Rothbergcf132e42015-04-29 16:58:27 +0200311 and a list of referencing files as value. Files matching %ignore are not
312 checked for undefined symbols."""
Valentin Rothberge2042a82015-10-15 10:37:47 +0200313 pool = Pool(cpu_count(), init_worker)
314 try:
315 return check_symbols_helper(pool, ignore)
316 except KeyboardInterrupt:
317 pool.terminate()
318 pool.join()
319 sys.exit(1)
320
321
322def check_symbols_helper(pool, ignore):
323 """Helper method for check_symbols(). Used to catch keyboard interrupts in
324 check_symbols() in order to properly terminate running worker processes."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200325 source_files = []
326 kconfig_files = []
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200327 defined_symbols = []
328 referenced_symbols = dict() # {file: [symbols]}
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200329
Valentin Rothberg1b2c8412015-11-26 14:17:15 +0100330 for gitfile in get_files():
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200331 if REGEX_FILE_KCONFIG.match(gitfile):
332 kconfig_files.append(gitfile)
333 else:
Ariel Marcovitch1439ebd2021-08-22 22:22:01 +0300334 if ignore and re.match(ignore, gitfile):
Valentin Rothberge2042a82015-10-15 10:37:47 +0200335 continue
336 # add source files that do not match the ignore pattern
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200337 source_files.append(gitfile)
338
Valentin Rothberge2042a82015-10-15 10:37:47 +0200339 # parse source files
340 arglist = partition(source_files, cpu_count())
341 for res in pool.map(parse_source_files, arglist):
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200342 referenced_symbols.update(res)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200343
Valentin Rothberge2042a82015-10-15 10:37:47 +0200344 # parse kconfig files
345 arglist = []
346 for part in partition(kconfig_files, cpu_count()):
347 arglist.append((part, ignore))
348 for res in pool.map(parse_kconfig_files, arglist):
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200349 defined_symbols.extend(res[0])
350 referenced_symbols.update(res[1])
351 defined_symbols = set(defined_symbols)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200352
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200353 # inverse mapping of referenced_symbols to dict(symbol: [files])
Valentin Rothberge2042a82015-10-15 10:37:47 +0200354 inv_map = dict()
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200355 for _file, symbols in referenced_symbols.items():
356 for symbol in symbols:
357 inv_map[symbol] = inv_map.get(symbol, set())
358 inv_map[symbol].add(_file)
359 referenced_symbols = inv_map
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200360
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200361 undefined = {} # {symbol: [files]}
362 for symbol in sorted(referenced_symbols):
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100363 # filter some false positives
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200364 if symbol == "FOO" or symbol == "BAR" or \
365 symbol == "FOO_BAR" or symbol == "XXX":
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100366 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200367 if symbol not in defined_symbols:
368 if symbol.endswith("_MODULE"):
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100369 # avoid false positives for kernel modules
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200370 if symbol[:-len("_MODULE")] in defined_symbols:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200371 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200372 undefined[symbol] = referenced_symbols.get(symbol)
373 return undefined, defined_symbols
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200374
375
Valentin Rothberge2042a82015-10-15 10:37:47 +0200376def parse_source_files(source_files):
377 """Parse each source file in @source_files and return dictionary with source
378 files as keys and lists of references Kconfig symbols as values."""
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200379 referenced_symbols = dict()
Valentin Rothberge2042a82015-10-15 10:37:47 +0200380 for sfile in source_files:
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200381 referenced_symbols[sfile] = parse_source_file(sfile)
382 return referenced_symbols
Valentin Rothberge2042a82015-10-15 10:37:47 +0200383
384
385def parse_source_file(sfile):
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200386 """Parse @sfile and return a list of referenced Kconfig symbols."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200387 lines = []
Valentin Rothberge2042a82015-10-15 10:37:47 +0200388 references = []
389
390 if not os.path.exists(sfile):
391 return references
392
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200393 with open(sfile, "r", encoding='utf-8', errors='replace') as stream:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200394 lines = stream.readlines()
395
396 for line in lines:
Valentin Rothberg36c79c7f2016-08-28 08:51:30 +0200397 if "CONFIG_" not in line:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200398 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200399 symbols = REGEX_SOURCE_SYMBOL.findall(line)
400 for symbol in symbols:
401 if not REGEX_FILTER_SYMBOLS.search(symbol):
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200402 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200403 references.append(symbol)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200404
405 return references
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200406
407
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200408def get_symbols_in_line(line):
409 """Return mentioned Kconfig symbols in @line."""
410 return REGEX_SYMBOL.findall(line)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200411
412
Valentin Rothberge2042a82015-10-15 10:37:47 +0200413def parse_kconfig_files(args):
414 """Parse kconfig files and return tuple of defined and references Kconfig
415 symbols. Note, @args is a tuple of a list of files and the @ignore
416 pattern."""
417 kconfig_files = args[0]
418 ignore = args[1]
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200419 defined_symbols = []
420 referenced_symbols = dict()
Valentin Rothberge2042a82015-10-15 10:37:47 +0200421
422 for kfile in kconfig_files:
423 defined, references = parse_kconfig_file(kfile)
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200424 defined_symbols.extend(defined)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200425 if ignore and re.match(ignore, kfile):
426 # do not collect references for files that match the ignore pattern
427 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200428 referenced_symbols[kfile] = references
429 return (defined_symbols, referenced_symbols)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200430
431
432def parse_kconfig_file(kfile):
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200433 """Parse @kfile and update symbol definitions and references."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200434 lines = []
Valentin Rothberge2042a82015-10-15 10:37:47 +0200435 defined = []
436 references = []
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200437
Valentin Rothberge2042a82015-10-15 10:37:47 +0200438 if not os.path.exists(kfile):
439 return defined, references
440
Valentin Rothberg7c5227a2016-08-28 08:51:28 +0200441 with open(kfile, "r", encoding='utf-8', errors='replace') as stream:
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200442 lines = stream.readlines()
443
444 for i in range(len(lines)):
445 line = lines[i]
446 line = line.strip('\n')
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100447 line = line.split("#")[0] # ignore comments
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200448
449 if REGEX_KCONFIG_DEF.match(line):
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200450 symbol_def = REGEX_KCONFIG_DEF.findall(line)
451 defined.append(symbol_def[0])
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200452 elif REGEX_KCONFIG_STMT.match(line):
Valentin Rothberge2042a82015-10-15 10:37:47 +0200453 line = REGEX_QUOTES.sub("", line)
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200454 symbols = get_symbols_in_line(line)
Valentin Rothbergcc641d552014-11-08 20:56:35 +0100455 # multi-line statements
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200456 while line.endswith("\\"):
457 i += 1
458 line = lines[i]
459 line = line.strip('\n')
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200460 symbols.extend(get_symbols_in_line(line))
461 for symbol in set(symbols):
462 if REGEX_NUMERIC.match(symbol):
Valentin Rothberg0bd38ae2015-07-27 12:33:05 +0200463 # ignore numeric values
464 continue
Valentin Rothbergef3f5542016-08-28 08:51:31 +0200465 references.append(symbol)
Valentin Rothberge2042a82015-10-15 10:37:47 +0200466
467 return defined, references
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200468
469
470if __name__ == "__main__":
471 main()