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,375 @@
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
+ import importlib
24
+
25
+ from pycg.machinery.definitions import DefinitionManager, Definition
26
+ from pycg import utils
27
+ from pycg.processing.base import ProcessingBase
28
+
29
+ class PreProcessor(ProcessingBase):
30
+ def __init__(self, filename, modname,
31
+ import_manager, scope_manager, def_manager, class_manager,
32
+ module_manager, modules_analyzed=None):
33
+ super().__init__(filename, modname, modules_analyzed)
34
+
35
+ self.modname = modname
36
+ self.mod_dir = "/".join(self.filename.split("/")[:-1])
37
+
38
+ self.import_manager = import_manager
39
+ self.scope_manager = scope_manager
40
+ self.def_manager = def_manager
41
+ self.class_manager = class_manager
42
+ self.module_manager = module_manager
43
+
44
+
45
+ def _get_fun_defaults(self, node):
46
+ defaults = {}
47
+ start = len(node.args.args) - len(node.args.defaults)
48
+ for cnt, d in enumerate(node.args.defaults, start=start):
49
+ if not d:
50
+ continue
51
+
52
+ self.visit(d)
53
+ defaults[node.args.args[cnt].arg] = self.decode_node(d)
54
+
55
+ start = len(node.args.kwonlyargs) - len(node.args.kw_defaults)
56
+ for cnt, d in enumerate(node.args.kw_defaults, start=start):
57
+ if not d:
58
+ continue
59
+ self.visit(d)
60
+ defaults[node.args.kwonlyargs[cnt].arg] = self.decode_node(d)
61
+
62
+ return defaults
63
+
64
+ def analyze_submodule(self, modname):
65
+ super().analyze_submodule(PreProcessor, modname,
66
+ self.import_manager, self.scope_manager, self.def_manager, self.class_manager,
67
+ self.module_manager, modules_analyzed=self.get_modules_analyzed())
68
+
69
+ def visit_Module(self, node):
70
+ def iterate_mod_items(items, const):
71
+ for item in items:
72
+ defi = self.def_manager.get(item)
73
+ if not defi:
74
+ defi = self.def_manager.create(item, const)
75
+
76
+ splitted = item.split(".")
77
+ name = splitted[-1]
78
+ parentns = ".".join(splitted[:-1])
79
+ self.scope_manager.get_scope(parentns).add_def(name, defi)
80
+
81
+ self.import_manager.set_current_mod(self.modname, self.filename)
82
+
83
+ mod = self.module_manager.create(self.modname, self.filename)
84
+
85
+ first = 1
86
+ last = len(self.contents.splitlines())
87
+ if last == 0:
88
+ first = 0
89
+ mod.add_method(self.modname, first, last)
90
+
91
+ root_sc = self.scope_manager.get_scope(self.modname)
92
+ if not root_sc:
93
+ # initialize module scopes
94
+ items = self.scope_manager.handle_module(self.modname,
95
+ self.filename, self.contents)
96
+
97
+ root_sc = self.scope_manager.get_scope(self.modname)
98
+ root_defi = self.def_manager.get(self.modname)
99
+ if not root_defi:
100
+ root_defi = self.def_manager.create(self.modname, utils.constants.MOD_DEF)
101
+ root_sc.add_def(self.modname.split(".")[-1], root_defi)
102
+
103
+ # create function and class defs and add them to their scope
104
+ # we do this here, because scope_manager doesn't have an
105
+ # interface with def_manager, and we want function definitions
106
+ # to have the correct points_to set
107
+ iterate_mod_items(items["functions"], utils.constants.FUN_DEF)
108
+ iterate_mod_items(items["classes"], utils.constants.CLS_DEF)
109
+
110
+ defi = self.def_manager.get(self.modname)
111
+ if not defi:
112
+ defi = self.def_manager.create(self.modname, utils.constants.MOD_DEF)
113
+
114
+ super().visit_Module(node)
115
+
116
+ def visit_Import(self, node, prefix='', level=0):
117
+ """
118
+ For imports of the form
119
+ `from something import anything`
120
+ prefix is set to "something".
121
+ For imports of the form
122
+ `from .relative import anything`
123
+ level is set to a number indicating the number
124
+ of parent directories (e.g. in this case level=1)
125
+ """
126
+ def handle_src_name(name):
127
+ # Get the module name and prepend prefix if necessary
128
+ src_name = name
129
+ if prefix:
130
+ src_name = prefix + "." + src_name
131
+ return src_name
132
+
133
+ def handle_scopes(imp_name, tgt_name, modname):
134
+ def create_def(scope, name, imported_def):
135
+ if not name in scope.get_defs():
136
+ def_ns = utils.join_ns(scope.get_ns(), name)
137
+ defi = self.def_manager.get(def_ns)
138
+ if not defi:
139
+ defi = self.def_manager.assign(def_ns, imported_def)
140
+ defi.get_name_pointer().add(imported_def.get_ns())
141
+ current_scope.add_def(name, defi)
142
+
143
+ current_scope = self.scope_manager.get_scope(self.current_ns)
144
+ imported_scope = self.scope_manager.get_scope(modname)
145
+ if tgt_name == "*":
146
+ for name, defi in imported_scope.get_defs().items():
147
+ create_def(current_scope, name, defi)
148
+ current_scope.get_def(name).get_name_pointer().add(defi.get_ns())
149
+ else:
150
+ # if it exists in the imported scope then copy it
151
+ defi = imported_scope.get_def(imp_name)
152
+ if not defi:
153
+ # maybe its a full namespace
154
+ defi = self.def_manager.get(imp_name)
155
+
156
+ if defi:
157
+ create_def(current_scope, tgt_name, defi)
158
+ current_scope.get_def(tgt_name).get_name_pointer().add(defi.get_ns())
159
+
160
+ def add_external_def(name, target):
161
+ # add an external def for the name
162
+ defi = self.def_manager.get(name)
163
+ if not defi:
164
+ defi = self.def_manager.create(name, utils.constants.EXT_DEF)
165
+ scope = self.scope_manager.get_scope(self.current_ns)
166
+ if target != "*":
167
+ # add a def for the target that points to the name
168
+ tgt_ns = utils.join_ns(scope.get_ns(), target)
169
+ tgt_defi = self.def_manager.get(tgt_ns)
170
+ if not tgt_defi:
171
+ tgt_defi = self.def_manager.create(tgt_ns, utils.constants.EXT_DEF)
172
+ tgt_defi.get_name_pointer().add(defi.get_ns())
173
+ scope.add_def(target, tgt_defi)
174
+
175
+ for import_item in node.names:
176
+ src_name = handle_src_name(import_item.name)
177
+ tgt_name = import_item.asname if import_item.asname else import_item.name
178
+ imported_name = self.import_manager.handle_import(src_name, level)
179
+
180
+ if not imported_name:
181
+ add_external_def(src_name, tgt_name)
182
+ continue
183
+
184
+ fname = self.import_manager.get_filepath(imported_name)
185
+ if not fname:
186
+ add_external_def(src_name, tgt_name)
187
+ continue
188
+ # only analyze modules under the current directory
189
+ if self.import_manager.get_mod_dir() in fname:
190
+ if not imported_name in self.modules_analyzed:
191
+ self.analyze_submodule(imported_name)
192
+ handle_scopes(import_item.name, tgt_name, imported_name)
193
+ else:
194
+ add_external_def(src_name, tgt_name)
195
+
196
+ # handle all modules that were not analyzed
197
+ for modname in self.import_manager.get_imports(self.modname):
198
+ fname = self.import_manager.get_filepath(modname)
199
+
200
+ if not fname:
201
+ continue
202
+ # only analyze modules under the current directory
203
+ if self.import_manager.get_mod_dir() in fname and \
204
+ not modname in self.modules_analyzed:
205
+ self.analyze_submodule(modname)
206
+
207
+
208
+ def visit_ImportFrom(self, node):
209
+ self.visit_Import(node, prefix=node.module, level=node.level)
210
+
211
+ def _get_last_line(self, node):
212
+ lines = sorted(list(ast.walk(node)), key=lambda x: x.lineno if hasattr(x, "lineno") else 0, reverse=True)
213
+ if not lines:
214
+ return node.lineno
215
+
216
+ last = getattr(lines[0], "lineno", node.lineno)
217
+ if last < node.lineno:
218
+ return node.lineno
219
+
220
+ return last
221
+
222
+ def _handle_function_def(self, node, fn_name):
223
+ current_def = self.def_manager.get(self.current_ns)
224
+
225
+ defaults = self._get_fun_defaults(node)
226
+
227
+ fn_def = self.def_manager.handle_function_def(self.current_ns, fn_name)
228
+
229
+ mod = self.module_manager.get(self.modname)
230
+ if not mod:
231
+ mod = self.module_manager.create(self.modname, self.filename)
232
+ mod.add_method(fn_def.get_ns(), node.lineno, self._get_last_line(node))
233
+
234
+ defs_to_create = []
235
+ name_pointer = fn_def.get_name_pointer()
236
+
237
+ # TODO: static methods can be created using the staticmethod() function too
238
+ is_static_method = False
239
+ if hasattr(node, "decorator_list"):
240
+ for decorator in node.decorator_list:
241
+ if isinstance(decorator, ast.Name) and decorator.id == utils.constants.STATIC_METHOD:
242
+ is_static_method = True
243
+
244
+ if current_def.get_type() == utils.constants.CLS_DEF and not is_static_method and node.args.args:
245
+ arg_ns = utils.join_ns(fn_def.get_ns(), node.args.args[0].arg)
246
+ arg_def = self.def_manager.get(arg_ns)
247
+ if not arg_def:
248
+ arg_def = self.def_manager.create(arg_ns, utils.constants.NAME_DEF)
249
+ arg_def.get_name_pointer().add(current_def.get_ns())
250
+
251
+ self.scope_manager.handle_assign(fn_def.get_ns(), arg_def.get_name(), arg_def)
252
+ node.args.args = node.args.args[1:]
253
+
254
+ for pos, arg in enumerate(node.args.args):
255
+ arg_ns = utils.join_ns(fn_def.get_ns(), arg.arg)
256
+ name_pointer.add_pos_arg(pos, arg.arg, arg_ns)
257
+ defs_to_create.append(arg_ns)
258
+
259
+ for arg in node.args.kwonlyargs:
260
+ arg_ns = utils.join_ns(fn_def.get_ns(), arg.arg)
261
+ # TODO: add_name_arg function
262
+ name_pointer.add_name_arg(arg.arg, arg_ns)
263
+ defs_to_create.append(arg_ns)
264
+
265
+ # TODO: Add support for kwargs and varargs
266
+ #if node.args.kwarg:
267
+ # pass
268
+ #if node.args.vararg:
269
+ # pass
270
+
271
+ for arg_ns in defs_to_create:
272
+ arg_def = self.def_manager.get(arg_ns)
273
+ if not arg_def:
274
+ arg_def = self.def_manager.create(arg_ns, utils.constants.NAME_DEF)
275
+
276
+ self.scope_manager.handle_assign(fn_def.get_ns(), arg_def.get_name(), arg_def)
277
+
278
+ # has a default
279
+ arg_name = arg_ns.split(".")[-1]
280
+ if defaults.get(arg_name, None):
281
+ for default in defaults[arg_name]:
282
+ if isinstance(default, Definition):
283
+ arg_def.get_name_pointer().add(default.get_ns())
284
+ if default.is_function_def():
285
+ arg_def.get_name_pointer().add(default.get_ns())
286
+ else:
287
+ arg_def.merge(default)
288
+ else:
289
+ arg_def.get_lit_pointer().add(default)
290
+ return fn_def
291
+
292
+ def visit_AsyncFunctionDef(self, node):
293
+ self.visit_FunctionDef(node)
294
+
295
+ def visit_FunctionDef(self, node):
296
+ fn_def = self._handle_function_def(node, node.name)
297
+
298
+ super().visit_FunctionDef(node)
299
+
300
+ def visit_For(self, node):
301
+ # just create the definition for target
302
+ if isinstance(node.target, ast.Name):
303
+ target_ns = utils.join_ns(self.current_ns, node.target.id)
304
+ if not self.def_manager.get(target_ns):
305
+ defi = self.def_manager.create(target_ns, utils.constants.NAME_DEF)
306
+ self.scope_manager.get_scope(self.current_ns).add_def(node.target.id, defi)
307
+ super().visit_For(node)
308
+
309
+ def visit_Assign(self, node):
310
+ self._visit_assign(node.value, node.targets)
311
+
312
+ def visit_Return(self, node):
313
+ self._visit_return(node)
314
+
315
+ def visit_Yield(self, node):
316
+ self._visit_return(node)
317
+
318
+ def visit_Call(self, node):
319
+ self.visit(node.func)
320
+ # if it is not a name there's nothing we can do here
321
+ # ModuleVisitor will be able to resolve those calls
322
+ # since it'll have the name tracking information
323
+ if not isinstance(node.func, ast.Name):
324
+ return
325
+
326
+ fullns = utils.join_ns(self.current_ns, node.func.id)
327
+
328
+ defi = self.scope_manager.get_def(self.current_ns, node.func.id)
329
+ if not defi:
330
+ return
331
+
332
+ if defi.get_type() == utils.constants.CLS_DEF:
333
+ defi = self.def_manager.get(utils.join_ns(defi.get_ns(), utils.constants.CLS_INIT))
334
+ if not defi:
335
+ return
336
+
337
+ self.iterate_call_args(defi, node)
338
+
339
+ def visit_Lambda(self, node):
340
+ # The name of a lambda is defined by the counter of the current scope
341
+ current_scope = self.scope_manager.get_scope(self.current_ns)
342
+ lambda_counter = current_scope.inc_lambda_counter()
343
+ lambda_name = utils.get_lambda_name(lambda_counter)
344
+ lambda_full_ns = utils.join_ns(self.current_ns, lambda_name)
345
+
346
+ # create a scope for the lambda
347
+ self.scope_manager.create_scope(lambda_full_ns, current_scope)
348
+ lambda_def = self._handle_function_def(node, lambda_name)
349
+ # add it to the current scope
350
+ current_scope.add_def(lambda_name, lambda_def)
351
+
352
+ super().visit_Lambda(node, lambda_name)
353
+
354
+ def visit_ClassDef(self, node):
355
+ # create a definition for the class (node.name)
356
+ cls_def = self.def_manager.handle_class_def(self.current_ns, node.name)
357
+
358
+ mod = self.module_manager.get(self.modname)
359
+ if not mod:
360
+ mod = self.module_manager.create(self.modname, self.filename)
361
+ mod.add_method(cls_def.get_ns(), node.lineno, self._get_last_line(node))
362
+
363
+ # iterate bases to compute MRO for the class
364
+ cls = self.class_manager.get(cls_def.get_ns())
365
+ if not cls:
366
+ cls = self.class_manager.create(cls_def.get_ns(), self.modname)
367
+
368
+ super().visit_ClassDef(node)
369
+
370
+ def analyze(self):
371
+ if not self.import_manager.get_node(self.modname):
372
+ self.import_manager.create_node(self.modname)
373
+ self.import_manager.set_filepath(self.modname, self.filename)
374
+
375
+ self.visit(ast.parse(self.contents, self.filename))
pycg/pycg.py ADDED
@@ -0,0 +1,229 @@
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 os
22
+ import ast
23
+
24
+ from pycg.processing.preprocessor import PreProcessor
25
+ from pycg.processing.postprocessor import PostProcessor
26
+ from pycg.processing.cgprocessor import CallGraphProcessor
27
+ from pycg.processing.keyerrprocessor import KeyErrProcessor
28
+
29
+ from pycg.machinery.scopes import ScopeManager
30
+ from pycg.machinery.definitions import DefinitionManager
31
+ from pycg.machinery.imports import ImportManager
32
+ from pycg.machinery.classes import ClassManager
33
+ from pycg.machinery.callgraph import CallGraph
34
+ from pycg.machinery.key_err import KeyErrors
35
+ from pycg.machinery.modules import ModuleManager
36
+ from pycg import utils
37
+
38
+ class CallGraphGenerator(object):
39
+ def __init__(self, entry_points, package, max_iter, operation):
40
+ self.entry_points = entry_points
41
+ self.package = package
42
+ self.state = None
43
+ self.max_iter = max_iter
44
+ self.operation = operation
45
+ self.setUp()
46
+
47
+ def setUp(self):
48
+ self.import_manager = ImportManager()
49
+ self.scope_manager = ScopeManager()
50
+ self.def_manager = DefinitionManager()
51
+ self.class_manager = ClassManager()
52
+ self.module_manager = ModuleManager()
53
+ self.cg = CallGraph()
54
+ self.key_errs = KeyErrors()
55
+
56
+ def extract_state(self):
57
+ state = {}
58
+ state["defs"] = {}
59
+ for key, defi in self.def_manager.get_defs().items():
60
+ state["defs"][key] = {
61
+ "names": defi.get_name_pointer().get().copy(),
62
+ "lit": defi.get_lit_pointer().get().copy()
63
+ }
64
+
65
+ state["scopes"] = {}
66
+ for key, scope in self.scope_manager.get_scopes().items():
67
+ state["scopes"][key] = set([x.get_ns() for (_, x) in scope.get_defs().items()])
68
+
69
+ state["classes"] = {}
70
+ for key, ch in self.class_manager.get_classes().items():
71
+ state["classes"][key] = ch.get_mro().copy()
72
+ return state
73
+
74
+ def reset_counters(self):
75
+ for key, scope in self.scope_manager.get_scopes().items():
76
+ scope.reset_counters()
77
+
78
+ def has_converged(self):
79
+ if not self.state:
80
+ return False
81
+
82
+ curr_state = self.extract_state()
83
+
84
+ # check defs
85
+ for key, defi in curr_state["defs"].items():
86
+ if not key in self.state["defs"]:
87
+ return False
88
+ if defi["names"] != self.state["defs"][key]["names"]:
89
+ return False
90
+ if defi["lit"] != self.state["defs"][key]["lit"]:
91
+ return False
92
+
93
+ # check scopes
94
+ for key, scope in curr_state["scopes"].items():
95
+ if not key in self.state["scopes"]:
96
+ return False
97
+ if scope != self.state["scopes"][key]:
98
+ return False
99
+
100
+ # check classes
101
+ for key, ch in curr_state["classes"].items():
102
+ if not key in self.state["classes"]:
103
+ return False
104
+ if ch != self.state["classes"][key]:
105
+ return False
106
+
107
+ return True
108
+
109
+ def remove_import_hooks(self):
110
+ self.import_manager.remove_hooks()
111
+
112
+ def tearDown(self):
113
+ self.remove_import_hooks()
114
+
115
+ def _get_mod_name(self, entry, pkg):
116
+ # We do this because we want __init__ modules to
117
+ # only contain the parent module
118
+ # since pycg can't differentiate between functions
119
+ # coming from __init__ files.
120
+
121
+ input_mod = utils.to_mod_name(
122
+ os.path.relpath(entry, pkg))
123
+ if input_mod.endswith("__init__"):
124
+ input_mod = ".".join(input_mod.split(".")[:-1])
125
+
126
+ return input_mod
127
+
128
+ def do_pass(self, cls, install_hooks=False, *args, **kwargs):
129
+ modules_analyzed = set()
130
+ for entry_point in self.entry_points:
131
+ input_pkg = self.package
132
+ input_mod = self._get_mod_name(entry_point, input_pkg)
133
+ input_file = os.path.abspath(entry_point)
134
+
135
+ if not input_mod:
136
+ continue
137
+
138
+ if not input_pkg:
139
+ input_pkg = os.path.dirname(input_file)
140
+
141
+ if not input_mod in modules_analyzed:
142
+ if install_hooks:
143
+ self.import_manager.set_pkg(input_pkg)
144
+ self.import_manager.install_hooks()
145
+
146
+ processor = cls(input_file, input_mod,
147
+ modules_analyzed=modules_analyzed, *args, **kwargs)
148
+ processor.analyze()
149
+ modules_analyzed = modules_analyzed.union(processor.get_modules_analyzed())
150
+
151
+ if install_hooks:
152
+ self.remove_import_hooks()
153
+
154
+ def analyze(self):
155
+ self.do_pass(PreProcessor, True,
156
+ self.import_manager, self.scope_manager, self.def_manager,
157
+ self.class_manager, self.module_manager)
158
+ self.def_manager.complete_definitions()
159
+
160
+ iter_cnt = 0
161
+ while (self.max_iter < 0 or iter_cnt < self.max_iter) and (not self.has_converged()):
162
+ self.state = self.extract_state()
163
+ self.reset_counters()
164
+ self.do_pass(PostProcessor, False,
165
+ self.import_manager, self.scope_manager, self.def_manager,
166
+ self.class_manager, self.module_manager)
167
+
168
+ self.def_manager.complete_definitions()
169
+ iter_cnt += 1
170
+
171
+ self.reset_counters()
172
+ if self.operation == utils.constants.CALL_GRAPH_OP:
173
+ self.do_pass(CallGraphProcessor, False,
174
+ self.import_manager, self.scope_manager, self.def_manager,
175
+ self.class_manager, self.module_manager, call_graph=self.cg)
176
+ elif self.operation == utils.constants.KEY_ERR_OP:
177
+ self.do_pass(KeyErrProcessor, False,
178
+ self.import_manager, self.scope_manager, self.def_manager,
179
+ self.class_manager, self.key_errs)
180
+ else:
181
+ raise Exception("Invalid operation: " + self.operation)
182
+
183
+
184
+ def output(self):
185
+ return self.cg.get()
186
+
187
+ def output_key_errs(self):
188
+ return self.key_errs.get()
189
+
190
+ def output_edges(self):
191
+ return self.key_errors
192
+
193
+ def output_edges(self):
194
+ return self.cg.get_edges()
195
+
196
+ def _generate_mods(self, mods):
197
+ res = {}
198
+ for mod, node in mods.items():
199
+ res[mod] = {
200
+ "filename": os.path.relpath(node.get_filename(), self.package)\
201
+ if node.get_filename() else None,
202
+ "methods": node.get_methods()
203
+ }
204
+ return res
205
+
206
+ def output_internal_mods(self):
207
+ return self._generate_mods(self.module_manager.get_internal_modules())
208
+
209
+ def output_external_mods(self):
210
+ return self._generate_mods(self.module_manager.get_external_modules())
211
+
212
+ def output_functions(self):
213
+ functions = []
214
+ for ns, defi in self.def_manager.get_defs().items():
215
+ if defi.is_function_def():
216
+ functions.append(ns)
217
+ return functions
218
+
219
+ def output_classes(self):
220
+ classes = {}
221
+ for cls, node in self.class_manager.get_classes().items():
222
+ classes[cls] = {
223
+ "mro": node.get_mro(),
224
+ "module": node.get_module()
225
+ }
226
+ return classes
227
+
228
+ def get_as_graph(self):
229
+ return self.def_manager.get_defs().items()
pycg/utils/__init__.py ADDED
@@ -0,0 +1,22 @@
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
+ from .common import *
22
+ from . import constants
pycg/utils/common.py ADDED
@@ -0,0 +1,39 @@
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 os
22
+
23
+ def get_lambda_name(counter):
24
+ return "<lambda{}>".format(counter)
25
+
26
+ def get_dict_name(counter):
27
+ return "<dict{}>".format(counter)
28
+
29
+ def get_list_name(counter):
30
+ return "<list{}>".format(counter)
31
+
32
+ def get_int_name(counter):
33
+ return "<int{}>".format(counter)
34
+
35
+ def join_ns(*args):
36
+ return ".".join([arg for arg in args])
37
+
38
+ def to_mod_name(name, package=None):
39
+ return os.path.splitext(name)[0].replace("/", ".")