PyCG 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. micro-benchmark/__init__.py +0 -0
  2. micro-benchmark/args_test.py +25 -0
  3. micro-benchmark/assignments_test.py +19 -0
  4. micro-benchmark/base.py +87 -0
  5. micro-benchmark/builtins_test.py +16 -0
  6. micro-benchmark/classes_test.py +73 -0
  7. micro-benchmark/create_pytests.py +42 -0
  8. micro-benchmark/decorators_test.py +28 -0
  9. micro-benchmark/dicts_test.py +43 -0
  10. micro-benchmark/direct_calls_test.py +19 -0
  11. micro-benchmark/dynamic_test.py +10 -0
  12. micro-benchmark/exceptions_test.py +16 -0
  13. micro-benchmark/external_test.py +25 -0
  14. micro-benchmark/functions_test.py +19 -0
  15. micro-benchmark/generators_test.py +25 -0
  16. micro-benchmark/imports_test.py +49 -0
  17. micro-benchmark/kwargs_test.py +16 -0
  18. micro-benchmark/lambdas_test.py +22 -0
  19. micro-benchmark/lists_test.py +31 -0
  20. micro-benchmark/mro_test.py +28 -0
  21. micro-benchmark/returns_test.py +19 -0
  22. micro-benchmark-key-errs/__init__.py +0 -0
  23. micro-benchmark-key-errs/assignments_test.py +16 -0
  24. micro-benchmark-key-errs/base.py +81 -0
  25. micro-benchmark-key-errs/classes_test.py +25 -0
  26. micro-benchmark-key-errs/create_pytests.py +42 -0
  27. micro-benchmark-key-errs/dicts_test.py +34 -0
  28. micro-benchmark-key-errs/kwargs_test.py +13 -0
  29. micro-benchmark-key-errs/lists_test.py +13 -0
  30. micro-benchmark-key-errs/parameters_test.py +16 -0
  31. pycg/__init__.py +0 -0
  32. pycg/__main__.py +104 -0
  33. pycg/formats/__init__.py +23 -0
  34. pycg/formats/as_graph.py +32 -0
  35. pycg/formats/base.py +23 -0
  36. pycg/formats/fasten.py +253 -0
  37. pycg/formats/simple.py +32 -0
  38. pycg/machinery/__init__.py +0 -0
  39. pycg/machinery/callgraph.py +59 -0
  40. pycg/machinery/classes.py +77 -0
  41. pycg/machinery/definitions.py +219 -0
  42. pycg/machinery/imports.py +220 -0
  43. pycg/machinery/key_err.py +34 -0
  44. pycg/machinery/modules.py +66 -0
  45. pycg/machinery/pointers.py +146 -0
  46. pycg/machinery/scopes.py +143 -0
  47. pycg/processing/__init__.py +0 -0
  48. pycg/processing/base.py +522 -0
  49. pycg/processing/cgprocessor.py +230 -0
  50. pycg/processing/keyerrprocessor.py +82 -0
  51. pycg/processing/postprocessor.py +308 -0
  52. pycg/processing/preprocessor.py +375 -0
  53. pycg/pycg.py +229 -0
  54. pycg/utils/__init__.py +22 -0
  55. pycg/utils/common.py +39 -0
  56. pycg/utils/constants.py +42 -0
  57. pycg-0.0.3.dist-info/LICENCE +201 -0
  58. pycg-0.0.3.dist-info/METADATA +150 -0
  59. pycg-0.0.3.dist-info/RECORD +62 -0
  60. pycg-0.0.3.dist-info/WHEEL +5 -0
  61. pycg-0.0.3.dist-info/entry_points.txt +3 -0
  62. pycg-0.0.3.dist-info/top_level.txt +3 -0
