Debian Codegraph @

src/backend/plugins/CtagsCache.py

raw symbols SCIP
1 # Copyright (c) 2010 Anil Kumar
2 # All rights reserved.
3 #
4 # License: BSD
5
6 import os, re, subprocess
7 from datetime import datetime
8
9 from PyQt6.QtCore import QThread
10
11 def _eintr_retry_call(func, *args):
12 while True:
13 try:
14 return func(*args)
15 except OSError as e:
16 if e.errno == errno.EINTR:
17 continue
18 raise
19
20 #class CtagsInfo:
21 #def __init__(self):
22 #pass
23
24 #@staticmethod
25 #def lang_suffixes():
26 #cmd = 'ctags --list-maps'
27 #args = cmd.split()
28 #import subprocess
29 #proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
30 #(out_data, err_data) = proc.communicate()
31 #out_data = out_data.decode()
32 #err_data = err_data.decode()
33 #res = re.split(r'\r?\n', out_data)
34 # res = out_data
35 #res = [ line.split(None, 1) for line in res if line != '' ]
36 #d = {}
37 #for line in res:
38 #import fnmatch
39 #fn_pats = line[1] .split()
40 #print line[0], fn_pats
41 #re_pats = '|'.join(fnmatch.translate(p) for p in fn_pats)
42 #print line[0], re_pats
43 #d[line[0]] = re_pats
44 #print d
45 #print 'ctag.lang'
46 #CtagsInfo.lang_suffixes()
47
48 class CtagsThread(QThread):
49 thread_list = []
50
51 def __init__(self, sig):
52 QThread.__init__(self)
53
54 self.sig = sig
55 self.ct_dict = {}
56
57 self.finished.connect(self._finished_cb)
58 CtagsThread.thread_list.append(self)
59
60 def _finished_cb(self):
61 #print 'CtagsThread.finished', len(self.ct_dict)
62 CtagsThread.thread_list.remove(self)
63 for k in self.ct_dict:
64 ct_cache[k] = self.ct_dict[k]
65
66 self.res = self.parse_result(self.res, self.sig)
67 if self.res != None:
68 self.sig.emit_result(self.res)
69
70 def ctags_bsearch(self, ct, n):
71 x = -1
72 y = len(ct) - 1
73
74 #print f, n
75 while x < y:
76 m = (x + y + 1) // 2
77 #print '(', x, y, m, ')'
78 if ct[m][1] > n:
79 #print 'y: m -1', ct[m][1]
80 m = m - 1
81 y = m
82 continue
83 if ct[m][1] < n:
84 #print 'x: m', ct[m][1]
85 x = m
86 continue
87 break
88 if y == -1:
89 return y
90 #assert x == m or y == m or ct[m][1] == n
91 return m
92
93 def _ctags_fix(self, line):
94 f = line[1]
95 n = int(line[2])
96 ct = self.ct_dict[f]
97
98 m = self.ctags_bsearch(ct, n)
99 if m == -1:
100 return True
101 if ct[m][1] != n:
102 if ct[m][2] in ['variable']:
103 #line[0] = '***** SMART *****'
104 #print line
105 return True
106 if f.endswith('.py'):
107 while m > 0 and (ct[m][2] in ['namespace']):
108 m = m - 1
109 if m == - 1:
110 return True
111 if ct[m][1] == n:
112 if self.cmd_str == 'DEF':
113 x = m
114 y = m
115 while x > 1 and ct[x - 1][1] == n:
116 x = x - 1
117 while y < len(ct) - 1 and ct[y + 1][1] == n:
118 y = y + 1
119 if x > y:
120 return False
121 for m in range(x, y + 1):
122 reqPat = self.sig.sym + '$'
123 if re.match(reqPat, ct[m][0]):
124 line[0] = ct[m][0]
125 return True
126 return False
127 else:
128 if self.cmd_str == 'DEF':
129 return False
130 if self.cmd_str == '-->':
131 if f.endswith('.tac'):
132 if ct[m][2] in ['reactor']:
133 line[0] = ct[m][0].split('=>')[0].strip() + "Is"
134 return True
135 line[0] = ct[m][0]
136 return True
137
138 def ct_override(self, fl):
139 pattern = os.getenv('SEASCOPE_CTAGS_OVERRIDE_PATTERN')
140 delim1 = os.getenv('SEASCOPE_CTAGS_OVERRIDE_DELIM_START')
141 delim2 = os.getenv('SEASCOPE_CTAGS_OVERRIDE_DELIM_END')
142 if not (pattern and delim1 and delim2):
143 return
144
145 res = {}
146 for f in fl:
147 args = ['grep', '-En', "%s" % pattern, "%s" % f]
148 try:
149 proc = subprocess.Popen(args, stdout=subprocess.PIPE)
150 (out_data, err_data) = _eintr_retry_call(proc.communicate)
151 out_data = out_data.decode()
152 out_data = out_data.split('\n')
153 except Exception as e:
154 out_data = [
155 'Failed to run ct override cmd\tignore\t0;\t ',
156 'cmd: %s\tignore\t0;\t ' % ' '.join(args),
157 'error: %s\tignore\t0;\t ' % str(e),
158 'ctags not installed ?\tignore\t0;\t ',
159 ]
160 f_res = {}
161 for line in out_data:
162 if (line == ''):
163 break
164 line = line.split(':', 1)
165 num = line[0]
166 inx1 = line[1].find(delim1) + 1
167 inx2 = line[1].find(delim2)
168 sym = line[1][inx1:inx2]
169 f_res[num] = [sym, num, 'function']
170 res[f] = f_res
171 return res
172
173 def runCtagsCustom(self, fl):
174 custom_map = os.getenv('SEASCOPE_CTAGS_SUFFIX_CMD_MAP')
175 if not custom_map:
176 return []
177 try:
178 custom_map = eval(custom_map)
179 except:
180 print('SEASCOPE_CTAGS_SUFFIX_CMD_MAP has errors')
181 return []
182
183 cmd_list = []
184 for (suffix, cmd) in custom_map:
185 _fl = [ f for f in fl if f.endswith(suffix) ]
186 args = cmd.split()
187 args += _fl
188 cmd_list.append(args)
189
190 if not len(cmd_list):
191 return []
192
193 out_data_all = []
194 for args in cmd_list:
195 proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
196 (out_data, err_data) = proc.communicate('\n'.join(fl).encode())
197 out_data = out_data.decode()
198 out_data = re.split(r'\r?\n', out_data)
199 out_data_all += out_data
200 return out_data_all
201
202 def _run_ctags(self):
203 override_res = self.ct_override(self.file_list)
204
205 cmd = 'ctags -n -u --fields=+K -L - -f -'
206 opt_I_file = os.getenv('SEASCOPE_CTAGS_OPT_I_FILE')
207 if opt_I_file and os.path.isfile(opt_I_file):
208 cmd += ' -I ' + opt_I_file
209 args = cmd.split()
210 proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
211 (out_data, err_data) = proc.communicate('\n'.join(self.file_list).encode())
212 out_data = out_data.decode()
213 out_data = re.split(r'\r?\n', out_data)
214 out_data += self.runCtagsCustom(self.file_list)
215
216 for line in out_data:
217 if line == '':
218 continue
219 line = line.split('\t')
220 f = line[1]
221 num = line[2].split(';', 1)[0]
222 if override_res:
223 override_ent = override_res.get(f, {}).pop(num, None)
224 if override_ent:
225 line[0] = override_ent[0]
226 line = [line[0], int(num), line[3]]
227 self.ct_dict[f].append(line)
228 if override_res:
229 for (f, o_res) in override_res.items():
230 if o_res:
231 res = self.ct_dict[f]
232 for line in o_res.values():
233 line = [line[0], int(line[1]), line[2]]
234 res.append(line)
235 self.ct_dict[f] = sorted(res, key=lambda e: e[1])
236
237 def prepare_file_list(self):
238 #t1 = datetime.now()
239 flist = set()
240 for line in self.res:
241 if line[0] in self.cond_list:
242 if line[1] not in ct_cache:
243 flist.add(line[1])
244 else:
245 self.ct_dict[line[1]] = ct_cache[line[1]]
246 for f in flist:
247 self.ct_dict[f] = []
248
249 #t2 = datetime.now()
250 #print ' ', len(flist), 'flist', t2 - t1
251
252 self.file_list = flist
253
254 def apply_fix(self, cmd_str, res, cond_list):
255 self.cmd_str = cmd_str
256 self.res = res
257 self.cond_list = cond_list
258
259 self.prepare_file_list()
260 self.start()
261
262 def run(self):
263 #t2 = datetime.now()
264
265 self._run_ctags()
266
267 #t3 = datetime.now()
268 #print ' ct', t3 - t2
269 res = []
270 for line in self.res:
271 if line[0] not in self.cond_list:
272 continue
273 if not self._ctags_fix(line):
274 continue
275 res.append(line)
276 self.res = res
277 #t4 = datetime.now()
278 #print ' fix', t4 - t3
279 #print ' total', t4 - t2
280
281 def _filter_res(self, res, sig):
282 req = sig.sym
283 out_res = []
284 if self.cmd_str == 'DEF':
285 import_re = re.compile(r'^\s*import\s+')
286 for line in res:
287 reqPat = req + '$'
288 if not re.match(reqPat, line[0]):
289 continue
290 if import_re.search(line[3]) and line[1].endswith('.py'):
291 continue
292 out_res.append(line)
293 return out_res
294 if self.cmd_str == '-->':
295 call_re = re.compile(r'\\b%s\\b\s*\(' % req)
296 extern_re = re.compile(r'^\s*extern\s+')
297 reactor_re = re.compile(r'\\b(\w+::)*(\w+)\s*=>.*\\b%s\\b' % req)
298 comment_re = re.compile(r'^\s*(\*\s|/\*|\*/|//\s|# )')
299 func_ptr_re = re.compile(r'\\b(\w+)\s*(=|:)\s*%s\s*[,;:)]' % req)
300 func_as_arg_re = re.compile(r'(^\s*|[(,]\s*)(\w+(\.|->))*%s\s*[,)]' % req);
301 def _check_line():
302 if line[1].endswith('.tac'):
303 if '=>' in line[3]:
304 grp = reactor_re.search(line[3])
305 if grp:
306 line[0] = grp.group(2) + "Is"
307 return True
308 # fallthru
309 if line[0] == req:
310 if not re.search(r'(\.|->)%s\\b' % req, line[3]):
311 return False
312 return True
313 if call_re.search(line[3]):
314 if extern_re.search(line[3]):
315 return False
316 return True
317 grp = func_ptr_re.search(line[3])
318 if grp:
319 line[0] = grp.group(1)
320 return True
321 if not func_as_arg_re.search(line[3]):
322 False
323 return True
324 for line in res:
325 if not _check_line():
326 continue
327 if line[0] == '<unknown>':
328 continue
329 if comment_re.search(line[3]):
330 continue
331 out_res.append(line)
332 return out_res
333 if self.cmd_str == '<--':
334 return res
335 if self.cmd_str == 'INC':
336 inc_re = re.compile(r'^\s*(#\s*include|(from\s+[^\s]+\s+)?import)\s+.*%s.*' % req)
337 for line in res:
338 if not inc_re.search(line[3]):
339 continue
340 out_res.append(line)
341 return out_res
342 return res
343
344 def parse_result(self, res, sig):
345 res = self._filter_res(res, sig)
346 return res
347
348 ct_cache = {}
349
350 def flush():
351 #print 'flushing ctags cache...'
352 global ct_cache
353 ct_cache = {}
354