Debian Codegraph @

share/analysis-scripts/find_fun.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 ##########################################################################
4 # #
5 # This file is part of Frama-C. #
6 # #
7 # Copyright (C) 2007-2022 #
8 # CEA (Commissariat à l'énergie atomique et aux énergies #
9 # alternatives) #
10 # #
11 # you can redistribute it and/or modify it under the terms of the GNU #
12 # Lesser General Public License as published by the Free Software #
13 # Foundation, version 2.1. #
14 # #
15 # It is distributed in the hope that it will be useful, #
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
18 # GNU Lesser General Public License for more details. #
19 # #
20 # See the GNU Lesser General Public License version 2.1 #
21 # for more details (enclosed in the file licenses/LGPLv2.1). #
22 # #
23 ##########################################################################
24
25 """This script finds files containing likely declarations and definitions
26 for a given function name, via heuristic syntactic matching."""
27
28 import argparse
29 import os
30 import re
31 import sys
32 from pathlib import Path
33
34 import function_finder
35
36 parser = argparse.ArgumentParser(
37 description="""
38 Looks for likely declarations/definitions of a function
39 in files with extensions '.c', '.h' and '.i'.
40 If any directories are specified, looks inside them,
41 otherwise looks inside PWD and /usr/include.
42 Subdirectories are always considered recursively."""
43 )
44
45 parser.add_argument(
46 "--directory",
47 "-C",
48 metavar="DIR",
49 default=".",
50 nargs=1,
51 help="print paths relative to directory DIR (default: .)",
52 )
53 parser.add_argument("funcname", help="function name to search")
54 parser.add_argument(
55 "dir",
56 nargs="*",
57 type=Path,
58 help="directories where to search (if empty: PWD /usr/include)",
59 )
60 args = vars(parser.parse_args())
61
62 reldir = args["directory"][0]
63 fname = args["funcname"]
64 dirs = args["dir"]
65
66 if re.match("[a-zA-Z_][a-zA-Z0-9_]*$", fname) is None:
67 print("error: function name contains invalid characters: %s" % fname)
68 print(" (only letters/digits/underscore allowed)")
69 sys.exit(1)
70
71 dirs = set(dirs)
72 if not dirs:
73 pwd = os.getcwd()
74 dirs = [Path(pwd), Path("/usr/include")]
75 else:
76 dirs = [Path(p) for p in set(sys.argv[2:])]
77
78 files = set()
79 for d in dirs:
80 # The usage of Path.glob here prevents symbolic links from being
81 # followed, which is desirable in some situations. However, if you
82 # need them, try using glob.glob instead.
83 files.update(d.glob("**/*.[ich]"))
84
85 print("Looking for '%s' inside %d file(s)..." % (fname, len(files)))
86
87 possible_declarators = []
88 possible_definers = []
89 re_fun = function_finder.prepare_re_specific_name(fname)
90 for f in files:
91 try:
92 found = function_finder.find_specific_name(re_fun, f)
93 if found:
94 if found == 1:
95 possible_declarators.append(f)
96 else:
97 possible_definers.append(f)
98 except OSError as e:
99 print(f"error opening '{f}' ({e.errno}, {e.strerror}), skipping file")
100
101
102 def relative_path_to(start):
103 return lambda p: os.path.relpath(p, start=start)
104
105
106 if not possible_declarators and not possible_definers:
107 print("No declaration/definition found for function '%s'" % fname)
108 sys.exit(0)
109
110 if reldir != ".":
111 reldir_msg = f" (relative to '{reldir}')"
112 else:
113 reldir_msg = ""
114 relative_path = relative_path_to(reldir)
115 if possible_declarators:
116 print(f"Possible declarations for function '{fname}' in the following file(s){reldir_msg}:")
117 print(
118 " "
119 + "\n ".join(
120 sorted([os.path.relpath(path, start=reldir) for path in possible_declarators])
121 )
122 )
123 if possible_definers:
124 print(f"Possible definitions for function '{fname}' in the following file(s){reldir_msg}:")
125 print(
126 " "
127 + "\n ".join(sorted([os.path.relpath(path, start=reldir) for path in possible_definers]))
128 )