@@ -0,0 +1,522 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ import ast
22
+ import os
23
+
24
+ from pycg import utils
25
+ from pycg.machinery.definitions import Definition
26
+
27
+ class ProcessingBase(ast.NodeVisitor):
28
+ def __init__(self, filename, modname, modules_analyzed):
29
+ self.modname = modname
30
+
31
+ self.modules_analyzed = modules_analyzed
32
+ self.modules_analyzed.add(self.modname)
33
+
34
+ self.filename = os.path.abspath(filename)
35
+
36
+ with open(filename, "rt") as f:
37
+ self.contents = f.read()
38
+
39
+ self.name_stack = []
40
+ self.method_stack = []
41
+ self.last_called_names = None
42
+
43
+ def get_modules_analyzed(self):
44
+ return self.modules_analyzed
45
+
46
+ def merge_modules_analyzed(self, analyzed):
47
+ self.modules_analyzed = self.modules_analyzed.union(analyzed)
48
+
49
+ @property
50
+ def current_ns(self):
51
+ return ".".join(self.name_stack)
52
+
53
+ @property
54
+ def current_method(self):
55
+ return ".".join(self.method_stack)
56
+
57
+ def visit_Module(self, node):
58
+ self.name_stack.append(self.modname)
59
+ self.method_stack.append(self.modname)
60
+ self.scope_manager.get_scope(self.modname).reset_counters()
61
+ self.generic_visit(node)
62
+ self.method_stack.pop()
63
+ self.name_stack.pop()
64
+
65
+ def visit_FunctionDef(self, node):
66
+ self.name_stack.append(node.name)
67
+ self.method_stack.append(node.name)
68
+ self.scope_manager.get_scope(self.current_ns).reset_counters()
69
+ for stmt in node.body:
70
+ self.visit(stmt)
71
+ self.method_stack.pop()
72
+ self.name_stack.pop()
73
+
74
+ def visit_Lambda(self, node, lambda_name=None):
75
+ lambda_ns = utils.join_ns(self.current_ns, lambda_name)
76
+ if not self.scope_manager.get_scope(lambda_ns):
77
+ self.scope_manager.create_scope(lambda_ns,
78
+ self.scope_manager.get_scope(self.current_ns))
79
+ self.name_stack.append(lambda_name)
80
+ self.method_stack.append(lambda_name)
81
+ self.visit(node.body)
82
+ self.method_stack.pop()
83
+ self.name_stack.pop()
84
+
85
+ def visit_For(self, node):
86
+ for item in node.body:
87
+ self.visit(item)
88
+
89
+ def visit_Dict(self, node):
90
+ counter = self.scope_manager.get_scope(self.current_ns).inc_dict_counter()
91
+ dict_name = utils.get_dict_name(counter)
92
+
93
+ sc = self.scope_manager.get_scope(utils.join_ns(self.current_ns, dict_name))
94
+ if not sc:
95
+ return
96
+ self.name_stack.append(dict_name)
97
+ sc.reset_counters()
98
+ for key, val in zip(node.keys, node.values):
99
+ if key:
100
+ self.visit(key)
101
+ if val:
102
+ self.visit(val)
103
+ self.name_stack.pop()
104
+
105
+ def visit_List(self, node):
106
+ counter = self.scope_manager.get_scope(self.current_ns).inc_list_counter()
107
+ list_name = utils.get_list_name(counter)
108
+
109
+ sc = self.scope_manager.get_scope(utils.join_ns(self.current_ns, list_name))
110
+ if not sc:
111
+ return
112
+ self.name_stack.append(list_name)
113
+ sc.reset_counters()
114
+ for elt in node.elts:
115
+ self.visit(elt)
116
+ self.name_stack.pop()
117
+
118
+ def visit_BinOp(self, node):
119
+ self.visit(node.left)
120
+ self.visit(node.right)
121
+
122
+ def visit_ClassDef(self, node):
123
+ self.name_stack.append(node.name)
124
+ self.method_stack.append(node.name)
125
+ self.scope_manager.get_scope(self.current_ns).reset_counters()
126
+ for stmt in node.body:
127
+ self.visit(stmt)
128
+ self.method_stack.pop()
129
+ self.name_stack.pop()
130
+
131
+ def visit_Tuple(self, node):
132
+ for elt in node.elts:
133
+ self.visit(elt)
134
+
135
+ def _handle_assign(self, targetns, decoded):
136
+ defi = self.def_manager.get(targetns)
137
+ if not defi:
138
+ defi = self.def_manager.create(targetns, utils.constants.NAME_DEF)
139
+
140
+ # check if decoded is iterable
141
+ try:
142
+ iter(decoded)
143
+ except TypeError:
144
+ return defi
145
+
146
+ for d in decoded:
147
+ if isinstance(d, Definition):
148
+ defi.get_name_pointer().add(d.get_ns())
149
+ else:
150
+ defi.get_lit_pointer().add(d)
151
+ return defi
152
+
153
+ def _visit_return(self, node):
154
+ if not node or not node.value:
155
+ return
156
+
157
+ self.visit(node.value)
158
+
159
+ return_ns = utils.join_ns(self.current_ns, utils.constants.RETURN_NAME)
160
+ self._handle_assign(return_ns, self.decode_node(node.value))
161
+
162
+ def _get_target_ns(self, target):
163
+ if isinstance(target, ast.Name):
164
+ return [utils.join_ns(self.current_ns, target.id)]
165
+ if isinstance(target, ast.Attribute):
166
+ bases = self._retrieve_base_names(target)
167
+ res = []
168
+ for base in bases:
169
+ res.append(utils.join_ns(base, target.attr))
170
+ return res
171
+ if isinstance(target, ast.Subscript):
172
+ return self.retrieve_subscript_names(target)
173
+ return []
174
+
175
+ def _visit_assign(self, value, targets):
176
+ self.visit(value)
177
+
178
+ decoded = self.decode_node(value)
179
+
180
+ def do_assign(decoded, target):
181
+ self.visit(target)
182
+ if isinstance(target, ast.Tuple):
183
+ for pos, elt in enumerate(target.elts):
184
+ if pos < len(decoded):
185
+ do_assign(decoded[pos], elt)
186
+ else:
187
+ targetns = self._get_target_ns(target)
188
+ for tns in targetns:
189
+ if not tns:
190
+ continue
191
+ defi = self._handle_assign(tns, decoded)
192
+ splitted = tns.split(".")
193
+ self.scope_manager.handle_assign(".".join(splitted[:-1]), splitted[-1], defi)
194
+
195
+ for target in targets:
196
+ do_assign(decoded, target)
197
+
198
+ def decode_node(self, node):
199
+ if isinstance(node, ast.Name):
200
+ return [self.scope_manager.get_def(self.current_ns, node.id)]
201
+ elif isinstance(node, ast.Call):
202
+ decoded = self.decode_node(node.func)
203
+ return_defs = []
204
+ for called_def in decoded:
205
+ if not isinstance(called_def, Definition):
206
+ continue
207
+
208
+ return_ns = utils.constants.INVALID_NAME
209
+ if called_def.get_type() == utils.constants.FUN_DEF:
210
+ return_ns = utils.join_ns(called_def.get_ns(), utils.constants.RETURN_NAME)
211
+ elif called_def.get_type() == utils.constants.CLS_DEF:
212
+ return_ns = called_def.get_ns()
213
+ defi = self.def_manager.get(return_ns)
214
+ if defi:
215
+ return_defs.append(defi)
216
+
217
+ return return_defs
218
+ elif isinstance(node, ast.Lambda):
219
+ lambda_counter = self.scope_manager.get_scope(self.current_ns).get_lambda_counter()
220
+ lambda_name = utils.get_lambda_name(lambda_counter)
221
+ return [self.scope_manager.get_def(self.current_ns, lambda_name)]
222
+ elif isinstance(node, ast.Tuple):
223
+ decoded = []
224
+ for elt in node.elts:
225
+ decoded.append(self.decode_node(elt))
226
+ return decoded
227
+ elif isinstance(node, ast.BinOp):
228
+ decoded_left = self.decode_node(node.left)
229
+ decoded_right = self.decode_node(node.right)
230
+ # return the non definition types if we're talking about a binop
231
+ # since we only care about the type of the return (num, str, etc)
232
+ if not isinstance(decoded_left, Definition):
233
+ return decoded_left
234
+ if not isinstance(decoded_right, Definition):
235
+ return decoded_right
236
+ elif isinstance(node, ast.Attribute):
237
+ names = self._retrieve_attribute_names(node)
238
+ defis = []
239
+ for name in names:
240
+ defi = self.def_manager.get(name)
241
+ if defi:
242
+ defis.append(defi)
243
+ return defis
244
+ elif isinstance(node, ast.Num):
245
+ return [node.n]
246
+ elif isinstance(node, ast.Str):
247
+ return [node.s]
248
+ elif self._is_literal(node):
249
+ return [node]
250
+ elif isinstance(node, ast.Dict):
251
+ dict_counter = self.scope_manager.get_scope(self.current_ns).get_dict_counter()
252
+ dict_name = utils.get_dict_name(dict_counter)
253
+ scope_def = self.scope_manager.get_def(self.current_ns, dict_name)
254
+ return [self.scope_manager.get_def(self.current_ns, dict_name)]
255
+ elif isinstance(node, ast.List):
256
+ list_counter = self.scope_manager.get_scope(self.current_ns).get_list_counter()
257
+ list_name = utils.get_list_name(list_counter)
258
+ scope_def = self.scope_manager.get_def(self.current_ns, list_name)
259
+ return [self.scope_manager.get_def(self.current_ns, list_name)]
260
+ elif isinstance(node, ast.Subscript):
261
+ names = self.retrieve_subscript_names(node)
262
+ defis = []
263
+ for name in names:
264
+ defi = self.def_manager.get(name)
265
+ if defi:
266
+ defis.append(defi)
267
+ return defis
268
+
269
+ return []
270
+
271
+ def _is_literal(self, item):
272
+ return isinstance(item, int) or isinstance(item, str) or isinstance(item, float)
273
+
274
+ def _retrieve_base_names(self, node):
275
+ if not isinstance(node, ast.Attribute):
276
+ raise Exception("The node is not an attribute")
277
+
278
+ if not getattr(self, "closured", None):
279
+ return set()
280
+
281
+ decoded = self.decode_node(node.value)
282
+ if not decoded:
283
+ return set()
284
+
285
+ names = set()
286
+ for name in decoded:
287
+ if not name or not isinstance(name, Definition):
288
+ continue
289
+
290
+ for base in self.closured.get(name.get_ns(), []):
291
+ cls = self.class_manager.get(base)
292
+ if not cls:
293
+ continue
294
+
295
+ for item in cls.get_mro():
296
+ names.add(item)
297
+ return names
298
+
299
+
300
+ def _retrieve_parent_names(self, node):
301
+ if not isinstance(node, ast.Attribute):
302
+ raise Exception("The node is not an attribute")
303
+
304
+ decoded = self.decode_node(node.value)
305
+ if not decoded:
306
+ return set()
307
+
308
+ names = set()
309
+ for parent in decoded:
310
+ if not parent or not isinstance(parent, Definition):
311
+ continue
312
+ if getattr(self, "closured", None) and self.closured.get(parent.get_ns(), None):
313
+ names = names.union(self.closured.get(parent.get_ns()))
314
+ else:
315
+ names.add(parent.get_ns())
316
+ return names
317
+
318
+ def _retrieve_attribute_names(self, node):
319
+ if not getattr(self, "closured", None):
320
+ return set()
321
+
322
+ parent_names = self._retrieve_parent_names(node)
323
+ names = set()
324
+ for parent_name in parent_names:
325
+ for name in self.closured.get(parent_name, []):
326
+ defi = self.def_manager.get(name)
327
+ if not defi:
328
+ continue
329
+ if defi.get_type() == utils.constants.CLS_DEF:
330
+ cls_names = self.find_cls_fun_ns(defi.get_ns(), node.attr)
331
+ if cls_names:
332
+ names = names.union(cls_names)
333
+ if defi.get_type() in [utils.constants.FUN_DEF, utils.constants.MOD_DEF]:
334
+ names.add(utils.join_ns(name, node.attr))
335
+ if defi.get_type() == utils.constants.EXT_DEF:
336
+ # HACK: extenral attributes can lead to infinite loops
337
+ # Identify them here
338
+ if node.attr in name:
339
+ continue
340
+ ext_name = utils.join_ns(name, node.attr)
341
+ if not self.def_manager.get(ext_name):
342
+ self.def_manager.create(ext_name, utils.constants.EXT_DEF)
343
+ names.add(ext_name)
344
+ return names
345
+
346
+ def iterate_call_args(self, defi, node):
347
+ for pos, arg in enumerate(node.args):
348
+ self.visit(arg)
349
+ decoded = self.decode_node(arg)
350
+ if defi.is_function_def():
351
+ pos_arg_names = defi.get_name_pointer().get_pos_arg(pos)
352
+ # if arguments for this position exist update their namespace
353
+ if not pos_arg_names:
354
+ continue
355
+ for name in pos_arg_names:
356
+ arg_def = self.def_manager.get(name)
357
+ if not arg_def:
358
+ continue
359
+ for d in decoded:
360
+ if isinstance(d, Definition):
361
+ arg_def.get_name_pointer().add(d.get_ns())
362
+ else:
363
+ arg_def.get_lit_pointer().add(d)
364
+ else:
365
+ for d in decoded:
366
+ if isinstance(d, Definition):
367
+ defi.get_name_pointer().add_pos_arg(pos, None, d.get_ns())
368
+ else:
369
+ defi.get_name_pointer().add_pos_lit_arg(pos, None, d)
370
+
371
+ for keyword in node.keywords:
372
+ self.visit(keyword.value)
373
+ decoded = self.decode_node(keyword.value)
374
+ if defi.is_function_def():
375
+ arg_names = defi.get_name_pointer().get_arg(keyword.arg)
376
+ if not arg_names:
377
+ continue
378
+ for name in arg_names:
379
+ arg_def = self.def_manager.get(name)
380
+ if not arg_def:
381
+ continue
382
+ for d in decoded:
383
+ if isinstance(d, Definition):
384
+ arg_def.get_name_pointer().add(d.get_ns())
385
+ else:
386
+ arg_def.get_lit_pointer().add(d)
387
+ else:
388
+ for d in decoded:
389
+ if isinstance(d, Definition):
390
+ defi.get_name_pointer().add_arg(keyword.arg, d.get_ns())
391
+ else:
392
+ defi.get_name_pointer().add_lit_arg(keyword.arg, d)
393
+
394
+ def retrieve_subscript_names(self, node):
395
+ if not isinstance(node, ast.Subscript):
396
+ raise Exception("The node is not an subcript")
397
+
398
+ if not getattr(self, "closured", None):
399
+ return set()
400
+
401
+ if getattr(node.slice, "value", None) and self._is_literal(node.slice.value):
402
+ sl_names = [node.slice.value]
403
+ else:
404
+ sl_names = self.decode_node(node.slice)
405
+
406
+ val_names = self.decode_node(node.value)
407
+
408
+ decoded_vals = set()
409
+ keys = set()
410
+ full_names = set()
411
+ # get all names associated with this variable name
412
+ for n in val_names:
413
+ if n and isinstance(n, Definition) and self.closured.get(n.get_ns(), None):
414
+ decoded_vals |= self.closured.get(n.get_ns())
415
+ for s in sl_names:
416
+ if isinstance(s, Definition) and self.closured.get(s.get_ns(), None):
417
+ # we care about the literals pointed by the name
418
+ # not the namespaces, so retrieve the literals pointed
419
+ for name in self.closured.get(s.get_ns()):
420
+ defi = self.def_manager.get(name)
421
+ if not defi:
422
+ continue
423
+ keys |= defi.get_lit_pointer().get()
424
+ elif isinstance(s, str):
425
+ keys.add(s)
426
+ elif isinstance(s, int):
427
+ keys.add(utils.get_int_name(s))
428
+
429
+ for d in decoded_vals:
430
+ for key in keys:
431
+ # check for existence of var name and key combination
432
+ str_key = str(key)
433
+ if isinstance(key, int):
434
+ str_key = utils.get_int_name(key)
435
+ full_ns = utils.join_ns(d, str_key)
436
+ full_names.add(full_ns)
437
+
438
+ return full_names
439
+
440
+ def retrieve_call_names(self, node):
441
+ names = set()
442
+ if isinstance(node.func, ast.Name):
443
+ defi = self.scope_manager.get_def(self.current_ns, node.func.id)
444
+ if defi:
445
+ names = self.closured.get(defi.get_ns(), None)
446
+ elif isinstance(node.func, ast.Call) and self.last_called_names:
447
+ for name in self.last_called_names:
448
+ return_ns = utils.join_ns(name, utils.constants.RETURN_NAME)
449
+ returns = self.closured.get(return_ns)
450
+ if not returns:
451
+ continue
452
+ for ret in returns:
453
+ defi = self.def_manager.get(ret)
454
+ names.add(defi.get_ns())
455
+ elif isinstance(node.func, ast.Attribute):
456
+ names = self._retrieve_attribute_names(node.func)
457
+ elif isinstance(node.func, ast.Subscript):
458
+ # Calls can be performed only on single indices, not ranges
459
+ full_names = self.retrieve_subscript_names(node.func)
460
+ for n in full_names:
461
+ if self.closured.get(n, None):
462
+ names |= self.closured.get(n)
463
+
464
+ return names
465
+
466
+ def analyze_submodules(self, cls, *args, **kwargs):
467
+ imports = self.import_manager.get_imports(self.modname)
468
+
469
+ for imp in imports:
470
+ self.analyze_submodule(cls, imp, *args, **kwargs)
471
+
472
+ def analyze_submodule(self, cls, imp, *args, **kwargs):
473
+ if imp in self.get_modules_analyzed():
474
+ return
475
+
476
+ fname = self.import_manager.get_filepath(imp)
477
+
478
+ if not fname or not self.import_manager.get_mod_dir() in fname:
479
+ return
480
+
481
+ self.import_manager.set_current_mod(imp, fname)
482
+
483
+ visitor = cls(fname, imp, *args, **kwargs)
484
+ visitor.analyze()
485
+ self.merge_modules_analyzed(visitor.get_modules_analyzed())
486
+
487
+ self.import_manager.set_current_mod(self.modname, self.filename)
488
+
489
+ def find_cls_fun_ns(self, cls_name, fn):
490
+ cls = self.class_manager.get(cls_name)
491
+ if not cls:
492
+ return set()
493
+
494
+ ext_names = set()
495
+ for item in cls.get_mro():
496
+ ns = utils.join_ns(item, fn)
497
+ names = set()
498
+ if getattr(self, "closured", None) and self.closured.get(ns, None):
499
+ names = self.closured[ns]
500
+ else:
501
+ names.add(ns)
502
+
503
+ if self.def_manager.get(ns):
504
+ return names
505
+
506
+ parent = self.def_manager.get(item)
507
+ if parent and parent.get_type() == utils.constants.EXT_DEF:
508
+ ext_names.add(ns)
509
+
510
+ for name in ext_names:
511
+ self.def_manager.create(name, utils.constants.EXT_DEF)
512
+ self.add_ext_mod_node(name)
513
+ return ext_names
514
+
515
+ def add_ext_mod_node(self, name):
516
+ ext_modname = name.split(".")[0]
517
+ ext_mod = self.module_manager.get(ext_modname)
518
+ if not ext_mod:
519
+ ext_mod = self.module_manager.create(ext_modname, None, external=True)
520
+ ext_mod.add_method(ext_modname)
521
+
522
+ ext_mod.add_method(name)